diff --git a/go.mod b/go.mod index 9f114d02879..3feea776fd2 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/openshift/installer go 1.17 require ( - cloud.google.com/go v0.79.0 + cloud.google.com/go v0.81.0 github.com/AlecAivazis/survey/v2 v2.2.12 github.com/Azure/azure-sdk-for-go v51.2.0+incompatible github.com/Azure/go-autorest/autorest v0.11.18 @@ -31,7 +31,7 @@ require ( github.com/go-playground/validator/v10 v10.2.0 github.com/golang/mock v1.6.0 github.com/golang/protobuf v1.5.2 - github.com/google/go-cmp v0.5.5 + github.com/google/go-cmp v0.5.6 github.com/google/uuid v1.2.0 github.com/gophercloud/gophercloud v0.19.0 github.com/gophercloud/utils v0.0.0-20210720165645-8a3ad2ad9e70 @@ -44,7 +44,6 @@ require ( github.com/hashicorp/terraform v0.14.6 github.com/hashicorp/terraform-plugin-sdk v1.16.0 github.com/hashicorp/terraform-provider-google v1.20.1-0.20200922000057-78da461b151a - github.com/hashicorp/terraform-provider-kubernetes v1.13.3 github.com/hashicorp/terraform-provider-vsphere v1.24.3 github.com/libvirt/libvirt-go v5.10.0+incompatible github.com/metal3-io/baremetal-operator v0.0.0-20211201170610-92ffa60c683d @@ -52,7 +51,7 @@ require ( github.com/metal3-io/baremetal-operator/pkg/hardwareutils v0.0.0 github.com/mitchellh/cli v1.1.2 github.com/openshift-metal3/terraform-provider-ironic v0.2.7 - github.com/openshift/api v0.0.0-20211119153416-313e51eab8c8 + github.com/openshift/api v0.0.0-20211210181228-6e0b1eb97188 github.com/openshift/client-go v0.0.0-20211025111749-96ca2abfc56c github.com/openshift/cloud-credential-operator v0.0.0-20200316201045-d10080b52c9e github.com/openshift/cluster-api-provider-alibaba v0.0.0-20211123142315-d16daa4e6349 @@ -68,7 +67,7 @@ require ( github.com/pkg/errors v0.9.1 github.com/pkg/sftp v1.10.1 github.com/prometheus/client_golang v1.11.0 - github.com/prometheus/common v0.26.0 + github.com/prometheus/common v0.28.0 github.com/shurcooL/vfsgen v0.0.0-20181202132449-6a9ea43bcacd github.com/sirupsen/logrus v1.8.1 github.com/spf13/cobra v1.2.1 @@ -84,22 +83,22 @@ require ( github.com/vincent-petithory/dataurl v0.0.0-20191104211930-d1553a71de50 github.com/vmware/govmomi v0.24.0 github.com/zclconf/go-cty v1.8.1 - golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 + golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 - golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43 - golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c + golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f + golang.org/x/sys v0.0.0-20211029165221-6e7872819dc8 google.golang.org/api v0.44.0 - google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c - google.golang.org/grpc v1.38.0 + google.golang.org/genproto v0.0.0-20210831024726-fe130286e0e2 + google.golang.org/grpc v1.40.0 gopkg.in/ini.v1 v1.62.0 gopkg.in/yaml.v2 v2.4.0 - k8s.io/api v0.22.2 - k8s.io/apiextensions-apiserver v0.22.2 - k8s.io/apimachinery v0.22.2 + k8s.io/api v0.23.0 + k8s.io/apiextensions-apiserver v0.23.0 + k8s.io/apimachinery v0.23.0 k8s.io/client-go v12.0.0+incompatible k8s.io/klog v1.0.0 - k8s.io/klog/v2 v2.9.0 - k8s.io/utils v0.0.0-20210819203725-bdf08cb9a70a + k8s.io/klog/v2 v2.30.0 + k8s.io/utils v0.0.0-20210930125809-cb0fa318a74b sigs.k8s.io/cluster-api-provider-aws v0.0.0 sigs.k8s.io/cluster-api-provider-openstack v0.0.0 sigs.k8s.io/controller-tools v0.7.0 @@ -108,7 +107,6 @@ require ( require ( cloud.google.com/go/bigtable v1.5.0 // indirect cloud.google.com/go/storage v1.11.0 // indirect - github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect github.com/Azure/go-autorest/autorest/azure/cli v0.4.2 // indirect github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect @@ -131,7 +129,6 @@ require ( github.com/IBM/push-notifications-go-sdk v0.0.0-20210310100607-5790b96c47f5 // indirect github.com/IBM/schematics-go-sdk v0.0.2 // indirect github.com/IBM/secrets-manager-go-sdk v0.1.19 // indirect - github.com/MakeNowJust/heredoc v1.0.0 // indirect github.com/Masterminds/goutils v1.1.0 // indirect github.com/Masterminds/semver v1.5.0 // indirect github.com/Masterminds/sprig v2.22.0+incompatible // indirect @@ -195,18 +192,15 @@ require ( github.com/eapache/go-resiliency v1.2.0 // indirect github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 // indirect github.com/eapache/queue v1.1.0 // indirect - github.com/evanphx/json-patch v4.11.0+incompatible // indirect - github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d // indirect - github.com/fatih/camelcase v1.0.0 // indirect - github.com/fatih/color v1.10.0 // indirect + github.com/evanphx/json-patch v4.12.0+incompatible // indirect + github.com/fatih/color v1.12.0 // indirect github.com/form3tech-oss/jwt-go v3.2.3+incompatible // indirect - github.com/fsnotify/fsnotify v1.4.9 // indirect + github.com/fsnotify/fsnotify v1.5.1 // indirect github.com/gammazero/deque v0.0.0-20190130191400-2afb3858e9c7 // indirect github.com/gammazero/workerpool v0.0.0-20190406235159-88d534f22b56 // indirect - github.com/go-errors/errors v1.0.1 // indirect github.com/go-kit/kit v0.10.0 // indirect github.com/go-logfmt/logfmt v0.5.0 // indirect - github.com/go-logr/logr v0.4.0 // indirect + github.com/go-logr/logr v1.2.0 // indirect github.com/go-openapi/analysis v0.19.5 // indirect github.com/go-openapi/errors v0.19.8 // indirect github.com/go-openapi/jsonpointer v0.19.5 // indirect @@ -220,22 +214,19 @@ require ( github.com/go-playground/locales v0.13.0 // indirect github.com/go-playground/universal-translator v0.17.0 // indirect github.com/go-stack/stack v1.8.0 // indirect - github.com/gobuffalo/flect v0.2.2 // indirect + github.com/gobuffalo/flect v0.2.3 // indirect github.com/gofrs/uuid v3.3.0+incompatible // indirect github.com/gogap/errors v0.0.0-20160523102334-149c546090d0 // indirect github.com/gogap/stack v0.0.0-20150131034635-fef68dddd4f8 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/snappy v0.0.1 // indirect - github.com/google/btree v1.0.1 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/gofuzz v1.2.0 // indirect github.com/google/martian v2.1.1-0.20190517191504-25dcb96d9e51+incompatible // indirect github.com/google/renameio v1.0.0 // indirect - github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/googleapis/gax-go/v2 v2.0.5 // indirect github.com/googleapis/gnostic v0.5.5 // indirect - github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect github.com/hashicorp/errwrap v1.0.0 // indirect github.com/hashicorp/go-checkpoint v0.5.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect @@ -260,14 +251,13 @@ require ( github.com/hokaccha/go-prettyjson v0.0.0-20170213120834-e6b9231a2b1c // indirect github.com/hooklift/iso9660 v1.0.0 // indirect github.com/huandu/xstrings v1.3.2 // indirect - github.com/imdario/mergo v0.3.11 // indirect + github.com/imdario/mergo v0.3.12 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/jcmturner/gofork v1.0.0 // indirect github.com/jen20/awspolicyequivalence v1.1.0 // indirect - github.com/jinzhu/copier v0.0.0-20190924061706-b57f9002281a // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect - github.com/json-iterator/go v1.1.11 // indirect + github.com/json-iterator/go v1.1.12 // indirect github.com/jstemmer/go-junit-report v0.9.1 // indirect github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 // indirect github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect @@ -278,7 +268,6 @@ require ( github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.2.1 // indirect github.com/libvirt/libvirt-go-xml v5.10.0+incompatible // indirect - github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect github.com/mailru/easyjson v0.7.6 // indirect github.com/masterzen/simplexml v0.0.0-20190410153822-31eea3082786 // indirect github.com/masterzen/winrm v0.0.0-20200615185753-c42b5136ff88 // indirect @@ -297,11 +286,8 @@ require ( github.com/mitchellh/mapstructure v1.4.1 // indirect github.com/mitchellh/panicwrap v1.0.0 // indirect github.com/mitchellh/reflectwalk v1.0.1 // indirect - github.com/moby/spdystream v0.2.0 // indirect - github.com/moby/term v0.0.0-20210610120745-9d4ed1856297 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.1 // indirect - github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect github.com/nicksnyder/go-i18n v1.10.0 // indirect github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect github.com/oklog/run v1.1.0 // indirect @@ -311,7 +297,6 @@ require ( github.com/openshift/cluster-api v0.0.0-20190805113604-f8de78af80fc // indirect github.com/packer-community/winrmcp v0.0.0-20180921211025-c76d91c1e7db // indirect github.com/pelletier/go-toml v1.9.3 // indirect - github.com/peterbourgon/diskv v2.0.1+incompatible // indirect github.com/pierrec/lz4 v2.6.1+incompatible // indirect github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect @@ -322,8 +307,6 @@ require ( github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 // indirect github.com/rickb777/date v1.12.5-0.20200422084442-6300e543c4d9 // indirect github.com/rickb777/plural v1.2.0 // indirect - github.com/robfig/cron v1.2.0 // indirect - github.com/russross/blackfriday v1.5.2 // indirect github.com/satori/go.uuid v1.2.0 // indirect github.com/satori/uuid v1.2.0 // indirect github.com/shopspring/decimal v1.2.0 // indirect @@ -345,15 +328,14 @@ require ( github.com/zclconf/go-cty-yaml v1.0.2 // indirect go.mongodb.org/mongo-driver v1.5.1 // indirect go.opencensus.io v0.22.5 // indirect - go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5 // indirect golang.org/x/mod v0.4.2 // indirect - golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 // indirect - golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d // indirect - golang.org/x/text v0.3.6 // indirect + golang.org/x/net v0.0.0-20210825183410-e898025ed96a // indirect + golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b // indirect + golang.org/x/text v0.3.7 // indirect golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac // indirect - golang.org/x/tools v0.1.2 // indirect + golang.org/x/tools v0.1.6-0.20210820212750-d4cc65f0b2ff // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect - gomodules.xyz/jsonpatch/v2 v2.1.0 // indirect + gomodules.xyz/jsonpatch/v2 v2.2.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/protobuf v1.27.1 // indirect gopkg.in/go-playground/validator.v9 v9.31.0 // indirect @@ -366,16 +348,12 @@ require ( gopkg.in/resty.v1 v1.12.0 // indirect gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect honnef.co/go/tools v0.0.1-2020.1.6 // indirect - k8s.io/cli-runtime v0.21.0-rc.0 // indirect - k8s.io/component-base v0.22.2 // indirect - k8s.io/kube-aggregator v0.22.0-rc.0 // indirect - k8s.io/kube-openapi v0.0.0-20210421082810-95288971da7e // indirect - k8s.io/kubectl v0.22.0 // indirect - sigs.k8s.io/controller-runtime v0.9.7 // indirect - sigs.k8s.io/kustomize/api v0.8.5 // indirect - sigs.k8s.io/kustomize/kyaml v0.10.15 // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.1.2 // indirect - sigs.k8s.io/yaml v1.2.0 // indirect + k8s.io/component-base v0.23.0 // indirect + k8s.io/kube-openapi v0.0.0-20211115234752-e816edb12b65 // indirect + sigs.k8s.io/controller-runtime v0.11.0 // indirect + sigs.k8s.io/json v0.0.0-20211020170558-c049b76a60c6 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.2.0 // indirect + sigs.k8s.io/yaml v1.3.0 // indirect ) replace ( @@ -389,7 +367,7 @@ replace ( github.com/metal3-io/baremetal-operator => github.com/openshift/baremetal-operator v0.0.0-20211201170610-92ffa60c683d // Use OpenShift fork github.com/metal3-io/baremetal-operator/apis => github.com/openshift/baremetal-operator/apis v0.0.0-20211201170610-92ffa60c683d // Use OpenShift fork github.com/metal3-io/baremetal-operator/pkg/hardwareutils => github.com/openshift/baremetal-operator/pkg/hardwareutils v0.0.0-20211201170610-92ffa60c683d // Use OpenShift fork - github.com/openshift/client-go => github.com/openshift/client-go v0.0.0-20200929181438-91d71ef2122c // Pin client-go + github.com/openshift/client-go => github.com/openshift/client-go v0.0.0-20211209144617-7385dd6338e3 // Pin client-go github.com/openshift/machine-config-operator => github.com/openshift/machine-config-operator v0.0.1-0.20201009041932-4fe8559913b8 // Pin MCO so it doesn't get downgraded github.com/spf13/afero => github.com/spf13/afero v1.2.2 github.com/terraform-providers/terraform-provider-aws => github.com/openshift/terraform-provider-aws v1.60.1-0.20211215220004-24df6d73af46 // Pin to openshift fork with tag v3.1.0-openshift-2 @@ -397,12 +375,11 @@ replace ( github.com/terraform-providers/terraform-provider-azurestack => github.com/openshift/terraform-provider-azurestack v0.10.0-openshift // Use OpenShift fork github.com/terraform-providers/terraform-provider-google v1.20.1-0.20200623174414-27107f2ee160 => github.com/openshift/terraform-providers-terraform-provider-google v1.20.1-0.20211201190933-7b79c6d1afc8 // Pin to 3.27.0-openshift github.com/terraform-providers/terraform-provider-ignition/v2 => github.com/community-terraform-providers/terraform-provider-ignition/v2 v2.1.0 - k8s.io/client-go => k8s.io/client-go v0.22.0 - k8s.io/kubectl => k8s.io/kubectl v0.21.0-rc.0 + k8s.io/client-go => k8s.io/client-go v0.23.0 + k8s.io/kubectl => k8s.io/kubectl v0.23.0 sigs.k8s.io/cluster-api-provider-aws => github.com/openshift/cluster-api-provider-aws v0.2.1-0.20210121023454-5ffc5f422a80 sigs.k8s.io/cluster-api-provider-azure => github.com/openshift/cluster-api-provider-azure v0.1.0-alpha.3.0.20210626224711-5d94c794092f // Indirect dependency through MAO from cluster API providers sigs.k8s.io/cluster-api-provider-openstack => github.com/openshift/cluster-api-provider-openstack v0.0.0-20211111204942-611d320170af - sigs.k8s.io/controller-runtime => sigs.k8s.io/controller-runtime v0.9.0-alpha.1 sigs.k8s.io/controller-tools => sigs.k8s.io/controller-tools v0.3.1-0.20200617211605-651903477185 ) diff --git a/go.sum b/go.sum index 09fc401e293..630eeac0506 100644 --- a/go.sum +++ b/go.sum @@ -42,7 +42,6 @@ github.com/Azure/azure-sdk-for-go v51.2.0+incompatible h1:qQNk//OOHK0GZcgMMgdJ4t github.com/Azure/azure-sdk-for-go v51.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= github.com/Azure/go-ansiterm v0.0.0-20210608223527-2377c96fe795/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= -github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Azure/go-autorest v11.7.1+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= @@ -56,7 +55,6 @@ github.com/Azure/go-autorest/autorest/azure/auth v0.4.1/go.mod h1:5TgH20II424SXI github.com/Azure/go-autorest/autorest/azure/cli v0.2.0/go.mod h1:WWTbGPvkAg3I4ms2j2s+Zr5xCGwGqTQh+6M2ZqOczkE= github.com/Azure/go-autorest/autorest/azure/cli v0.3.1/go.mod h1:ZG5p860J94/0kI9mNJVoIoLgXcirM2gF5i2kWloofxw= github.com/Azure/go-autorest/autorest/azure/cli v0.4.0/go.mod h1:JljT387FplPzBA31vUcvsetLKF3pec5bdAxjVU4kI2s= -github.com/Azure/go-autorest/autorest/azure/cli v0.4.1/go.mod h1:JfDgiIO1/RPu6z42AdQTyjOoCM2MFhLqSBDvMEkDgcg= github.com/Azure/go-autorest/autorest/azure/cli v0.4.2 h1:dMOmEJfkLKW/7JsokJqkyoYSgmR08hi9KrhjZb+JALY= github.com/Azure/go-autorest/autorest/azure/cli v0.4.2/go.mod h1:7qkJkT+j6b+hIpzMOwPChJhTqS8VbsqqgULzMNRugoM= github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= @@ -85,7 +83,6 @@ github.com/ChrisTrenkamp/goxpath v0.0.0-20190607011252-c5096ec8773d/go.mod h1:nu github.com/DataDog/datadog-go v2.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= github.com/Djarvur/go-err113 v0.0.0-20200511133814-5174e21577d5/go.mod h1:4UJr5HIiMZrwgkSPdsjy2uOQExX/WEILpIrO9UPGuXs= -github.com/Djarvur/go-err113 v0.1.0/go.mod h1:4UJr5HIiMZrwgkSPdsjy2uOQExX/WEILpIrO9UPGuXs= github.com/IBM-Cloud/bluemix-go v0.0.0-20210611051827-cdc80c935c05 h1:b/epmuvf99xhUlf81l0r/ciONJSjoUs78t+BC7lCcvI= github.com/IBM-Cloud/bluemix-go v0.0.0-20210611051827-cdc80c935c05/go.mod h1:kqTYO0mts71aa8PVwviaKlCKYud/NbEkFIqU8aHH3/g= github.com/IBM-Cloud/ibm-cloud-cli-sdk v0.5.3/go.mod h1:RiUvKuHKTBmBApDMUQzBL14pQUGKcx/IioKQPIcRQjs= @@ -139,7 +136,6 @@ github.com/InVisionApp/go-health v2.1.0+incompatible/go.mod h1:/+Gv1o8JUsrjC6pi6 github.com/Jeffail/gabs v1.1.1/go.mod h1:6xMvQMK4k33lb7GUUpaAPh6nKMmemQeg5d4gn7/bOXc= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= github.com/MakeNowJust/heredoc v0.0.0-20170808103936-bb23615498cd/go.mod h1:64YHyfSL2R96J44Nlwm39UHepQbyR5q10x7iYa1ks2E= -github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= github.com/Masterminds/goutils v1.1.0 h1:zukEsf/1JZwCMgHiK3GZftabmxiCw4apj3a28RPBiVg= github.com/Masterminds/goutils v1.1.0/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= @@ -263,7 +259,6 @@ github.com/aliyun/fc-go-sdk v0.0.0-20200925033337-c013428cbe21/go.mod h1:X4Pc3TF github.com/aliyun/terraform-provider-alicloud v1.132.0 h1:neBCKJGbL7XJBkzySQX7GJ2M98a7tju3y8XRY4BJxHA= github.com/aliyun/terraform-provider-alicloud v1.132.0/go.mod h1:7Ac42rNclVHQRkt91rPHJbHY4Ro1UzbU+sQ3xT9m5ds= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= -github.com/andybalholm/brotli v1.0.0/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= github.com/andybalholm/brotli v1.0.1 h1:KqhlKozYbRtJvsPrrEeXcO+N2l6NYT5A2QAFmSULpEc= github.com/andybalholm/brotli v1.0.1/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= github.com/andybalholm/crlf v0.0.0-20171020200849-670099aa064f/go.mod h1:k8feO4+kXDxro6ErPXBRTJ/ro2mf0SsFG8s7doP9kJE= @@ -274,6 +269,7 @@ github.com/antchfx/xpath v1.1.2/go.mod h1:Yee4kTMuNiPYJ7nSNorELQMr1J33uOpXDMByNY github.com/antchfx/xquery v0.0.0-20180515051857-ad5b8c7a47b0 h1:JaCC8jz0zdMLk2m+qCCVLLLM/PL93p84w4pK3aJWj60= github.com/antchfx/xquery v0.0.0-20180515051857-ad5b8c7a47b0/go.mod h1:LzD22aAzDP8/dyiCKFp31He4m2GPjl0AFyzDtZzUu9M= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20210826220005-b48c857c3a0e/go.mod h1:F7bn7fEU90QkQ3tnmaTx3LTKLEDqnwWODIYppRQ5hnY= github.com/apache/openwhisk-client-go v0.0.0-20200201143223-a804fb82d105 h1:k1wP1gZMrNJeXTz6a+3010NKC/ZvSffk07BzrLmYrmc= github.com/apache/openwhisk-client-go v0.0.0-20200201143223-a804fb82d105/go.mod h1:jLLKYP7+1+LFlIJW1n9U1gqeveLM1HIwa4ZHNOFxjPw= github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= @@ -293,6 +289,7 @@ github.com/apparentlymart/go-userdirs v0.0.0-20200915174352-b0c018a67c13/go.mod github.com/apparentlymart/go-versions v1.0.1 h1:ECIpSn0adcYNsBfSRwdDdz9fWlL+S/6EUd9+irwkBgU= github.com/apparentlymart/go-versions v1.0.1/go.mod h1:YF5j7IQtrOAOnsGkniupEA5bfCjzd7i14yu0shZavyM= github.com/apple/foundationdb/bindings/go v0.0.0-20190411004307-cd5c9d91fad2/go.mod h1:OMVSB21p9+xQUIqlGizHPZfjK+SHws1ht+ZytVDoz9U= +github.com/appscode/jsonpatch v0.0.0-20190108182946-7c0e3b262f30/go.mod h1:4AJxUpXUhv4N+ziTvIcWWXgeorXpxPZOfk9HdEVr96M= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/circbuf v0.0.0-20190214190532-5111143e8da2 h1:7Ip0wMmLHLRJdrloDxZfhMm0xrLXZS8+COSu2bXmEQs= github.com/armon/circbuf v0.0.0-20190214190532-5111143e8da2/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= @@ -323,6 +320,7 @@ github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f/go.mod github.com/beevik/etree v1.1.0 h1:T0xke/WvNtMoCqgzPhkX2r4rjY3GDZFi+FjpRZY2Jbs= github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A= github.com/benbjohnson/clock v1.0.3/go.mod h1:bGMdMPoPVvcYyt1gHDf4J2KE153Yf9BuiUKYMaxlTDM= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -330,7 +328,6 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r github.com/bflad/gopaniccheck v0.1.0/go.mod h1:ZCj2vSr7EqVeDaqVsWN4n2MwdROx1YL+LFo47TSWtsA= github.com/bflad/tfproviderdocs v0.7.0/go.mod h1:W6wVZPtBa6V5bpjaK1eJAoVCL/7B4Amfrld0dro+fHU= github.com/bflad/tfproviderlint v0.15.0/go.mod h1:0fdh7JywihC58Io8AZ+gpcmQtJggse0MCOXF2tMmnAQ= -github.com/bflad/tfproviderlint v0.18.0/go.mod h1:0fdh7JywihC58Io8AZ+gpcmQtJggse0MCOXF2tMmnAQ= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= @@ -467,7 +464,6 @@ github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7Do github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/daixiang0/gci v0.2.4/go.mod h1:+AV8KmHTGxxwp/pY84TLQfFKp2vuKXXJVzF3kD/hfR4= github.com/dave/dst v0.26.2/go.mod h1:UMDJuIRPfyUCC78eFuB+SV/WI8oDeyFDvM/JR6NI3IU= github.com/dave/gopackages v0.0.0-20170318123100-46e7023ec56e/go.mod h1:i00+b/gKdIDIxuLDFob7ustLAVqhsZRk2qVZrArELGQ= github.com/dave/jennifer v1.2.0/go.mod h1:fIb+770HOpJ2fmN9EPPKOqm1vMGhB+TwXKMZhrIygKg= @@ -536,7 +532,6 @@ github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaB 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/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= -github.com/elazarl/goproxy v0.0.0-20190911111923-ecfe977594f1 h1:yY9rWGoXv1U5pl4gxqlULARMQD7x0QG85lqEXTWysik= github.com/elazarl/goproxy v0.0.0-20190911111923-ecfe977594f1/go.mod h1:Ro8st/ElPeALwNFlcTpWmkr6IoMFfkjXAvTHpevnDsM= github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8= github.com/elazarl/goproxy/ext v0.0.0-20190911111923-ecfe977594f1/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8= @@ -544,28 +539,29 @@ github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb github.com/emicklei/go-restful v2.9.0+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/emicklei/go-restful v2.9.5+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/emicklei/go-restful v2.10.0+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= -github.com/emicklei/go-restful v2.14.2+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/emirpasic/gods v1.12.0 h1:QAUIPSaCu4G+POclxeqb3F+WPpdKqFGlw36+yOzGlrg= github.com/emirpasic/gods v1.12.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3ymbK86o= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/evanphx/json-patch v0.0.0-20190203023257-5858425f7550/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/evanphx/json-patch v0.5.2/go.mod h1:ZWS5hhDbVDyob71nXKNL0+PWn6ToqBHMikGIFbs31qQ= +github.com/evanphx/json-patch v4.0.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/evanphx/json-patch v4.1.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/evanphx/json-patch v4.5.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/evanphx/json-patch v4.11.0+incompatible h1:glyUF9yIYtMHzn8xaKw5rMhdWcwsYV8dZHIq5567/xs= github.com/evanphx/json-patch v4.11.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d h1:105gxyaGwCFad8crR9dcMQWvV9Hvulu6hwUh4tWPJnM= +github.com/evanphx/json-patch v4.12.0+incompatible h1:4onqiflcdA9EOZ4RxV643DvftH5pOlLGNtQ5lPWQu84= +github.com/evanphx/json-patch v4.12.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d/go.mod h1:ZZMPRZwes7CROmyNKgQzC3XPs6L/G2EJLHddWejkmf4= github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 h1:JWuenKqqX8nojtoVVWjGfOF9635RETekkoH6Cc9SX0A= github.com/facebookgo/stack v0.0.0-20160209184415-751773369052/go.mod h1:UbMTZqLaRiH3MsBH8va0n7s1pQYcu3uTb8G4tygF4Zg= -github.com/fatih/camelcase v1.0.0 h1:hxNvNX/xYBp0ovncs8WyWZrOrpBNub/JfaMvbURyft8= github.com/fatih/camelcase v1.0.0/go.mod h1:yN2Sb0lFhZJUdVvtELVWefmrXpuZESvPmqwoZc+/fpc= github.com/fatih/color v1.6.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= -github.com/fatih/color v1.10.0 h1:s36xzo75JdqLaaWoiEHk767eHiwo0598uUxyfiPkDsg= -github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= +github.com/fatih/color v1.12.0 h1:mRhaKNwANqRgUBGKmnI5ZxEk7QXmjQeCcuYFMX2bfcc= +github.com/fatih/color v1.12.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= @@ -582,8 +578,9 @@ github.com/frankban/quicktest v1.4.1/go.mod h1:36zfPVQyHxymz4cH7wlDmVwDrJuljRB60 github.com/frankban/quicktest v1.10.2 h1:19ARM85nVi4xH7xPXuc5eM/udya5ieh7b/Sv+d844Tk= github.com/frankban/quicktest v1.10.2/go.mod h1:K+q6oSqb0W0Ininfk863uOk1lMy69l/P6txr3mVT54s= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= +github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/fsouza/go-dockerclient v0.0.0-20171004212419-da3951ba2e9e/go.mod h1:KpcjM623fQYE9MZiTGzKhjfxXAV9wbyX2C1cyRHfhl0= github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa/go.mod h1:KnogPXtdwXqoenmZCw6S+25EAm2MkxbG0deNDu4cbSA= github.com/fvbommel/sortorder v1.0.1/go.mod h1:uk88iVf1ovNn1iLfgUVU2F9o5eO30ui720w+kxuqRs0= @@ -593,6 +590,7 @@ github.com/gammazero/deque v0.0.0-20190130191400-2afb3858e9c7/go.mod h1:GeIq9qoE github.com/gammazero/workerpool v0.0.0-20181230203049-86a96b5d5d92/go.mod h1:w9RqFVO2BM3xwWEcAB8Fwp0OviTBBEiRmSBDfbXnd3w= github.com/gammazero/workerpool v0.0.0-20190406235159-88d534f22b56 h1:VzbudKn/nvxYKOdzgkEBS6SSreRjAgoJ+ZeS4wPFkgc= github.com/gammazero/workerpool v0.0.0-20190406235159-88d534f22b56/go.mod h1:w9RqFVO2BM3xwWEcAB8Fwp0OviTBBEiRmSBDfbXnd3w= +github.com/getkin/kin-openapi v0.76.0/go.mod h1:660oXbgy5JFMKreazJaQTw7o+X00qeSyhcnluiMv+Xg= github.com/getsentry/raven-go v0.0.0-20190513200303-c977f96e1095/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ= github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ= github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= @@ -606,8 +604,6 @@ github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkPro github.com/go-bindata/go-bindata v3.1.2+incompatible/go.mod h1:xK8Dsgwmeed+BBsSy2XTopBn/8uK2HWuGSnA11C3Joo= github.com/go-critic/go-critic v0.3.5-0.20190526074819-1df300866540/go.mod h1:+sE8vrLDS2M0pZkBk0wy6+nLdKexVDrl/jBqQOTDThA= github.com/go-critic/go-critic v0.5.0/go.mod h1:4jeRh3ZAVnRYhuWdOEvwzVqLUpxMSoAT0xZ74JsTPlo= -github.com/go-critic/go-critic v0.5.2/go.mod h1:cc0+HvdE3lFpqLecgqMaJcvWWH77sLdBp+wLGPM1Yyo= -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-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4= github.com/go-git/gcfg v1.5.0/go.mod h1:5m20vg6GwYabIxaOonVkTdrILxQMpEShl1xiMF4ua+E= @@ -638,10 +634,14 @@ github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7 github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= github.com/go-logr/logr v0.2.1/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= github.com/go-logr/logr v0.3.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= -github.com/go-logr/logr v0.4.0 h1:K7/B1jt6fIBQVd4Owv2MqGQClcgf0R266+7C/QjRcLc= github.com/go-logr/logr v0.4.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= -github.com/go-logr/zapr v0.4.0 h1:uc1uML3hRYL9/ZZPdgHS/n8Nzo+eaYL/Efxkkamf7OM= +github.com/go-logr/logr v1.2.0 h1:QK40JKJyMdUDz+h+xvCsru/bJhvG0UxvePV0ufL/AcE= +github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/zapr v0.1.0/go.mod h1:tabnROwaDl0UNxkVeFRbY8bwB37GwRv0P8lg6aAiEnk= +github.com/go-logr/zapr v0.2.0/go.mod h1:qhKdvif7YF5GI9NWEpyxTSSBdGmzkNguibrdCNVPunU= github.com/go-logr/zapr v0.4.0/go.mod h1:tabnROwaDl0UNxkVeFRbY8bwB37GwRv0P8lg6aAiEnk= +github.com/go-logr/zapr v1.2.0 h1:n4JnPI1T3Qq1SFEi/F8rwLrZERp2bso19PJZDB9dayk= +github.com/go-logr/zapr v1.2.0/go.mod h1:Qa4Bsj2Vb+FAVeAKsLD8RLQ+YRJB8YDmOAKxaBQf7Ro= github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8= github.com/go-openapi/analysis v0.0.0-20180825180245-b006789cd277/go.mod h1:k70tL6pCuVxPJOHXQ+wIac1FUrvNkHolPie/cLEU6hI= @@ -662,7 +662,6 @@ github.com/go-openapi/jsonreference v0.17.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3Hfo github.com/go-openapi/jsonreference v0.18.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3HfopLOL6uZrK/VgnsK9I= github.com/go-openapi/jsonreference v0.19.2/go.mod h1:jMjeRr2HHw6nAVajTXJ4eiUwohSTlpa0o73RUL1owJc= github.com/go-openapi/jsonreference v0.19.3/go.mod h1:rjx6GuL8TTa9VaixXglHmQmIL98+wF9xc8zWvFonSJ8= -github.com/go-openapi/jsonreference v0.19.4/go.mod h1:RdybgQwPxbL4UEjuAruzK1x3nE69AqPYEJeo/TWfEeg= github.com/go-openapi/jsonreference v0.19.5 h1:1WJP/wi4OjB4iV8KVbH73rQaoialJrqv8gitZLxGLtM= github.com/go-openapi/jsonreference v0.19.5/go.mod h1:RdybgQwPxbL4UEjuAruzK1x3nE69AqPYEJeo/TWfEeg= github.com/go-openapi/loads v0.19.0/go.mod h1:72tmFy5wsWx89uEVddd0RjRWPZm92WRLhf7AC+0+OOU= @@ -692,7 +691,6 @@ github.com/go-openapi/swag v0.18.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/ github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.7/go.mod h1:ao+8BpOPyKdpQz3AOJfbeEVpLmWAvlT1IfTe5McPyhY= -github.com/go-openapi/swag v0.19.9/go.mod h1:ao+8BpOPyKdpQz3AOJfbeEVpLmWAvlT1IfTe5McPyhY= github.com/go-openapi/swag v0.19.14 h1:gm3vOOXfiuw5i9p5N9xJvfjvuofpyvLA9Wr6QfK5Fng= github.com/go-openapi/swag v0.19.14/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-openapi/validate v0.19.8 h1:YFzsdWIDfVuLvIOF+ZmKjVg1MbPJ1QgY9PihMwei1ys= @@ -742,8 +740,9 @@ github.com/gobuffalo/flect v0.1.0/go.mod h1:d2ehjJqGOH/Kjqcoz+F7jHTBbmDb38yXA598 github.com/gobuffalo/flect v0.1.1/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= github.com/gobuffalo/flect v0.1.3/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= github.com/gobuffalo/flect v0.2.0/go.mod h1:W3K3X9ksuZfir8f/LrfVtWmCDQFfayuylOJ7sz/Fj80= -github.com/gobuffalo/flect v0.2.2 h1:PAVD7sp0KOdfswjAw9BpLCU9hXo7wFSzgpQ+zNeks/A= github.com/gobuffalo/flect v0.2.2/go.mod h1:vmkQwuZYhN5Pc4ljYQZzP+1sq+NEkK+lh20jmEmX3jc= +github.com/gobuffalo/flect v0.2.3 h1:f/ZukRnSNA/DUpSNDadko7Qc0PhGvsew35p/2tu+CRY= +github.com/gobuffalo/flect v0.2.3/go.mod h1:vmkQwuZYhN5Pc4ljYQZzP+1sq+NEkK+lh20jmEmX3jc= github.com/gobuffalo/genny v0.0.0-20190329151137-27723ad26ef9/go.mod h1:rWs4Z12d1Zbf19rlsn0nurr75KqhYp52EAGGxTbBhNk= github.com/gobuffalo/genny v0.0.0-20190403191548-3ca520ef0d9e/go.mod h1:80lIj3kVJWwOrXWWMRzzdhW3DsrdjILVil/SFKBzF28= github.com/gobuffalo/genny v0.1.0/go.mod h1:XidbUqzak3lHdS//TPu2OgiFB+51Ur5f7CSnXZ/JDvo= @@ -752,7 +751,6 @@ github.com/gobuffalo/gitgen v0.0.0-20190315122116-cc086187d211/go.mod h1:vEHJk/E github.com/gobuffalo/gogen v0.0.0-20190315121717-8f38393713f5/go.mod h1:V9QVDIxsgKNZs6L2IYiGR8datgMhB577vzTDqypH360= github.com/gobuffalo/gogen v0.1.0/go.mod h1:8NTelM5qd8RZ15VjQTFkAW6qOMx5wBbW4dSCS3BY8gg= github.com/gobuffalo/gogen v0.1.1/go.mod h1:y8iBtmHmGc4qa3urIyo1shvOD8JftTtfcKi+71xfDNE= -github.com/gobuffalo/here v0.6.0/go.mod h1:wAG085dHOYqUpf+Ap+WOdrPTp5IYcDAs/x7PLa8Y5fM= github.com/gobuffalo/logger v0.0.0-20190315122211-86e12af44bc2/go.mod h1:QdxcLw541hSGtBnhUc4gaNIXRjiDppFGaDqzbrBd3v8= github.com/gobuffalo/mapi v1.0.1/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= github.com/gobuffalo/mapi v1.0.2/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= @@ -768,7 +766,6 @@ github.com/godbus/dbus v0.0.0-20190422162347-ade71ed3457e/go.mod h1:bBOAhwG1umN6 github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gofrs/flock v0.7.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= -github.com/gofrs/flock v0.8.0/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gofrs/uuid v3.3.0+incompatible h1:8K4tyRfvU1CYPgJsveYFQMhpFd/wXNM7iK6rR7UHz84= github.com/gofrs/uuid v3.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= @@ -788,7 +785,9 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69 github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20180513044358-24b0969c4cb7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191027212112-611e8accdfc9/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -839,17 +838,14 @@ github.com/golangci/gofmt v0.0.0-20181222123516-0b8337e80d98/go.mod h1:9qCChq59u github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a/go.mod h1:9qCChq59u/eW8im404Q2WWTrnBUQKjpNYKMbU4M7EFU= github.com/golangci/golangci-lint v1.18.0/go.mod h1:kaqo8l0OZKYPtjNmG4z4HrWLgcYNIJ9B9q3LWri9uLg= github.com/golangci/golangci-lint v1.29.0/go.mod h1:Iq2GFBB9OoolSDWD81m0iJ2MR4MwDVbi4eC93fO7wh0= -github.com/golangci/golangci-lint v1.31.0/go.mod h1:aMQuNCA+NDU5+4jLL5pEuFHoue0IznKE2+/GsFvvs8A= github.com/golangci/gosec v0.0.0-20190211064107-66fb7fc33547/go.mod h1:0qUabqiIQgfmlAmulqxyiGkkyF6/tOGSnY2cnPVwrzU= github.com/golangci/ineffassign v0.0.0-20190609212857-42439a7714cc/go.mod h1:e5tpTHCfVze+7EpLEozzMB3eafxo2KT5veNg1k6byQU= github.com/golangci/lint-1 v0.0.0-20190420132249-ee948d087217/go.mod h1:66R6K6P6VWk9I95jvqGxkqJxVWGFy9XlDwLwVz1RCFg= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0/go.mod h1:66R6K6P6VWk9I95jvqGxkqJxVWGFy9XlDwLwVz1RCFg= github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca/go.mod h1:tvlJhZqDe4LMs4ZHD0oMUlt9G2LWuDGoisJTBzLMV9o= github.com/golangci/misspell v0.0.0-20180809174111-950f5d19e770/go.mod h1:dEbvlSfYbMQDtrpRMQU675gSDLDNa8sCPPChZ7PhiVA= -github.com/golangci/misspell v0.3.5/go.mod h1:dEbvlSfYbMQDtrpRMQU675gSDLDNa8sCPPChZ7PhiVA= github.com/golangci/prealloc v0.0.0-20180630174525-215b22d4de21/go.mod h1:tf5+bzsHdTM0bsB7+8mt0GUMvjCgwLpTapNZHU8AajI= github.com/golangci/revgrep v0.0.0-20180526074752-d9c87f5ffaf0/go.mod h1:qOQCunEYvmd/TLamH+7LlVccLvUH5kZNhbCgTHoBbp4= -github.com/golangci/revgrep v0.0.0-20180812185044-276a5c0a1039/go.mod h1:qOQCunEYvmd/TLamH+7LlVccLvUH5kZNhbCgTHoBbp4= github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4/go.mod h1:Izgrg8RkN3rCIMLGE9CyYmU9pY2Jer6DgANEnZ/L/cQ= github.com/golangplus/testing v0.0.0-20180327235837-af21d9c3145e/go.mod h1:0AA//k/eakGydO4jKRoRL2j92ZKSzTgj9tclaCrvXHk= github.com/gonum/blas v0.0.0-20181208220705-f22b278b28ac/go.mod h1:P32wAyui1PQ58Oce/KYkOqQv8cVw1zAapXOl+dRFGbc= @@ -863,6 +859,8 @@ github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Z github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4= github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9uaxA= +github.com/google/cel-go v0.9.0/go.mod h1:U7ayypeSkw23szu4GaQTPJGx66c20mx8JklMSxrmI1w= +github.com/google/cel-spec v0.6.0/go.mod h1:Nwjgxy5CbjlPrtCWjeDjUyKMl8w41YBYGjsyDdqk0xA= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -872,8 +870,9 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= github.com/google/go-metrics-stackdriver v0.0.0-20190816035513-b52628e82e2a/go.mod h1:o93WzqysX0jP/10Y13hfL6aq9RoUvGaVdkrH5awMksE= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= @@ -893,7 +892,6 @@ github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hf github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/renameio v1.0.0 h1:xhp2CnJmgQmpJU4RY8chagahUq5mbPPAbiSQstKpVMA= github.com/google/renameio v1.0.0/go.mod h1:t/HQoYBZSsWSNK35C6CO/TpPLDVWvxOHboWUAweKUpk= -github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v0.0.0-20170306145142-6a5e28554805/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -906,6 +904,7 @@ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5m github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= github.com/googleapis/gnostic v0.1.0/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= github.com/googleapis/gnostic v0.2.0/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= +github.com/googleapis/gnostic v0.3.1/go.mod h1:on+2t9HRStVgn95RSsFWFz+6Q0Snyqv1awfrALZdbtU= github.com/googleapis/gnostic v0.4.1/go.mod h1:LRhVm6pbyptWbWbuZ38d1eyptfvIytN3ir6b65WBswg= github.com/googleapis/gnostic v0.5.1/go.mod h1:6U4PtQXGIEt/Z3h5MAT7FNofLnw9vXk2cUuW7uA/OeU= github.com/googleapis/gnostic v0.5.4/go.mod h1:TRWw1s4gxBGjSe301Dai3c7wXJAZy57+/6tawkOvqHQ= @@ -913,8 +912,6 @@ github.com/googleapis/gnostic v0.5.5 h1:9fHAtK0uDfpveeqqo1hkEZJcFvYXAiCN3UutL8F9 github.com/googleapis/gnostic v0.5.5/go.mod h1:7+EbHbldMins07ALC74bsA81Ovc97DwqyJO1AENw9kA= github.com/gookit/color v1.1.7/go.mod h1:R3ogXq2B9rTbXoSHJ1HyUVAZ3poOJHpd9nQmyGZsfvQ= github.com/gookit/color v1.2.4/go.mod h1:AhIE+pS6D4Ql0SQWbBeXPHw7gY0/sjHoA4s/n1KB7xg= -github.com/gookit/color v1.2.5/go.mod h1:AhIE+pS6D4Ql0SQWbBeXPHw7gY0/sjHoA4s/n1KB7xg= -github.com/gookit/color v1.2.9/go.mod h1:AhIE+pS6D4Ql0SQWbBeXPHw7gY0/sjHoA4s/n1KB7xg= github.com/gophercloud/gophercloud v0.17.0 h1:BgVw0saxyeHWH5us/SQe1ltp0GRnytjmOLXDA8pO77E= github.com/gophercloud/gophercloud v0.17.0/go.mod h1:wRtmUelyIIv3CSSDI47aUwbs075O6i+LY+pXsKCBsb4= github.com/gophercloud/utils v0.0.0-20200423144003-7c72efc7435d/go.mod h1:ehWUbLQJPqS0Ep+CxeD559hsm9pthPXadJNKwZkp43w= @@ -932,17 +929,14 @@ github.com/gorilla/mux v0.0.0-20191024121256-f395758b854c/go.mod h1:DVbg23sWSpFR github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gostaticanalysis/analysisutil v0.0.0-20190318220348-4088753ea4d3/go.mod h1:eEOZF4jCKGi+aprrirO9e7WKB3beBRtWgqGunKl6pKE= github.com/gostaticanalysis/analysisutil v0.0.3/go.mod h1:eEOZF4jCKGi+aprrirO9e7WKB3beBRtWgqGunKl6pKE= -github.com/gostaticanalysis/analysisutil v0.2.1/go.mod h1:18U/DLpRgIUd459wGxVHE0fRgmo1UgHDcbw7F5idXu0= -github.com/gostaticanalysis/comment v1.4.1/go.mod h1:ih6ZxzTHLdadaiSnF5WY3dxUoXfXAlTaRzuaNDlSado= github.com/gotestyourself/gotestyourself v2.2.0+incompatible/go.mod h1:zZKM6oeNM8k+FRljX1mnzVYeS8wiGgQyvST1/GafPbY= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= -github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 h1:+ngKgrYPPJrOjhax5N+uePQ0Fh1Z7PheYoUI/0nzkPA= -github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= @@ -1037,6 +1031,7 @@ github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09 github.com/hashicorp/go-version v1.3.0 h1:McDWVJIU/y+u1BRV06dPaLfLCaT7fUTJLp5r04x7iNw= github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= +github.com/hashicorp/golang-lru v0.0.0-20180201235237-0fb14efe8c47/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= 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/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= @@ -1049,7 +1044,6 @@ github.com/hashicorp/hcl/v2 v2.0.0/go.mod h1:oVVDG71tEinNGYCxinCYadcmKU9bglqW9pV github.com/hashicorp/hcl/v2 v2.1.0/go.mod h1:oVVDG71tEinNGYCxinCYadcmKU9bglqW9pV3txagJ90= github.com/hashicorp/hcl/v2 v2.3.0/go.mod h1:d+FwDBbOLvpAM3Z6J7gPj/VoAGkNe/gm352ZhjJ/Zv8= github.com/hashicorp/hcl/v2 v2.5.0/go.mod h1:bQTN5mpo+jewjJgh8jr0JUguIi7qPHUF6yIfAEN3jqY= -github.com/hashicorp/hcl/v2 v2.6.0/go.mod h1:bQTN5mpo+jewjJgh8jr0JUguIi7qPHUF6yIfAEN3jqY= github.com/hashicorp/hcl/v2 v2.8.2 h1:wmFle3D1vu0okesm8BTLVDyJ6/OL9DCLUwn0b2OptiY= github.com/hashicorp/hcl/v2 v2.8.2/go.mod h1:bQTN5mpo+jewjJgh8jr0JUguIi7qPHUF6yIfAEN3jqY= github.com/hashicorp/hil v0.0.0-20190212132231-97b3a9cdfa93/go.mod h1:n2TSygSNwsLJ76m8qFXTSc7beTb+auJxYdqrnoqwZWE= @@ -1077,17 +1071,13 @@ github.com/hashicorp/terraform-exec v0.10.0/go.mod h1:tOT8j1J8rP05bZBGWXfMyU3HkL github.com/hashicorp/terraform-exec v0.13.1 h1:Usw5mrBV0nku6QO5UhcpDCtBZRcxT3BafXtCUltUYmQ= github.com/hashicorp/terraform-exec v0.13.1/go.mod h1:vH84znKpolnS9NPiDh8xeFsZopfTHQpQKjbKbXLPVrE= github.com/hashicorp/terraform-json v0.5.0/go.mod h1:eAbqb4w0pSlRmdvl8fOyHAi/+8jnkVYN28gJkSJrLhU= -github.com/hashicorp/terraform-json v0.6.0/go.mod h1:eAbqb4w0pSlRmdvl8fOyHAi/+8jnkVYN28gJkSJrLhU= github.com/hashicorp/terraform-json v0.9.0 h1:WE7+Wt93W93feOiCligElSyS0tlDzwZUtJuDGIBr8zg= github.com/hashicorp/terraform-json v0.9.0/go.mod h1:3defM4kkMfttwiE7VakJDwCd4R+umhSQnvJwORXbprE= github.com/hashicorp/terraform-plugin-sdk/v2 v2.0.0/go.mod h1:xOf85UtHJ0/9/EF3eKgZFlJ6feN8sDtjQRWRHhimCUw= github.com/hashicorp/terraform-plugin-test/v2 v2.2.0 h1:Csqv/DStF0KYuDPAaogVyN5yhLO4Wug9cDMrVmYV7KY= github.com/hashicorp/terraform-plugin-test/v2 v2.2.0/go.mod h1:/FHxBiZaMxizcYBoVgyRMMYORiZQKE607BsVovGcDTg= -github.com/hashicorp/terraform-provider-google v1.20.1-0.20200824213103-e32ba28ec398/go.mod h1:qc51ZGlewTr4W9ho2SxvlPETQmDyeN/kC27b1mTQuQw= github.com/hashicorp/terraform-provider-google v1.20.1-0.20200922000057-78da461b151a h1:J7d8jVFwOK4MywoTQJrY9z0C00ZcUXR98PVeBylMX/I= github.com/hashicorp/terraform-provider-google v1.20.1-0.20200922000057-78da461b151a/go.mod h1:4JrXtiICFM47r7o5k5wNOynNNog+L5L9PNCsfaKFheU= -github.com/hashicorp/terraform-provider-kubernetes v1.13.3 h1:IFnDQfFd6xK7BZYK7HG4zBoElIB7FDdX85BmlkQhSpM= -github.com/hashicorp/terraform-provider-kubernetes v1.13.3/go.mod h1:XSLp2+OcV4wZQ6VhgHswDwz4LJwiwO1/vbJYKt+gqWg= github.com/hashicorp/terraform-svchost v0.0.0-20191011084731-65d371908596/go.mod h1:kNDNcF7sN4DocDLBkQYz73HGKwN1ANB1blq4lIYLYvg= github.com/hashicorp/terraform-svchost v0.0.0-20191119180714-d2e4933b9136/go.mod h1:kNDNcF7sN4DocDLBkQYz73HGKwN1ANB1blq4lIYLYvg= github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734 h1:HKLsbzeOsfXmKNpr3GiT18XAblV0BjCbzL8KQAMZGa0= @@ -1148,11 +1138,14 @@ github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.7/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.9/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= -github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA= +github.com/imdario/mergo v0.3.10/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= +github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/influxdb v0.0.0-20190411212539-d24b7ba8c4c4/go.mod h1:qZna6X/4elxqT3yI9iZYdZrWWdeFOOprn86kgg4+IzY= @@ -1174,10 +1167,7 @@ github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJS github.com/jhump/protoreflect v1.6.0 h1:h5jfMVslIg6l29nsMs0D8Wj17RDVdNYti0vDN/PZZoE= github.com/jhump/protoreflect v1.6.0/go.mod h1:eaTn3RZAmMBcV0fifFvlm6VHNz3wSkYyXYWUh7ymB74= github.com/jingyugao/rowserrcheck v0.0.0-20191204022205-72ab7603b68a/go.mod h1:xRskid8CManxVta/ALEhJha/pweKBaVG6fWgc0yH25s= -github.com/jinzhu/copier v0.0.0-20190924061706-b57f9002281a h1:zPPuIq2jAWWPTrGt70eK/BSch+gFAGrNzecsoENgu2o= -github.com/jinzhu/copier v0.0.0-20190924061706-b57f9002281a/go.mod h1:yL958EeXv8Ylng6IfnvG4oflryUi3vgA3xPs9hmII1s= github.com/jirfag/go-printf-func-name v0.0.0-20191110105641-45db9963cdd3/go.mod h1:HEWGJkRDzjJY2sqdDwxccsGicWEf9BQOZsq2tV+xzM0= -github.com/jirfag/go-printf-func-name v0.0.0-20200119135958-7558a9eaa5af/go.mod h1:HEWGJkRDzjJY2sqdDwxccsGicWEf9BQOZsq2tV+xzM0= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= @@ -1202,8 +1192,9 @@ github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/u github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.11 h1:uVUAXhF2To8cbw/3xN3pxj6kk7TYKs98NIrTqPlMWAQ= github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jstemmer/go-junit-report v0.9.1 h1:6QPYqodiu3GuPL+7mfx+NwDdp2eTkp9IfEUpgAwUN0o= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= @@ -1237,7 +1228,6 @@ github.com/klauspost/compress v1.10.4/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYs github.com/klauspost/compress v1.10.5/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.10.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.10.8/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= -github.com/klauspost/compress v1.10.10/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.0/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.2/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.8 h1:difgzQsp5mdAz9v8lm3P/I+EpDKMU/6uTMw1y1FObuo= @@ -1282,7 +1272,6 @@ github.com/libvirt/libvirt-go v5.10.0+incompatible/go.mod h1:34zsnB4iGeOv7Byj6qo github.com/libvirt/libvirt-go-xml v4.10.0+incompatible/go.mod h1:oBlgD3xOA01ihiK5stbhFzvieyW+jVS6kbbsMVF623A= github.com/libvirt/libvirt-go-xml v5.10.0+incompatible h1:kcgVynR4a9cuh/kc7Ywl8XRBUxbqe05seR2qgN+yTno= github.com/libvirt/libvirt-go-xml v5.10.0+incompatible/go.mod h1:oBlgD3xOA01ihiK5stbhFzvieyW+jVS6kbbsMVF623A= -github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= @@ -1299,7 +1288,6 @@ github.com/lusis/go-artifactory v0.0.0-20160115162124-7e4ce345df82/go.mod h1:y54 github.com/magiconair/properties v1.7.6/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= -github.com/magiconair/properties v1.8.2/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/magiconair/properties v1.8.4/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= @@ -1313,7 +1301,6 @@ github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/maratori/testpackage v1.0.1/go.mod h1:ddKdw+XG0Phzhx8BFDTKgpWP4i7MpApTE5fXSKAqwDU= github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE= -github.com/markbates/pkger v0.17.1/go.mod h1:0JoVlrol20BSywW79rN3kdFFsE5xYM+rSCQDXbLhiuI= github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0= github.com/martini-contrib/render v0.0.0-20150707142108-ec18f8345a11/go.mod h1:Ah2dBMoxZEqk118as2T4u4fjfXarE0pPnMJaArZQZsI= github.com/masterzen/simplexml v0.0.0-20160608183007-4572e39b1ab9/go.mod h1:kCEbxUJlNDEBNbdQMkPSp6yaKcRXVI6f4ddk8Riv4bc= @@ -1322,7 +1309,6 @@ github.com/masterzen/simplexml v0.0.0-20190410153822-31eea3082786/go.mod h1:kCEb github.com/masterzen/winrm v0.0.0-20200615185753-c42b5136ff88 h1:cxuVcCvCLD9yYDbRCWw0jSgh1oT6P6mv3aJDKK5o7X4= github.com/masterzen/winrm v0.0.0-20200615185753-c42b5136ff88/go.mod h1:a2HXwefeat3evJHxFXSayvRHpYEPJYtErl4uIzfaUqY= github.com/matoous/godox v0.0.0-20190911065817-5d6d842e92eb/go.mod h1:1BELzlh859Sh1c6+90blK8lbYy0kwQf1bYlBhBysy1s= -github.com/matoous/godox v0.0.0-20200801072554-4fb83dc2941e/go.mod h1:1BELzlh859Sh1c6+90blK8lbYy0kwQf1bYlBhBysy1s= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= @@ -1408,21 +1394,19 @@ github.com/mitchellh/prefixedio v0.0.0-20190213213902-5733675afd51/go.mod h1:kB1 github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.1 h1:FVzMWA5RllMAKIdUSC8mdWo3XtwoecrH79BY70sEEpE= github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/moby/spdystream v0.2.0 h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8= github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= github.com/moby/term v0.0.0-20200312100748-672ec06f55cd/go.mod h1:DdlQx2hp0Ss5/fLikoLlEeIYiATotOjgB//nb973jeo= github.com/moby/term v0.0.0-20200915141129-7f0af18e79f2/go.mod h1:TjQg8pa4iejrUrjiz0MCtMV38jdMNW4doKSiBrEvCQQ= github.com/moby/term v0.0.0-20201216013528-df9cb8a40635/go.mod h1:FBS0z0QWA44HXygs7VXDUOGoN/1TV3RuWkLO04am3wc= -github.com/moby/term v0.0.0-20210610120745-9d4ed1856297 h1:yH0SvLzcbZxcJXho2yh7CqdENGMQe73Cw3woZBpPli0= github.com/moby/term v0.0.0-20210610120745-9d4ed1856297/go.mod h1:vgPCkQMyxTZ7IDy8SXRufE172gr8+K/JE/7hHFxHW3A= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 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-20180320133207-05fbef0ca5da/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 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/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4= github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= @@ -1454,7 +1438,6 @@ github.com/nicksnyder/go-i18n v1.10.0/go.mod h1:HrK7VCrbOvQoUAQ7Vpy7i87N7JZZZ7R2 github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nishanths/exhaustive v0.0.0-20200708172631-8866003e3856/go.mod h1:wBEpHwM2OdmeNpdCvRPUlkEbBuaFmcK4Wv8Q7FuGW3c= -github.com/nishanths/exhaustive v0.0.0-20200811152831-6cf413ae40e0/go.mod h1:wBEpHwM2OdmeNpdCvRPUlkEbBuaFmcK4Wv8Q7FuGW3c= github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d h1:VhgPp6v9qf9Agr/56bj7Y/xa04UccTW04VP0Qed4vnQ= github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U= github.com/nwaples/rardecode v1.0.0/go.mod h1:5DzqNKiOdpKKBH87u8VlvAnPZMXcGRhxWkRpHbbfGS0= @@ -1478,13 +1461,14 @@ github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+ github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.13.0/go.mod h1:+REjRxOmWfHCjfv9TTWB1jD1Frx4XydAD3zm1lskyM0= github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= github.com/onsi/ginkgo v1.14.1/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= github.com/onsi/ginkgo v1.14.2/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg= -github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= +github.com/onsi/ginkgo v1.16.2/go.mod h1:CObGmKUOKaSC0RjmoAK7tKyn4Azo5P2IWuoMnvwxz1E= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v0.0.0-20190113212917-5533ce8a0da3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.4.2/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= @@ -1499,8 +1483,11 @@ github.com/onsi/gomega v1.10.2/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1y github.com/onsi/gomega v1.10.3/go.mod h1:V9xEwhxec5O8UDM77eCW8vLymOMltsqPVYWrpDsH8xc= github.com/onsi/gomega v1.10.4/go.mod h1:g/HbgYopi++010VEqkFgJHKC09uJiW9UkXvMUuKHUCQ= github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= -github.com/onsi/gomega v1.14.0 h1:ep6kpPVwmr/nTbklSx2nrLNSIO62DoYAhnPNIMhK8gI= +github.com/onsi/gomega v1.13.0/go.mod h1:lRk9szgn8TxENtWd0Tp4c3wjlRfMTMH27I+3Je41yGY= github.com/onsi/gomega v1.14.0/go.mod h1:cIuvLEne0aoVhAgh/O6ac0Op8WWw9H6eYCriF+tEHG0= +github.com/onsi/gomega v1.15.0/go.mod h1:cIuvLEne0aoVhAgh/O6ac0Op8WWw9H6eYCriF+tEHG0= +github.com/onsi/gomega v1.17.0 h1:9Luw4uT5HTjHTN8+aNcSThgH1vdXnmdJ8xIfZ4wyTRE= +github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= github.com/opencontainers/go-digest v0.0.0-20180430190053-c9281466c8b2/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= @@ -1522,7 +1509,6 @@ github.com/openshift/api v0.0.0-20200424083944-0422dc17083e/go.mod h1:VnbEzX8SAa github.com/openshift/api v0.0.0-20200827090112-c05698d102cf/go.mod h1:M3xexPhgM8DISzzRpuFUy+jfPjQPIcs9yqEYj17mXV8= github.com/openshift/api v0.0.0-20200829102639-8a3a835f1acf/go.mod h1:M3xexPhgM8DISzzRpuFUy+jfPjQPIcs9yqEYj17mXV8= github.com/openshift/api v0.0.0-20200901182017-7ac89ba6b971/go.mod h1:M3xexPhgM8DISzzRpuFUy+jfPjQPIcs9yqEYj17mXV8= -github.com/openshift/api v0.0.0-20200929171550-c99a4deebbe5/go.mod h1:Si/I9UGeRR3qzg01YWPmtlr0GeGk2fnuggXJRmjAZ6U= github.com/openshift/api v0.0.0-20201214114959-164a2fb63b5f/go.mod h1:aqU5Cq+kqKKPbDMqxo9FojgDeSpNJI7iuskjXjtojDg= github.com/openshift/api v0.0.0-20201216151826-78a19e96f9eb/go.mod h1:aqU5Cq+kqKKPbDMqxo9FojgDeSpNJI7iuskjXjtojDg= github.com/openshift/api v0.0.0-20210331193751-3acddb19d360/go.mod h1:dZ4kytOo3svxJHNYd0J55hwe/6IQG5gAUHUE0F3Jkio= @@ -1532,8 +1518,9 @@ github.com/openshift/api v0.0.0-20210730095913-85e1d547cdee/go.mod h1:ntkQrC1Z6A github.com/openshift/api v0.0.0-20210816181336-8ff39b776da3/go.mod h1:x81TFA31x1OMT9SYWukQqJ/KbmeveRN6fo+XeGRK8g0= github.com/openshift/api v0.0.0-20211025104849-a11323ccb6ea/go.mod h1:RsQCVJu4qhUawxxDP7pGlwU3IA4F01wYm3qKEu29Su8= github.com/openshift/api v0.0.0-20211108165917-be1be0e89115/go.mod h1:RsQCVJu4qhUawxxDP7pGlwU3IA4F01wYm3qKEu29Su8= -github.com/openshift/api v0.0.0-20211119153416-313e51eab8c8 h1:FBV3/2ac0uE3MGExSzx/TqJKWNpNjHrpxRBIbmxI654= -github.com/openshift/api v0.0.0-20211119153416-313e51eab8c8/go.mod h1:RsQCVJu4qhUawxxDP7pGlwU3IA4F01wYm3qKEu29Su8= +github.com/openshift/api v0.0.0-20211209135129-c58d9f695577/go.mod h1:DoslCwtqUpr3d/gsbq4ZlkaMEdYqKxuypsDjorcHhME= +github.com/openshift/api v0.0.0-20211210181228-6e0b1eb97188 h1:Z9UVScJKlWgNTvFzjkbZlEX3UzptTki2RwzaLaLjnFA= +github.com/openshift/api v0.0.0-20211210181228-6e0b1eb97188/go.mod h1:DoslCwtqUpr3d/gsbq4ZlkaMEdYqKxuypsDjorcHhME= github.com/openshift/baremetal-operator v0.0.0-20211201170610-92ffa60c683d h1:4KkYItiWENIs2bV6lKOcIMdWUnZJA+GWT9Us7z0P1UA= github.com/openshift/baremetal-operator v0.0.0-20211201170610-92ffa60c683d/go.mod h1:p32F1DBUxfgd0JjM4rCuhJomFJokEoWR1Z/LZNL2LM8= github.com/openshift/baremetal-operator/apis v0.0.0-20211201170610-92ffa60c683d h1:DHGXCvXWsPExutf3tgQYD4TVDSAOviLXO7Vnc42oXhw= @@ -1546,8 +1533,8 @@ github.com/openshift/build-machinery-go v0.0.0-20200819073603-48aa266c95f7/go.mo github.com/openshift/build-machinery-go v0.0.0-20200917070002-f171684f77ab/go.mod h1:b1BuldmJlbA/xYtdZvKi+7j5YGB44qJUJDZ9zwiNCfE= github.com/openshift/build-machinery-go v0.0.0-20210209125900-0da259a2c359/go.mod h1:b1BuldmJlbA/xYtdZvKi+7j5YGB44qJUJDZ9zwiNCfE= github.com/openshift/build-machinery-go v0.0.0-20210712174854-1bb7fd1518d3/go.mod h1:b1BuldmJlbA/xYtdZvKi+7j5YGB44qJUJDZ9zwiNCfE= -github.com/openshift/client-go v0.0.0-20200929181438-91d71ef2122c h1:DQTWW8DGRN7fu5qwEPcbdP9hAxXi7dm5cvi0hrdR3UE= -github.com/openshift/client-go v0.0.0-20200929181438-91d71ef2122c/go.mod h1:MwESrlhzumQGcGtPCpz/WjDrlvhu1fMNlLBcNYjO0fY= +github.com/openshift/client-go v0.0.0-20211209144617-7385dd6338e3 h1:SG1aqwleU6bGD0X4mhkTNupjVnByMYYuW4XbnCPavQU= +github.com/openshift/client-go v0.0.0-20211209144617-7385dd6338e3/go.mod h1:cwhyki5lqBmrT0m8Im+9I7PGFaraOzcYPtEz93RcsGY= github.com/openshift/cloud-credential-operator v0.0.0-20200316201045-d10080b52c9e h1:2gyl9UVyjHSWzdS56KUXxQwIhENbq2x2olqoMQSA/C8= github.com/openshift/cloud-credential-operator v0.0.0-20200316201045-d10080b52c9e/go.mod h1:iPn+uhIe7nkP5BMHe2QnbLtg5m/AIQ1xvz9s3cig5ss= github.com/openshift/cluster-api v0.0.0-20190805113604-f8de78af80fc h1:6Nf3TaiooyEZNk+3ZHonNOujT+HacuSj9cxyeGTc/zg= @@ -1634,6 +1621,7 @@ github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIw github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= +github.com/pborman/uuid v0.0.0-20170612153648-e790cca94e6c/go.mod h1:VyrYX9gd7irzKovcSS6BIIEwPRkP2Wm2m9ufcdFSJ34= github.com/pborman/uuid v0.0.0-20180906182336-adf5a7427709/go.mod h1:VyrYX9gd7irzKovcSS6BIIEwPRkP2Wm2m9ufcdFSJ34= github.com/pborman/uuid v1.2.0 h1:J7Q5mO4ysT1dv8hyrUGHb9+ooztCXu1D8MY8DZYsu3g= github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= @@ -1641,11 +1629,9 @@ github.com/pelletier/go-toml v1.1.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/9 github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.6.0/go.mod h1:5N711Q9dKgbdkxHL+MEfF31hpT7l0S0s/t2kKREewys= github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE= -github.com/pelletier/go-toml v1.8.0/go.mod h1:D6yutnOGMveHEPV7VQOuvI/gXY61bv+9bAOTRnLElKs= github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5dSQ= github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= -github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d/go.mod h1:3OzsM7FXDQlpCiw2j81fOmAwQLnZnLGXVKUzeKQXIAw= github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= @@ -1682,6 +1668,7 @@ github.com/pquerna/otp v1.2.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1 github.com/pquerna/otp v1.2.1-0.20191009055518-468c2dd2b58d h1:PinQItctnaL2LtkaSM678+ZLLy5TajwOeXzWvYC7tII= github.com/pquerna/otp v1.2.1-0.20191009055518-468c2dd2b58d/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg= github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.2/go.mod h1:OsXs2jCmiKlQ1lTBmv21f2mNfw4xf/QclQDMrYNZzcM= github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= @@ -1702,6 +1689,7 @@ github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6T github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.0.0-20180518154759-7600349dcfe1/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= @@ -1711,10 +1699,12 @@ github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+ github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= github.com/prometheus/common v0.15.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s= -github.com/prometheus/common v0.26.0 h1:iMAkS2TDoNWnKM+Kopnx/8tnEStIfpYA0ur0xQzzhMQ= github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= +github.com/prometheus/common v0.28.0 h1:vGVfV9KrDTvWt5boZO0I19g2E3CsWfpPPKZM9dt3mEw= +github.com/prometheus/common v0.28.0/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= github.com/prometheus/procfs v0.0.0-20180125133057-cb4147076ac7/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20180612222113-7d6f385de8be/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= @@ -1723,6 +1713,7 @@ github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7z github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= +github.com/prometheus/procfs v0.0.11/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.2.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4= @@ -1730,9 +1721,7 @@ github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1 github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/quasilyte/go-consistent v0.0.0-20190521200055-c6f3937de18c/go.mod h1:5STLWrekHfjyYwxBRVRXNOSewLJ3PWfDJd1VyTS21fI= github.com/quasilyte/go-ruleguard v0.1.2-0.20200318202121-b00d7a75d3d8/go.mod h1:CGFX09Ci3pq9QZdj86B+VGIdNj4VyCo2iPOGS9esB/k= -github.com/quasilyte/go-ruleguard v0.2.0/go.mod h1:2RT/tf0Ce0UDj5y243iWKosQogJd8+1G3Rs2fxmlYnw= github.com/quasilyte/regex/syntax v0.0.0-20200407221936-30656e2c4a95/go.mod h1:rlzQ04UMyJXu/aOvhd8qT+hvDrFpiwqp8MRXDY9szc0= -github.com/quasilyte/regex/syntax v0.0.0-20200805063351-8f842688393c/go.mod h1:rlzQ04UMyJXu/aOvhd8qT+hvDrFpiwqp8MRXDY9szc0= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 h1:MkV+77GLUNo5oJ0jf870itWm3D0Sjh7+Za9gazKc5LQ= github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= @@ -1741,7 +1730,6 @@ github.com/rickb777/date v1.12.5-0.20200422084442-6300e543c4d9 h1:czJCcoUR3FMpHn github.com/rickb777/date v1.12.5-0.20200422084442-6300e543c4d9/go.mod h1:L8WrssTzvgYw34/Ppa0JpJfI7KKXZ2cVGI6Djt0brUU= github.com/rickb777/plural v1.2.0 h1:5tvEc7UBCZ7l8h/2UeybSkt/uu1DQsZFOFdNevmUhlE= github.com/rickb777/plural v1.2.0/go.mod h1:UdpyWFCGbo3mvK3f/PfZOAOrkjzJlYN/sD46XNWJ+Es= -github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ= github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= @@ -1749,10 +1737,7 @@ github.com/rogpeppe/go-charset v0.0.0-20180617210344-2471d30d28b4/go.mod h1:qgYe github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.5.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.0/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/russross/blackfriday v1.5.2 h1:HyvC0ARfnZBqnXwABFeSZHpKvJHJJfPz81GNueLj0oo= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryancurrah/gomodguard v1.1.0/go.mod h1:4O8tr7hBODaGE6VIhfJDHcwzh5GUccKSJBU0UMXJFVM= @@ -1768,11 +1753,9 @@ github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdh github.com/satori/uuid v0.0.0-20160927100844-b061729afc07/go.mod h1:B8HLsPLik/YNn6KKWVMDJ8nzCL8RP5WyfsnmvnAEwIU= github.com/satori/uuid v1.2.0 h1:6TFY4nxn5XwBx0gDfzbEMCNT6k4N/4FNIuN8RACZ0KI= github.com/satori/uuid v1.2.0/go.mod h1:B8HLsPLik/YNn6KKWVMDJ8nzCL8RP5WyfsnmvnAEwIU= -github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/securego/gosec v0.0.0-20191002120514-e680875ea14d/go.mod h1:w5+eXa0mYznDkHaMCXA4XYffjlH+cy1oyKbfzJXa2Do= github.com/securego/gosec/v2 v2.3.0/go.mod h1:UzeVyUXbxukhLeHKV3VVqo7HdoQR9MrRfFmZYotn8ME= -github.com/securego/gosec/v2 v2.4.0/go.mod h1:0/Q4cjmlFDfDUj1+Fib61sc+U5IQb2w+Iv9/C3wPVko= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= @@ -1819,7 +1802,6 @@ github.com/sonatard/noctx v0.0.1/go.mod h1:9D2D/EoULe8Yy2joDHJj7bv3sZoq9AaSb8B4l github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= github.com/sourcegraph/go-diff v0.5.1/go.mod h1:j2dHj3m8aZgQO8lMTcTnBcXkRRRqi34cd2MNlA9u1mE= github.com/sourcegraph/go-diff v0.5.3/go.mod h1:v9JDtjCE4HHHCZGId75rg8gkKKa98RVjBcBGsVmMmak= -github.com/sourcegraph/go-diff v0.6.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= @@ -1847,9 +1829,7 @@ github.com/spf13/viper v1.0.2/go.mod h1:A8kyI5cUJhb8N+3pkfONlcEcZbueH6nhAm0Fq7Sr github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= -github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= -github.com/ssgreg/nlreturn/v2 v2.1.0/go.mod h1:E/iiPB78hV7Szg2YfRgyIrk1AD6JVMTRkkxBiELzh2I= github.com/stoewer/go-strcase v1.0.2/go.mod h1:eLfe5bL3qbL7ep/KafHzthxejrOF5J3xmt03uL5tzek= github.com/stoewer/go-strcase v1.2.0 h1:Z2iHWqGXH00XYgqDmNgQbIBxf3wrNq0F3feEy0ainaU= github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= @@ -1859,8 +1839,6 @@ github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5J github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= -github.com/stretchr/objx v0.3.0 h1:NGXK3lHquSN08v5vWalVI/L8XU9hdzE/G6xsrze47As= -github.com/stretchr/objx v0.3.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/testify v0.0.0-20151208002404-e3a8ff8ce365/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= @@ -1877,7 +1855,6 @@ github.com/svanharmelen/jsonapi v0.0.0-20180618144545-0c0828c3f16d/go.mod h1:BST github.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= github.com/tchap/go-patricia v2.3.0+incompatible/go.mod h1:bmLyhP68RS6kStMGxByiQ23RP/odRBOTVjwp2cDyi6I= github.com/tdakkota/asciicheck v0.0.0-20200416190851-d7f85be797a2/go.mod h1:yHp0ai0Z9gUljN3o0xMhYJnH/IcvkdTBOX2fmJ93JEM= -github.com/tdakkota/asciicheck v0.0.0-20200416200610-e657995f937b/go.mod h1:yHp0ai0Z9gUljN3o0xMhYJnH/IcvkdTBOX2fmJ93JEM= github.com/tencentcloud/tencentcloud-sdk-go v3.0.82+incompatible/go.mod h1:0PfYow01SHPMhKY31xa+EFz2RStxIqj6JFAJS+IkCi4= github.com/tencentyun/cos-go-sdk-v5 v0.0.0-20190808065407-f07404cefc8c/go.mod h1:wk2XFUg6egk4tSDNZtXeKfe2G6690UVyt163PuUxBZk= github.com/terraform-provider-openstack/terraform-provider-openstack v1.37.0 h1:g7mB+EJWenwFZ2ieTnhstOj3XTNuCwpl+in8vC1HGPc= @@ -1895,12 +1872,10 @@ github.com/terraform-providers/terraform-provider-random v1.3.2-0.20190925210718 github.com/terraform-providers/terraform-provider-random v1.3.2-0.20190925210718-83518d96ae4f/go.mod h1:F4KE9YftuJyMiBth4W1kCrsyOHndtTjAmZ+ZzjqWY+4= github.com/terraform-providers/terraform-provider-template v1.0.0/go.mod h1:/J+B8me5DCMa0rEBH5ic2aKPjhtpWNeScmxFJWxB1EU= github.com/tetafro/godot v0.4.2/go.mod h1:/7NLHhv08H1+8DNj0MElpAACw1ajsCuf3TKNQxA5S+0= -github.com/tetafro/godot v0.4.8/go.mod h1:/7NLHhv08H1+8DNj0MElpAACw1ajsCuf3TKNQxA5S+0= github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/timakin/bodyclose v0.0.0-20190721030226-87058b9bfcec/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk= github.com/timakin/bodyclose v0.0.0-20190930140734-f7f2e9bca95e/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk= -github.com/timakin/bodyclose v0.0.0-20200424151742-cb6215831a94/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk= github.com/tjfoc/gmsm v1.3.2 h1:7JVkAn5bvUJ7HtU08iW6UiD+UTmJTIToHCfeFzkcCxM= github.com/tjfoc/gmsm v1.3.2/go.mod h1:HaUcFuY0auTiaHB9MHFGCPx5IaLhTUd2atbCFBQXn9w= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= @@ -1921,7 +1896,6 @@ github.com/ulikunitz/xz v0.5.7 h1:YvTNdFzX6+W5m9msiYg/zpkSURPPtOlzbqYjrFn7Yt4= github.com/ulikunitz/xz v0.5.7/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= github.com/ultraware/funlen v0.0.1/go.mod h1:Dp4UiAus7Wdb9KUZsYWZEWiRzGuM2kXM1lPbfaF6xhA= github.com/ultraware/funlen v0.0.2/go.mod h1:Dp4UiAus7Wdb9KUZsYWZEWiRzGuM2kXM1lPbfaF6xhA= -github.com/ultraware/funlen v0.0.3/go.mod h1:Dp4UiAus7Wdb9KUZsYWZEWiRzGuM2kXM1lPbfaF6xhA= github.com/ultraware/whitespace v0.0.4/go.mod h1:aVMh/gQve5Maj9hQ/hg+F75lr/X5A89uZnzAmWSineA= github.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= @@ -1932,12 +1906,10 @@ github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6Kllzaw github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasthttp v1.2.0/go.mod h1:4vX61m6KN+xDduDNwXrhIAVZaZaZiQ1luJk8LWSxF3s= github.com/valyala/fasthttp v1.12.0/go.mod h1:229t1eWu9UXTPmoUkbpN/fctKPBY4IJoFXQnxHGXy6E= -github.com/valyala/fasthttp v1.15.1/go.mod h1:YOKImeEosDdBPnxc0gy7INqi3m1zK6A+xl6TwOBhHCA= github.com/valyala/fasthttp v1.22.0 h1:OpwH5KDOJ9cS2bq8fD+KfT4IrksK0llvkHf4MZx42jQ= github.com/valyala/fasthttp v1.22.0/go.mod h1:0mw2RjXGOzxf4NL2jni3gUQ7LfjjUSiG5sskOUUSEpU= github.com/valyala/quicktemplate v1.1.1/go.mod h1:EH+4AkTd43SvgIbQHYu59/cJyxDoOVRUAfrukLPuGJ4= github.com/valyala/quicktemplate v1.5.1/go.mod h1:v7yYWpBEiutDyNfVaph6oC/yKwejzVyTX/2cwwHxyok= -github.com/valyala/quicktemplate v1.6.2/go.mod h1:mtEJpQtUiBV0SHhMX6RtiJtqxncgrfmjcUy5T68X8TM= github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= github.com/vbatts/tar-split v0.11.1/go.mod h1:LEuURwDEiWjRjwu46yU3KVGuUdVv/dcnpcEPSzR8z6g= github.com/vbauerster/mpb/v5 v5.2.2/go.mod h1:W5Fvgw4dm3/0NhqzV8j6EacfuTe5SvnzBRwiXxDR9ww= @@ -1989,13 +1961,13 @@ github.com/yuin/goldmark v1.1.30/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/zclconf/go-cty v1.0.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v1.1.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v1.1.1/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v1.2.0/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= github.com/zclconf/go-cty v1.2.1/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= github.com/zclconf/go-cty v1.4.0/go.mod h1:nHzOclRkoj++EU9ZjSrZvRG0BXIWt8c7loYc0qXAFGQ= -github.com/zclconf/go-cty v1.6.1/go.mod h1:VDR4+I79ubFBGm1uJac1226K5yANQFHeauxPBoP54+o= github.com/zclconf/go-cty v1.7.1/go.mod h1:VDR4+I79ubFBGm1uJac1226K5yANQFHeauxPBoP54+o= github.com/zclconf/go-cty v1.8.1 h1:SI0LqNeNxAgv2WWqWJMlG2/Ad/6aYJ7IVYYMigmfkuI= github.com/zclconf/go-cty v1.8.1/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= @@ -2045,7 +2017,6 @@ go.opentelemetry.io/otel/sdk/export/metric v0.20.0/go.mod h1:h7RBNMsDJ5pmI1zExLi go.opentelemetry.io/otel/sdk/metric v0.20.0/go.mod h1:knxiS8Xd4E/N+ZqKmUPf3gTTZ4/0TjTXukfxjzSTpHE= go.opentelemetry.io/otel/trace v0.20.0/go.mod h1:6GjCW8zgDjwGHGa6GkyeB8+/5vjT16gUEi0Nf1iBdgw= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= -go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5 h1:+FNtrFTmVw0YZGpBGX56XDee331t6JAXeK2bcyhLOOc= go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5/go.mod h1:nmDLcffg48OtT/PSW0Hg7FvpRQsQh5OSqIylirxKC7o= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= @@ -2053,25 +2024,33 @@ go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/goleak v1.1.10 h1:z+mqJhf6ss6BSfSM671tgKyZBFPTTJM+HLxnhPC3wu0= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= +go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= +go.uber.org/goleak v1.1.12 h1:gZAh5/EyT/HQwlpkCy6wTpqfH9H8Lz8zbm3dZh+OyzA= +go.uber.org/goleak v1.1.12/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.8.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= -go.uber.org/zap v1.17.0 h1:MTjgFu6ZLKvY6Pvaqk97GlxNBuMpV4Hy/3P6tRGlI2U= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= +go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= +go.uber.org/zap v1.19.0/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= +go.uber.org/zap v1.19.1 h1:ue41HOKd1vGURxrmeKIgELGb3jPW9DMUDGtsinblHwI= +go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= go4.org v0.0.0-20191010144846-132d2879e1e9/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= go4.org v0.0.0-20200104003542-c7e774b10ea0 h1:M6XsnQeLwG+rHQ+/rrGh3puBI3WZEy9TBWmf2H+enQA= go4.org v0.0.0-20200104003542-c7e774b10ea0/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= golang.org/x/arch v0.0.0-20180920145803-b19384d3c130/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8= golang.org/x/crypto v0.0.0-20180608092829-8ac0e0d97ce4/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20180820150726-614d502a4dac/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= @@ -2109,8 +2088,9 @@ golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 h1:It14KIkyBFYkHkwZ7k45minvA9aorojkyjGk9KJ5B/w= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ= +golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190312203227-4b39c73a6495/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -2202,8 +2182,11 @@ golang.org/x/net v0.0.0-20210226101413-39120d07d75e/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= -golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 h1:ADo5wSpq2gqaCGQWzk7S5vd//0iyyLeAratkEoG5dLE= golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210825183410-e898025ed96a h1:bRuuGXV8wwSdGTB+CtJf+FjgO1APK1CoO39T4BN/XBw= +golang.org/x/net v0.0.0-20210825183410-e898025ed96a/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190130055435-99b60b757ec1/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -2212,8 +2195,10 @@ golang.org/x/oauth2 v0.0.0-20190402181905-9f3314589c9a/go.mod h1:gOpvHmFTYa4Iltr golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43 h1:ld7aEMNHoBnnDAX15v1T6z31v8HwR2A9FYOuAhWqkwc= golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f h1:Qmd2pbz05z7z6lm0DrgQVVPuBm92jqujBKMHMOlOQEw= +golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= 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= @@ -2295,14 +2280,12 @@ golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200610111108-226ff32320da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200831180312-196b9ba8737a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200923182605-d9f96fdee20d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -2319,13 +2302,18 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210426230700-d19ff857e887/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210817190340-bfb29a6856f2/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210831042530-f4d43177bf5e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211029165221-6e7872819dc8 h1:M69LAlWZCshgp0QSzyDcSsSIejIEeuaCVpmwcKwyLMk= +golang.org/x/sys v0.0.0-20211029165221-6e7872819dc8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d h1:SZxvLBoTP5yHO3Frd4z4vrF+DBX9vMVanchswa69toE= -golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b h1:9zKuko04nR4gjZ4+DNjHqRlAJqbJETHwiNKDqTfOjfE= +golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.0.0-20170915090833-1cbadb444a80/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -2335,13 +2323,15 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20210611083556-38a9dc6acbc6/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac h1:7zkz7BUtwNFFqcowJ+RIgu2MaV/MapERkDIy+mwPyjs= golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20170915040203-e531a2a1c15f/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -2410,7 +2400,6 @@ golang.org/x/tools v0.0.0-20200409170454-77362c5149f0/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20200410194907-79a7a3126eef/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200414032229-332987a829c3/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200422022333-3d57cf2e726e/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200426102838-f3a5411a4c3b/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200505023115-26f46d2f7ef8/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200509030707-2212a7e161a5/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= @@ -2425,17 +2414,11 @@ golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200625211823-6506e20df31f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200626171337-aa94e735be7f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200701041122-1837592efa10/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200710042808-f1c4188a97a1/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200721032237-77f530d86f9a/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200731060945-b5fad4ed8dd6/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200812195022-5ae4c3c160a0/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200820010801-b793a1359eac/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200827163409-021d7c6f1ec3/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= -golang.org/x/tools v0.0.0-20200911153331-7ad463ce66dd/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= golang.org/x/tools v0.0.0-20201020123448-f5c826d1900e/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20201028111035-eafbe7b904eb/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= @@ -2443,15 +2426,19 @@ golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210107193943-4ed967dd8eff/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.2 h1:kRBLX7v7Af8W7Gdbbc908OJcdgtK8bOz9Uaj8/F1ACA= golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.6-0.20210820212750-d4cc65f0b2ff h1:VX/uD7MK0AHXGiScH3fsieUQUcpmRERPDYtqZdJnA+Q= +golang.org/x/tools v0.1.6-0.20210820212750-d4cc65f0b2ff/go.mod h1:YD9qOF0M9xpSpdWTBbzEl5e/RnCefISl8E5Noe10jFM= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gomodules.xyz/jsonpatch/v2 v2.1.0 h1:Phva6wqu+xR//Njw6iorylFFgn/z547tw5Ne3HZPQ+k= +gomodules.xyz/jsonpatch/v2 v2.0.1/go.mod h1:IhYNNY4jnS53ZnfE4PAmpKtDpTCj1JFXc+3mwe7XcUU= gomodules.xyz/jsonpatch/v2 v2.1.0/go.mod h1:IhYNNY4jnS53ZnfE4PAmpKtDpTCj1JFXc+3mwe7XcUU= +gomodules.xyz/jsonpatch/v2 v2.2.0 h1:4pT439QV83L+G9FkcCriY6EkpcK6r6bK+A5FBUMI7qY= +gomodules.xyz/jsonpatch/v2 v2.2.0/go.mod h1:WXp+iVDkoLQqPudfQ9GBlwB2eZ5DKOnjQZCYdOS8GPY= 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/go.mod h1:kS+toOQn6AQKjmKJ7gzohV1XkqsFehRA2FbsbkopSuQ= @@ -2511,7 +2498,6 @@ gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/ini.v1 v1.42.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.56.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/ini.v1 v1.61.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/jcmturner/aescts.v1 v1.0.1 h1:cVVZBK2b1zY26haWB4vbBiZrfFQnfbTVrE3xZq6hrEw= @@ -2561,13 +2547,11 @@ gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= -gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.0.1-2020.1.5/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.6 h1:W18jzjh8mfPez+AwGLxmOImucz/IFjpNlrKVnaj2YVc= honnef.co/go/tools v0.0.1-2020.1.6/go.mod h1:pyyisuGw24ruLjrr1ddx39WE0y9OooInRzEYLhQB2YY= k8s.io/api v0.0.0-20190409021203-6e4e0e4f393b/go.mod h1:iuAfoD4hCxJ8Onx9kaTIt30j7jUFS00AXQi6QMi99vA= @@ -2576,27 +2560,35 @@ k8s.io/api v0.0.0-20190620084959-7cf5895f2711/go.mod h1:TBhBqb1AWbBQbW3XRusr7n7E k8s.io/api v0.18.0-beta.2/go.mod h1:2oeNnWEqcSmaM/ibSh3t7xcIqbkGXhzZdn4ezV9T4m0= k8s.io/api v0.18.0/go.mod h1:q2HRQkfDzHMBZL9l/y9rH63PkQl4vae0xRT+8prbrK8= k8s.io/api v0.18.2/go.mod h1:SJCWI7OLzhZSvbY7U8zwNl9UA4o1fizoug34OV/2r78= +k8s.io/api v0.18.6/go.mod h1:eeyxr+cwCjMdLAmr2W3RyDI0VvTawSg/3RFFBEnmZGI= k8s.io/api v0.19.0/go.mod h1:I1K45XlvTrDjmj5LoM5LuP/KYrhWbjUKT/SoPG0qTjw= -k8s.io/api v0.19.1/go.mod h1:+u/k4/K/7vp4vsfdT7dyl8Oxk1F26Md4g5F26Tu85PU= +k8s.io/api v0.19.2/go.mod h1:IQpK0zFQ1xc5iNIQPqzgoOwuFugaYHK4iCknlAQP9nI= k8s.io/api v0.20.0/go.mod h1:HyLC5l5eoS/ygQYl1BXBgFzWNlkHiAuyNAbevIn+FKg= -k8s.io/api v0.21.0-beta.1/go.mod h1:8A+GKfJYDnFlmsIqnwi7z2l5+GwI3fbIdAkPu3xiZKA= k8s.io/api v0.21.0-rc.0/go.mod h1:Dkc/ZauWJrgZhjOjeBgW89xZQiTBJA2RaBKYHXPsi2Y= k8s.io/api v0.21.0/go.mod h1:+YbrhBBGgsxbF6o6Kj4KJPJnBmAKuXDeS3E18bgHNVU= +k8s.io/api v0.21.2/go.mod h1:Lv6UGJZ1rlMI1qusN8ruAp9PUBFyBwpEHAdG24vIsiU= +k8s.io/api v0.21.3/go.mod h1:hUgeYHUbBp23Ue4qdX9tR8/ANi/g3ehylAqDn9NWVOg= k8s.io/api v0.21.4/go.mod h1:fTVGP+M4D8+00FN2cMnJqk/eb/GH53bvmNs2SVTmpFk= k8s.io/api v0.22.0-rc.0/go.mod h1:EUcKB6RvpW74HMRUSSNwpUzrIHBdGT1FeAvOV+txic0= k8s.io/api v0.22.0/go.mod h1:0AoXXqst47OI/L0oGKq9DG61dvGRPXs7X4/B7KyjBCU= k8s.io/api v0.22.1/go.mod h1:bh13rkTp3F1XEaLGykbyRD2QaTTzPm0e/BMd8ptFONY= -k8s.io/api v0.22.2 h1:M8ZzAD0V6725Fjg53fKeTJxGsJvRbk4TEm/fexHMtfw= -k8s.io/api v0.22.2/go.mod h1:y3ydYpLJAaDI+BbSe2xmGcqxiWHmWjkEeIbiwHvnPR8= +k8s.io/api v0.23.0 h1:WrL1gb73VSC8obi8cuYETJGXEoFNEh3LU0Pt+Sokgro= +k8s.io/api v0.23.0/go.mod h1:8wmDdLBHBNxtOIytwLstXt5E9PddnZb0GaMcqsvDBpg= +k8s.io/apiextensions-apiserver v0.0.0-20190409022649-727a075fdec8/go.mod h1:IxkesAMoaCRoLrPJdZNZUQp9NfZnzqaVzLhb2VEQzXE= k8s.io/apiextensions-apiserver v0.18.0-beta.2/go.mod h1:Hnrg5jx8/PbxRbUoqDGxtQkULjwx8FDW4WYJaKNK+fk= k8s.io/apiextensions-apiserver v0.18.2/go.mod h1:q3faSnRGmYimiocj6cHQ1I3WpLqmDgJFlKL37fC4ZvY= +k8s.io/apiextensions-apiserver v0.18.6/go.mod h1:lv89S7fUysXjLZO7ke783xOwVTm6lKizADfvUM/SS/M= k8s.io/apiextensions-apiserver v0.19.0/go.mod h1:znfQxNpjqz/ZehvbfMg5N6fvBJW5Lqu5HVLTJQdP4Fs= +k8s.io/apiextensions-apiserver v0.19.2/go.mod h1:EYNjpqIAvNZe+svXVx9j4uBaVhTB4C94HkY3w058qcg= k8s.io/apiextensions-apiserver v0.20.0/go.mod h1:ZH+C33L2Bh1LY1+HphoRmN1IQVLTShVcTojivK3N9xg= -k8s.io/apiextensions-apiserver v0.21.0-beta.1/go.mod h1:vluMqsJ5+hPgM9UtBhkFSGrfD86KUac9yeKVqpGBZz0= k8s.io/apiextensions-apiserver v0.21.0-rc.0/go.mod h1:ItIoMBJU1gy93Qwr/B2699r4b0VmZqAOU+15BvozxMY= +k8s.io/apiextensions-apiserver v0.21.0/go.mod h1:gsQGNtGkc/YoDG9loKI0V+oLZM4ljRPjc/sql5tmvzc= +k8s.io/apiextensions-apiserver v0.21.2/go.mod h1:+Axoz5/l3AYpGLlhJDfcVQzCerVYq3K3CvDMvw6X1RA= +k8s.io/apiextensions-apiserver v0.21.3/go.mod h1:kl6dap3Gd45+21Jnh6utCx8Z2xxLm8LGDkprcd+KbsE= +k8s.io/apiextensions-apiserver v0.21.4/go.mod h1:OoC8LhI9LnV+wKjZkXIBbLUwtnOGJiTRE33qctH5CIk= k8s.io/apiextensions-apiserver v0.22.0-rc.0/go.mod h1:KSr+2VJ6ye8Fy50q7xHZ/Tw8vrRII82KIKbz9eUFmeo= -k8s.io/apiextensions-apiserver v0.22.2 h1:zK7qI8Ery7j2CaN23UCFaC1hj7dMiI87n01+nKuewd4= -k8s.io/apiextensions-apiserver v0.22.2/go.mod h1:2E0Ve/isxNl7tWLSUDgi6+cmwHi5fQRdwGVCxbC+KFA= +k8s.io/apiextensions-apiserver v0.23.0 h1:uii8BYmHYiT2ZTAJxmvc3X8UhNYMxl2A0z0Xq3Pm+WY= +k8s.io/apiextensions-apiserver v0.23.0/go.mod h1:xIFAEEDlAZgpVBl/1VSjGDmLoXAWRG40+GsWhKhAxY4= k8s.io/apimachinery v0.0.0-20190404173353-6a84e37a896d/go.mod h1:ccL7Eh7zubPUSh9A3USN90/OzHNSVN6zxzde07TDCL0= k8s.io/apimachinery v0.0.0-20190409092423-760d1845f48b/go.mod h1:FW86P8YXVLsbuplGMZeb20J3jYHscrDqw4jELaFJvRU= k8s.io/apimachinery v0.0.0-20190612205821-1799e75a0719/go.mod h1:I4A+glKBHiTgiEjQiCCQfCAIcIMFGt291SmsvcrFzJA= @@ -2604,62 +2596,72 @@ k8s.io/apimachinery v0.0.0-20190913080033-27d36303b655/go.mod h1:nL6pwRT8NgfF8TT k8s.io/apimachinery v0.18.0-beta.2/go.mod h1:9SnR/e11v5IbyPCGbvJViimtJ0SwHG4nfZFjU77ftcA= k8s.io/apimachinery v0.18.0/go.mod h1:9SnR/e11v5IbyPCGbvJViimtJ0SwHG4nfZFjU77ftcA= k8s.io/apimachinery v0.18.2/go.mod h1:9SnR/e11v5IbyPCGbvJViimtJ0SwHG4nfZFjU77ftcA= +k8s.io/apimachinery v0.18.6/go.mod h1:OaXp26zu/5J7p0f92ASynJa1pZo06YlV9fG7BoWbCko= k8s.io/apimachinery v0.19.0/go.mod h1:DnPGDnARWFvYa3pMHgSxtbZb7gpzzAZ1pTfaUNDVlmA= -k8s.io/apimachinery v0.19.1/go.mod h1:DnPGDnARWFvYa3pMHgSxtbZb7gpzzAZ1pTfaUNDVlmA= +k8s.io/apimachinery v0.19.2/go.mod h1:DnPGDnARWFvYa3pMHgSxtbZb7gpzzAZ1pTfaUNDVlmA= k8s.io/apimachinery v0.20.0/go.mod h1:WlLqWAHZGg07AeltaI0MV5uk1Omp8xaN0JGLY6gkRpU= -k8s.io/apimachinery v0.21.0-beta.1/go.mod h1:ZaN7d/yx5I8h2mk8Nu08sdLigsmkt4flkTxCTc9LElI= k8s.io/apimachinery v0.21.0-rc.0/go.mod h1:jbreFvJo3ov9rj7eWT7+sYiRx+qZuCYXwWT1bcDswPY= k8s.io/apimachinery v0.21.0/go.mod h1:jbreFvJo3ov9rj7eWT7+sYiRx+qZuCYXwWT1bcDswPY= k8s.io/apimachinery v0.21.1/go.mod h1:jbreFvJo3ov9rj7eWT7+sYiRx+qZuCYXwWT1bcDswPY= +k8s.io/apimachinery v0.21.2/go.mod h1:CdTY8fU/BlvAbJ2z/8kBwimGki5Zp8/fbVuLY8gJumM= +k8s.io/apimachinery v0.21.3/go.mod h1:H/IM+5vH9kZRNJ4l3x/fXP/5bOPJaVP/guptnZPeCFI= k8s.io/apimachinery v0.21.4/go.mod h1:H/IM+5vH9kZRNJ4l3x/fXP/5bOPJaVP/guptnZPeCFI= k8s.io/apimachinery v0.22.0-rc.0/go.mod h1:O3oNtNadZdeOMxHFVxOreoznohCpy0z6mocxbZr7oJ0= k8s.io/apimachinery v0.22.0/go.mod h1:O3oNtNadZdeOMxHFVxOreoznohCpy0z6mocxbZr7oJ0= k8s.io/apimachinery v0.22.1/go.mod h1:O3oNtNadZdeOMxHFVxOreoznohCpy0z6mocxbZr7oJ0= -k8s.io/apimachinery v0.22.2 h1:ejz6y/zNma8clPVfNDLnPbleBo6MpoFy/HBiBqCouVk= -k8s.io/apimachinery v0.22.2/go.mod h1:O3oNtNadZdeOMxHFVxOreoznohCpy0z6mocxbZr7oJ0= +k8s.io/apimachinery v0.23.0 h1:mIfWRMjBuMdolAWJ3Fd+aPTMv3X9z+waiARMpvvb0HQ= +k8s.io/apimachinery v0.23.0/go.mod h1:fFCTTBKvKcwTPFzjlcxp91uPFZr+JA0FubU4fLzzFYc= k8s.io/apiserver v0.18.0-beta.2/go.mod h1:bnblMkMoCFnIfVnVftd0SXJPzyvrk3RtaqSbblphF/A= k8s.io/apiserver v0.18.2/go.mod h1:Xbh066NqrZO8cbsoenCwyDJ1OSi8Ag8I2lezeHxzwzw= +k8s.io/apiserver v0.18.6/go.mod h1:Zt2XvTHuaZjBz6EFYzpp+X4hTmgWGy8AthNVnTdm3Wg= k8s.io/apiserver v0.19.0/go.mod h1:XvzqavYj73931x7FLtyagh8WibHpePJ1QwWrSJs2CLk= -k8s.io/apiserver v0.19.1/go.mod h1:iRxYIjA0X2XEyoW8KslN4gDhasfH4bWcjj6ckVeZX28= +k8s.io/apiserver v0.19.2/go.mod h1:FreAq0bJ2vtZFj9Ago/X0oNGC51GfubKK/ViOKfVAOA= k8s.io/apiserver v0.20.0/go.mod h1:6gRIWiOkvGvQt12WTYmsiYoUyYW0FXSiMdNl4m+sxY8= -k8s.io/apiserver v0.21.0-beta.1/go.mod h1:nl/H4DPS1abtRhCj8bhosbyU9XOgnMt0QFK3fAFEhSE= k8s.io/apiserver v0.21.0-rc.0/go.mod h1:QlW7+1CZTZtAcKvJ34/n4DIb8sC93FeQpkd1KSU+Sok= k8s.io/apiserver v0.21.0/go.mod h1:w2YSn4/WIwYuxG5zJmcqtRdtqgW/J2JRgFAqps3bBpg= +k8s.io/apiserver v0.21.2/go.mod h1:lN4yBoGyiNT7SC1dmNk0ue6a5Wi6O3SWOIw91TsucQw= +k8s.io/apiserver v0.21.3/go.mod h1:eDPWlZG6/cCCMj/JBcEpDoK+I+6i3r9GsChYBHSbAzU= +k8s.io/apiserver v0.21.4/go.mod h1:SErUuFBBPZUcD2nsUU8hItxoYheqyYr2o/pCINEPW8g= k8s.io/apiserver v0.22.0-rc.0/go.mod h1:1AfFSkRbaPVFzfSIWd0m/onp49mmAOqXR9qrLJFixlw= k8s.io/apiserver v0.22.0/go.mod h1:04kaIEzIQrTGJ5syLppQWvpkLJXQtJECHmae+ZGc/nc= -k8s.io/apiserver v0.22.2/go.mod h1:vrpMmbyjWrgdyOvZTSpsusQq5iigKNWv9o9KlDAbBHI= -k8s.io/cli-runtime v0.21.0-rc.0 h1:M2cLtWR/LvuSSK8uhdTppcjyd/tqi3Dz5ZiOVfrhDHE= -k8s.io/cli-runtime v0.21.0-rc.0/go.mod h1:Gp9Njd5Z9IayPHKL8AKVVMrdzHrMHN+WnGMHYC7Lsds= -k8s.io/client-go v0.22.0 h1:sD6o9O6tCwUKCENw8v+HFsuAbq2jCu8cWC61/ydwA50= -k8s.io/client-go v0.22.0/go.mod h1:GUjIuXR5PiEv/RVK5OODUsm6eZk7wtSWZSaSJbpFdGg= +k8s.io/apiserver v0.23.0/go.mod h1:Cec35u/9zAepDPPFyT+UMrgqOCjgJ5qtfVJDxjZYmt4= +k8s.io/cli-runtime v0.23.0/go.mod h1:B5N3YH0KP1iKr6gEuJ/RRmGjO0mJQ/f/JrsmEiPQAlU= +k8s.io/client-go v0.23.0 h1:vcsOqyPq7XV3QmQRCBH/t9BICJM9Q1M18qahjv+rebY= +k8s.io/client-go v0.23.0/go.mod h1:hrDnpnK1mSr65lHHcUuIZIXDgEbzc7/683c6hyG4jTA= k8s.io/cluster-bootstrap v0.0.0-20190202014938-c9acc0c1bea2/go.mod h1:iBSm2nwo3OaiuW8VDvc3ySDXK5SKfUrxwPvBloKG7zg= k8s.io/code-generator v0.0.0-20191003035328-700b1226c0bd/go.mod h1:HC9p4y3SBN+txSs8x57qmNPXFZ/CxdCHiDTNnocCSEw= k8s.io/code-generator v0.18.0-beta.2/go.mod h1:+UHX5rSbxmR8kzS+FAv7um6dtYrZokQvjHpDSYRVkTc= k8s.io/code-generator v0.18.0/go.mod h1:+UHX5rSbxmR8kzS+FAv7um6dtYrZokQvjHpDSYRVkTc= k8s.io/code-generator v0.18.2/go.mod h1:+UHX5rSbxmR8kzS+FAv7um6dtYrZokQvjHpDSYRVkTc= +k8s.io/code-generator v0.18.6/go.mod h1:TgNEVx9hCyPGpdtCWA34olQYLkh3ok9ar7XfSsr8b6c= k8s.io/code-generator v0.19.0/go.mod h1:moqLn7w0t9cMs4+5CQyxnfA/HV8MF6aAVENF+WZZhgk= -k8s.io/code-generator v0.19.1/go.mod h1:moqLn7w0t9cMs4+5CQyxnfA/HV8MF6aAVENF+WZZhgk= +k8s.io/code-generator v0.19.2/go.mod h1:moqLn7w0t9cMs4+5CQyxnfA/HV8MF6aAVENF+WZZhgk= k8s.io/code-generator v0.20.0/go.mod h1:UsqdF+VX4PU2g46NC2JRs4gc+IfrctnwHb76RNbWHJg= -k8s.io/code-generator v0.21.0-beta.1/go.mod h1:IpCUojpiKp25KNB3/UbEeElznqpQUMvhAOUoC7AbISY= k8s.io/code-generator v0.21.0-rc.0/go.mod h1:hUlps5+9QaTrKx+jiM4rmq7YmH8wPOIko64uZCHDh6Q= k8s.io/code-generator v0.21.0/go.mod h1:hUlps5+9QaTrKx+jiM4rmq7YmH8wPOIko64uZCHDh6Q= +k8s.io/code-generator v0.21.2/go.mod h1:8mXJDCB7HcRo1xiEQstcguZkbxZaqeUOrO9SsicWs3U= +k8s.io/code-generator v0.21.3/go.mod h1:K3y0Bv9Cz2cOW2vXUrNZlFbflhuPvuadW6JdnN6gGKo= +k8s.io/code-generator v0.21.4/go.mod h1:K3y0Bv9Cz2cOW2vXUrNZlFbflhuPvuadW6JdnN6gGKo= k8s.io/code-generator v0.22.0-rc.0/go.mod h1:eV77Y09IopzeXOJzndrDyCI88UBok2h6WxAlBwpxa+o= k8s.io/code-generator v0.22.0/go.mod h1:eV77Y09IopzeXOJzndrDyCI88UBok2h6WxAlBwpxa+o= k8s.io/code-generator v0.22.1/go.mod h1:eV77Y09IopzeXOJzndrDyCI88UBok2h6WxAlBwpxa+o= -k8s.io/code-generator v0.22.2/go.mod h1:eV77Y09IopzeXOJzndrDyCI88UBok2h6WxAlBwpxa+o= +k8s.io/code-generator v0.23.0/go.mod h1:vQvOhDXhuzqiVfM/YHp+dmg10WDZCchJVObc9MvowsE= k8s.io/component-base v0.18.0-beta.2/go.mod h1:HVk5FpRnyzQ/MjBr9//e/yEBjTVa2qjGXCTuUzcD7ks= k8s.io/component-base v0.18.2/go.mod h1:kqLlMuhJNHQ9lz8Z7V5bxUUtjFZnrypArGl58gmDfUM= +k8s.io/component-base v0.18.6/go.mod h1:knSVsibPR5K6EW2XOjEHik6sdU5nCvKMrzMt2D4In14= k8s.io/component-base v0.19.0/go.mod h1:dKsY8BxkA+9dZIAh2aWJLL/UdASFDNtGYTCItL4LM7Y= -k8s.io/component-base v0.19.1/go.mod h1:b0vDKYa8EdJJ8dHUA6fGPj4z8taqGks5mfZvp3p/jVo= +k8s.io/component-base v0.19.2/go.mod h1:g5LrsiTiabMLZ40AR6Hl45f088DevyGY+cCE2agEIVo= k8s.io/component-base v0.20.0/go.mod h1:wKPj+RHnAr8LW2EIBIK7AxOHPde4gme2lzXwVSoRXeA= -k8s.io/component-base v0.21.0-beta.1/go.mod h1:WPMZyV0sNk3ruzA8cWt1EO2KWAnLDK2docEC14JWbTM= k8s.io/component-base v0.21.0-rc.0/go.mod h1:XlP0bM7QJFWRGZYPc5NmphkvsYQ+o7804HWH3GTGjDY= k8s.io/component-base v0.21.0/go.mod h1:qvtjz6X0USWXbgmbfXR+Agik4RZ3jv2Bgr5QnZzdPYw= +k8s.io/component-base v0.21.2/go.mod h1:9lvmIThzdlrJj5Hp8Z/TOgIkdfsNARQ1pT+3PByuiuc= +k8s.io/component-base v0.21.3/go.mod h1:kkuhtfEHeZM6LkX0saqSK8PbdO7A0HigUngmhhrwfGQ= +k8s.io/component-base v0.21.4/go.mod h1:ZKG0eHVX+tUDcaoIGpU3Vtk4TIjMddN9uhEWDmW6Nyg= k8s.io/component-base v0.22.0-rc.0/go.mod h1:DKSub/kewg24bK+3ZJ/csu86fSBYpGdYk837eCTvEKg= k8s.io/component-base v0.22.0/go.mod h1:SXj6Z+V6P6GsBhHZVbWCw9hFjUdUYnJerlhhPnYCBCg= -k8s.io/component-base v0.22.2 h1:vNIvE0AIrLhjX8drH0BgCNJcR4QZxMXcJzBsDplDx9M= -k8s.io/component-base v0.22.2/go.mod h1:5Br2QhI9OTe79p+TzPe9JKNQYvEKbq9rTJDWllunGug= -k8s.io/component-helpers v0.21.0-rc.0/go.mod h1:A8RfzdPEZoysfI5C0RExdjy7Zy/RZET3tcUmt7BMWdc= +k8s.io/component-base v0.23.0 h1:UAnyzjvVZ2ZR1lF35YwtNY6VMN94WtOnArcXBu34es8= +k8s.io/component-base v0.23.0/go.mod h1:DHH5uiFvLC1edCpvcTDV++NKULdYYU6pR9Tt3HIKMKI= +k8s.io/component-helpers v0.23.0/go.mod h1:liXMh6FZS4qamKtMJQ7uLHnFe3tlC86RX5mJEk/aerg= k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= k8s.io/gengo v0.0.0-20190822140433-26a664648505/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= k8s.io/gengo v0.0.0-20190907103519-ebc107f98eab/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= @@ -2668,6 +2670,7 @@ k8s.io/gengo v0.0.0-20200413195148-3a45101e95ac/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8 k8s.io/gengo v0.0.0-20200428234225-8167cfdcfc14/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= k8s.io/gengo v0.0.0-20201113003025-83324d819ded/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= k8s.io/gengo v0.0.0-20201214224949-b6c5ce23f027/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= +k8s.io/gengo v0.0.0-20210813121822-485abfe95c7c/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= k8s.io/klog v0.0.0-20181102134211-b9b56d5dfc92/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= k8s.io/klog v0.0.0-20190306015804-8e90cee79f82/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= k8s.io/klog v0.3.0/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= @@ -2679,44 +2682,47 @@ k8s.io/klog/v2 v2.0.0/go.mod h1:PBfzABfn139FHAV07az/IF9Wp1bkk3vpT2XSJ76fSDE= k8s.io/klog/v2 v2.2.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= k8s.io/klog/v2 v2.3.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= k8s.io/klog/v2 v2.4.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= -k8s.io/klog/v2 v2.5.0/go.mod h1:hy9LJ/NvuK+iVyP4Ehqva4HxZG/oXyIS3n3Jmire4Ec= k8s.io/klog/v2 v2.8.0/go.mod h1:hy9LJ/NvuK+iVyP4Ehqva4HxZG/oXyIS3n3Jmire4Ec= -k8s.io/klog/v2 v2.9.0 h1:D7HV+n1V57XeZ0m6tdRkfknthUaM06VFbWldOFh8kzM= k8s.io/klog/v2 v2.9.0/go.mod h1:hy9LJ/NvuK+iVyP4Ehqva4HxZG/oXyIS3n3Jmire4Ec= +k8s.io/klog/v2 v2.30.0 h1:bUO6drIvCIsvZ/XFgfxoGFQU/a4Qkh0iAlvUR7vlHJw= +k8s.io/klog/v2 v2.30.0/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= k8s.io/kube-aggregator v0.18.0-beta.2/go.mod h1:O3Td9mheraINbLHH4pzoFP2gRzG0Wk1COqzdSL4rBPk= k8s.io/kube-aggregator v0.18.2/go.mod h1:ijq6FnNUoKinA6kKbkN6svdTacSoQVNtKqmQ1+XJEYQ= k8s.io/kube-aggregator v0.19.0/go.mod h1:1Ln45PQggFAG8xOqWPIYMxUq8WNtpPnYsbUJ39DpF/A= -k8s.io/kube-aggregator v0.19.1/go.mod h1:oAj1kWeSDCh7sdzUOs6XXPn/jbzJY+yGGxDd0QyLJC8= k8s.io/kube-aggregator v0.20.0/go.mod h1:3Is/gzzWmhhG/rA3CpA1+eVye87lreBQDFGcAGT7gzo= k8s.io/kube-aggregator v0.21.0-rc.0/go.mod h1:M+whOmsAeQf8ObJ0/eO9Af1Dz2UQEB9OW9BWmt9b2sU= -k8s.io/kube-aggregator v0.22.0-rc.0 h1:FenE183nFPnFOFzZmwha8ElJ2/ByvcPu3tpEfx82xgU= k8s.io/kube-aggregator v0.22.0-rc.0/go.mod h1:g0xtiBSsbMKvewN7xR/Icib4TrHxtvrJcHtYvFsgw7k= +k8s.io/kube-openapi v0.0.0-20180731170545-e3762e86a74c/go.mod h1:BXM9ceUBTj2QnfH2MK1odQs778ajze1RxcmP6S8RVVc= k8s.io/kube-openapi v0.0.0-20190228160746-b3a7cee44a30/go.mod h1:BXM9ceUBTj2QnfH2MK1odQs778ajze1RxcmP6S8RVVc= k8s.io/kube-openapi v0.0.0-20190816220812-743ec37842bf/go.mod h1:1TqjTSzOxsLGIKfj0lK8EeCP7K1iUG65v09OM0/WG5E= k8s.io/kube-openapi v0.0.0-20200121204235-bf4fb3bd569c/go.mod h1:GRQhZsXIAJ1xR0C9bd8UpWHZ5plfAS9fzPjJuQ6JL3E= +k8s.io/kube-openapi v0.0.0-20200410145947-61e04a5be9a6/go.mod h1:GRQhZsXIAJ1xR0C9bd8UpWHZ5plfAS9fzPjJuQ6JL3E= k8s.io/kube-openapi v0.0.0-20200805222855-6aeccd4b50c6/go.mod h1:UuqjUnNftUyPE5H64/qeyjQoUZhGpeFDVdxjTeEVN2o= -k8s.io/kube-openapi v0.0.0-20200831175022-64514a1d5d59/go.mod h1:UuqjUnNftUyPE5H64/qeyjQoUZhGpeFDVdxjTeEVN2o= k8s.io/kube-openapi v0.0.0-20201113171705-d219536bb9fd/go.mod h1:WOJ3KddDSol4tAGcJo0Tvi+dK12EcqSLqcWsryKMpfM= k8s.io/kube-openapi v0.0.0-20210305001622-591a79e4bda7/go.mod h1:wXW5VT87nVfh/iLV8FpR2uDvrFyomxbtb1KivDbvPTE= -k8s.io/kube-openapi v0.0.0-20210421082810-95288971da7e h1:KLHHjkdQFomZy8+06csTWZ0m1343QqxZhR2LJ1OxCYM= k8s.io/kube-openapi v0.0.0-20210421082810-95288971da7e/go.mod h1:vHXdDvt9+2spS2Rx9ql3I8tycm3H9FDfdUoIuKCefvw= -k8s.io/kubectl v0.21.0-rc.0 h1:UDHfpjRunMTqSyRR8GC7ywZ1ylmM2CpXkqRPqCPTXwk= -k8s.io/kubectl v0.21.0-rc.0/go.mod h1:eOKzb5p2/9pNzt2TQpVSzfB/41W6ZMm0JbJEIvyH08U= +k8s.io/kube-openapi v0.0.0-20211115234752-e816edb12b65 h1:E3J9oCLlaobFUqsjG9DfKbP2BmgwBL2p7pn0A3dG9W4= +k8s.io/kube-openapi v0.0.0-20211115234752-e816edb12b65/go.mod h1:sX9MT8g7NVZM5lVL/j8QyCCJe8YSMW30QvGZWaCIDIk= +k8s.io/kubectl v0.23.0/go.mod h1:TfcGEs3u4dkmoC2eku1GYymdGaMtPMcaLLFrX/RB2kI= k8s.io/kubelet v0.19.0/go.mod h1:cGds22piF/LnFzfAaIT+efvOYBHVYdunqka6NVuNw9g= -k8s.io/metrics v0.21.0-rc.0/go.mod h1:iCF67TNbrhChr/eb99uHt0H1hE7Rd1EC2Ic/yknzIE4= +k8s.io/metrics v0.23.0/go.mod h1:NDiZTwppEtAuKJ1Rxt3S4dhyRzdp6yUcJf0vo023dPo= +k8s.io/utils v0.0.0-20190506122338-8fab8cb257d5/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= k8s.io/utils v0.0.0-20190529001817-6999998975a7/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= k8s.io/utils v0.0.0-20200229041039-0a110f9eb7ab/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= k8s.io/utils v0.0.0-20200324210504-a9aa75ae1b89/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= k8s.io/utils v0.0.0-20200327001022-6496210b90e8/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= k8s.io/utils v0.0.0-20200411171748-3d5a2fe318e4/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= +k8s.io/utils v0.0.0-20200603063816-c1c6865ac451/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20200729134348-d5654de09c73/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= -k8s.io/utils v0.0.0-20200821003339-5e75c0163111/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= +k8s.io/utils v0.0.0-20200912215256-4140de9c8800/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20201110183641-67b214c5f920/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20210111153108-fddb29f9d009/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= +k8s.io/utils v0.0.0-20210527160623-6fdb442a123b/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20210707171843-4b05e18ac7d9/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= +k8s.io/utils v0.0.0-20210722164352-7f3ee0f31471/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20210802155522-efc7438f0176/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= -k8s.io/utils v0.0.0-20210819203725-bdf08cb9a70a h1:8dYfu/Fc9Gz2rNJKB9IQRGgQOh2clmRzNIPPY1xLY5g= -k8s.io/utils v0.0.0-20210819203725-bdf08cb9a70a/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= +k8s.io/utils v0.0.0-20210930125809-cb0fa318a74b h1:wxEMGetGMur3J1xuGLQY7GEQYg9bZxKn3tKo5k/eYcs= +k8s.io/utils v0.0.0-20210930125809-cb0fa318a74b/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= layeh.com/radius v0.0.0-20190322222518-890bc1058917/go.mod h1:fywZKyu//X7iRzaxLgPWsvc0L26IUpVvE/aeIL2JtIQ= 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= @@ -2724,12 +2730,10 @@ modernc.org/mathutil v1.0.0/go.mod h1:wU0vUrJsVWBZ4P6e7xtFJEhFSNsfRLJ8H458uRjg03 modernc.org/strutil v1.0.0/go.mod h1:lstksw84oURvj9y3tn8lGvRxyRC1S2+g5uuIzNfIOBs= modernc.org/xc v1.0.0/go.mod h1:mRNCo0bvLjGhHO9WsyuKVU4q0ceiDDDoEeWDJHrNx8I= mvdan.cc/gofumpt v0.0.0-20200709182408-4fd085cb6d5f/go.mod h1:9VQ397fNXEnF84t90W4r4TRCQK+pg9f8ugVfyj+S26w= -mvdan.cc/gofumpt v0.0.0-20200802201014-ab5a8192947d/go.mod h1:bzrjFmaD6+xqohD3KYP0H2FEuxknnBmyyOxdhLdaIws= mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed/go.mod h1:Xkxe497xwlCKkIaQYRfC7CSLworTXY9RMqwhhCm+8Nc= mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b/go.mod h1:2odslEg/xrtNQqCYg2/jCoyKnw3vv5biOc3JnIcYfL4= mvdan.cc/unparam v0.0.0-20190209190245-fbb59629db34/go.mod h1:H6SUd1XjIs+qQCyskXg5OFSrilMRUkD8ePJpHKDPaeY= mvdan.cc/unparam v0.0.0-20190720180237-d51796306d8f/go.mod h1:4G1h5nDURzA3bwVMZIVpwbkw+04kSxk3rAtzlimaUJw= -mvdan.cc/unparam v0.0.0-20200501210554-b37ab49443f7/go.mod h1:HGC5lll35J70Y5v7vCGb9oLhHoScFwkHDJm/05RdSTc= rsc.io/binaryregexp v0.2.0 h1:HfqmD5MEmC0zvwBuF187nq9mdnXjXsSivRiXN7SmRkE= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= @@ -2738,34 +2742,47 @@ sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.7/go.mod h1:PHgbrJT sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.9/go.mod h1:dzAXnQbTRyDlZPJX2SUPEqvnB+j7AJjtlox7PEwigU0= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.14/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.15/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.19/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.21/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.22/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= -sigs.k8s.io/controller-runtime v0.9.0-alpha.1 h1:yIYTxDHQfcrYWO1hjZvHhjkGY1fYFo1k07FzlTono4E= -sigs.k8s.io/controller-runtime v0.9.0-alpha.1/go.mod h1:BARxVvgj+8Ihw9modUvYh7/OJmjxuBtLK8P36jdf7rY= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.25/go.mod h1:Mlj9PNLmG9bZ6BHFwFKDo5afkpWyUISkb9Me0GnK66I= +sigs.k8s.io/controller-runtime v0.0.0-20190520212815-96b67f231945/go.mod h1:TSH2R0nSz4WAlUUlNnOFcOR/VUhfwBLlmtq2X6AiQCA= +sigs.k8s.io/controller-runtime v0.6.0/go.mod h1:CpYf5pdNY/B352A1TFLAS2JVSlnGQ5O2cftPHndTroo= +sigs.k8s.io/controller-runtime v0.6.2/go.mod h1:vhcq/rlnENJ09SIRp3EveTaZ0yqH526hjf9iJdbUJ/E= +sigs.k8s.io/controller-runtime v0.7.0/go.mod h1:pJ3YBrJiAqMAZKi6UVGuE98ZrroV1p+pIhoHsMm9wdU= +sigs.k8s.io/controller-runtime v0.9.0-alpha.1.0.20210413130450-7ef2da0bc161/go.mod h1:ufPDuvefw2Y1KnBgHQrLdOjueYlj+XJV2AszbT+WTxs= +sigs.k8s.io/controller-runtime v0.9.0-beta.1.0.20210512131817-ce2f0c92d77e/go.mod h1:ufPDuvefw2Y1KnBgHQrLdOjueYlj+XJV2AszbT+WTxs= +sigs.k8s.io/controller-runtime v0.9.3/go.mod h1:TxzMCHyEUpaeuOiZx/bIdc2T81vfs/aKdvJt9wuu0zk= +sigs.k8s.io/controller-runtime v0.9.6/go.mod h1:q6PpkM5vqQubEKUKOM6qr06oXGzOBcCby1DA9FbyZeA= +sigs.k8s.io/controller-runtime v0.9.7/go.mod h1:nExcHcQ2zvLMeoO9K7rOesGCmgu32srN5SENvpAEbGA= +sigs.k8s.io/controller-runtime v0.11.0 h1:DqO+c8mywcZLFJWILq4iktoECTyn30Bkj0CwgqMpZWQ= +sigs.k8s.io/controller-runtime v0.11.0/go.mod h1:KKwLiTooNGu+JmLZGn9Sl3Gjmfj66eMbCQznLP5zcqA= sigs.k8s.io/controller-tools v0.3.1-0.20200617211605-651903477185 h1:wLsmaqTEgs3DIfNzr0u/AfPHSVJbWHj/eevcS4AFvFE= sigs.k8s.io/controller-tools v0.3.1-0.20200617211605-651903477185/go.mod h1:JuPG+FXjAeZL7eGmTuXUJduEMlI2/kGqb0rUGlVi+Yo= +sigs.k8s.io/json v0.0.0-20211020170558-c049b76a60c6 h1:fD1pz4yfdADVNfFmcP2aBEtudwUQ1AlLnRBALr33v3s= +sigs.k8s.io/json v0.0.0-20211020170558-c049b76a60c6/go.mod h1:p4QtZmO4uMYipTQNzagwnNoseA6OxSUutVw05NhYDRs= sigs.k8s.io/kube-storage-version-migrator v0.0.3/go.mod h1:mXfSLkx9xbJHQsgNDDUZK/iQTs2tMbx/hsJlWe6Fthw= sigs.k8s.io/kube-storage-version-migrator v0.0.4/go.mod h1:mXfSLkx9xbJHQsgNDDUZK/iQTs2tMbx/hsJlWe6Fthw= -sigs.k8s.io/kustomize/api v0.8.5 h1:bfCXGXDAbFbb/Jv5AhMj2BB8a5VAJuuQ5/KU69WtDjQ= -sigs.k8s.io/kustomize/api v0.8.5/go.mod h1:M377apnKT5ZHJS++6H4rQoCHmWtt6qTpp3mbe7p6OLY= -sigs.k8s.io/kustomize/cmd/config v0.9.7/go.mod h1:MvXCpHs77cfyxRmCNUQjIqCmZyYsbn5PyQpWiq44nW0= -sigs.k8s.io/kustomize/kustomize/v4 v4.0.5/go.mod h1:C7rYla7sI8EnxHE/xEhRBSHMNfcL91fx0uKmUlUhrBk= -sigs.k8s.io/kustomize/kyaml v0.10.15 h1:dSLgG78KyaxN4HylPXdK+7zB3k7sW6q3IcCmcfKA+aI= -sigs.k8s.io/kustomize/kyaml v0.10.15/go.mod h1:mlQFagmkm1P+W4lZJbJ/yaxMd8PqMRSC4cPcfUVt5Hg= +sigs.k8s.io/kustomize/api v0.10.1/go.mod h1:2FigT1QN6xKdcnGS2Ppp1uIWrtWN28Ms8A3OZUZhwr8= +sigs.k8s.io/kustomize/cmd/config v0.10.2/go.mod h1:K2aW7nXJ0AaT+VA/eO0/dzFLxmpFcTzudmAgDwPY1HQ= +sigs.k8s.io/kustomize/kustomize/v4 v4.4.1/go.mod h1:qOKJMMz2mBP+vcS7vK+mNz4HBLjaQSWRY22EF6Tb7Io= +sigs.k8s.io/kustomize/kyaml v0.13.0/go.mod h1:FTJxEZ86ScK184NpGSAQcfEqee0nul8oLCK30D47m4E= sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e h1:4Z09Hglb792X0kfOBBJUPFEyvVfQWrYT/l8h5EKA6JQ= sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI= sigs.k8s.io/structured-merge-diff/v3 v3.0.0-20200116222232-67a7b8c61874/go.mod h1:PlARxl6Hbt/+BC80dRLi1qAmnMqwqDg62YvvVkZjemw= sigs.k8s.io/structured-merge-diff/v3 v3.0.0/go.mod h1:PlARxl6Hbt/+BC80dRLi1qAmnMqwqDg62YvvVkZjemw= sigs.k8s.io/structured-merge-diff/v4 v4.0.1/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.0.2/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= -sigs.k8s.io/structured-merge-diff/v4 v4.0.3/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.1.0/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.1.1/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= -sigs.k8s.io/structured-merge-diff/v4 v4.1.2 h1:Hr/htKFmJEbtMgS/UD0N+gtgctAqz81t3nu+sPzynno= sigs.k8s.io/structured-merge-diff/v4 v4.1.2/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4= +sigs.k8s.io/structured-merge-diff/v4 v4.2.0 h1:kDvPBbnPk+qYmkHmSo8vKGp438IASWofnbbUKDE/bv0= +sigs.k8s.io/structured-merge-diff/v4 v4.2.0/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4= +sigs.k8s.io/testing_frameworks v0.1.1/go.mod h1:VVBKrHmJ6Ekkfz284YKhQePcdycOzNH9qL6ht1zEr/U= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= -sigs.k8s.io/yaml v1.2.0 h1:kr/MCeFWJWTwyaHoR9c8EjH9OumOmoF9YGiZd7lFm/Q= sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= +sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= +sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= vbom.ml/util v0.0.0-20180919145318-efcd4e0f9787/go.mod h1:so/NYdZXCz+E3ZpW0uAoCj6uzU2+8OWDFv/HxUSs7kI= diff --git a/hack/verify-codegen.sh b/hack/verify-codegen.sh index 14f4a4500fe..97434f91118 100755 --- a/hack/verify-codegen.sh +++ b/hack/verify-codegen.sh @@ -10,6 +10,6 @@ else --env IS_CONTAINER=TRUE \ --volume "${PWD}:/go/src/github.com/openshift/installer:z" \ --workdir /go/src/github.com/openshift/installer \ - docker.io/openshift/origin-release:golang-1.16 \ + docker.io/golang:1.17 \ ./hack/verify-codegen.sh "${@}" fi diff --git a/pkg/terraform/exec/plugins/kubernetes.go b/pkg/terraform/exec/plugins/kubernetes.go deleted file mode 100644 index f19ee573941..00000000000 --- a/pkg/terraform/exec/plugins/kubernetes.go +++ /dev/null @@ -1,14 +0,0 @@ -package plugins - -import ( - "github.com/hashicorp/terraform-plugin-sdk/plugin" - "github.com/hashicorp/terraform-provider-kubernetes/kubernetes" -) - -func init() { - exec := func() { - plugin.Serve(&plugin.ServeOpts{ - ProviderFunc: kubernetes.Provider}) - } - KnownPlugins["terraform-provider-kubernetes"] = exec -} diff --git a/vendor/github.com/Azure/go-ansiterm/LICENSE b/vendor/github.com/Azure/go-ansiterm/LICENSE deleted file mode 100644 index e3d9a64d1d8..00000000000 --- a/vendor/github.com/Azure/go-ansiterm/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Microsoft Corporation - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/Azure/go-ansiterm/README.md b/vendor/github.com/Azure/go-ansiterm/README.md deleted file mode 100644 index 261c041e7ab..00000000000 --- a/vendor/github.com/Azure/go-ansiterm/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# go-ansiterm - -This is a cross platform Ansi Terminal Emulation library. It reads a stream of Ansi characters and produces the appropriate function calls. The results of the function calls are platform dependent. - -For example the parser might receive "ESC, [, A" as a stream of three characters. This is the code for Cursor Up (http://www.vt100.net/docs/vt510-rm/CUU). The parser then calls the cursor up function (CUU()) on an event handler. The event handler determines what platform specific work must be done to cause the cursor to move up one position. - -The parser (parser.go) is a partial implementation of this state machine (http://vt100.net/emu/vt500_parser.png). There are also two event handler implementations, one for tests (test_event_handler.go) to validate that the expected events are being produced and called, the other is a Windows implementation (winterm/win_event_handler.go). - -See parser_test.go for examples exercising the state machine and generating appropriate function calls. - ------ -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/vendor/github.com/Azure/go-ansiterm/constants.go b/vendor/github.com/Azure/go-ansiterm/constants.go deleted file mode 100644 index 96504a33bc9..00000000000 --- 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 8d66e777c03..00000000000 --- 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 bcbe00d0c5e..00000000000 --- 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 7ed5e01c342..00000000000 --- 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 1c719db9e48..00000000000 --- 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 6390abd231b..00000000000 --- 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 98087b38c20..00000000000 --- 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 52451e94693..00000000000 --- 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 593b10ab696..00000000000 --- 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 03cec7ada62..00000000000 --- 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 de0a1f9cde3..00000000000 --- 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 0bb5e51e9aa..00000000000 --- 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 f2ea1fcd12d..00000000000 --- 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 392114493a2..00000000000 --- 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 5599082ae9c..00000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go +++ /dev/null @@ -1,196 +0,0 @@ -// +build windows - -package winterm - -import ( - "fmt" - "os" - "strconv" - "strings" - "syscall" - - "github.com/Azure/go-ansiterm" - windows "golang.org/x/sys/windows" -) - -// Windows keyboard constants -// See https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx. -const ( - VK_PRIOR = 0x21 // PAGE UP key - VK_NEXT = 0x22 // PAGE DOWN key - VK_END = 0x23 // END key - VK_HOME = 0x24 // HOME key - VK_LEFT = 0x25 // LEFT ARROW key - VK_UP = 0x26 // UP ARROW key - VK_RIGHT = 0x27 // RIGHT ARROW key - VK_DOWN = 0x28 // DOWN ARROW key - VK_SELECT = 0x29 // SELECT key - VK_PRINT = 0x2A // PRINT key - VK_EXECUTE = 0x2B // EXECUTE key - VK_SNAPSHOT = 0x2C // PRINT SCREEN key - VK_INSERT = 0x2D // INS key - VK_DELETE = 0x2E // DEL key - VK_HELP = 0x2F // HELP key - VK_F1 = 0x70 // F1 key - VK_F2 = 0x71 // F2 key - VK_F3 = 0x72 // F3 key - VK_F4 = 0x73 // F4 key - VK_F5 = 0x74 // F5 key - VK_F6 = 0x75 // F6 key - VK_F7 = 0x76 // F7 key - VK_F8 = 0x77 // F8 key - VK_F9 = 0x78 // F9 key - VK_F10 = 0x79 // F10 key - VK_F11 = 0x7A // F11 key - VK_F12 = 0x7B // F12 key - - RIGHT_ALT_PRESSED = 0x0001 - LEFT_ALT_PRESSED = 0x0002 - RIGHT_CTRL_PRESSED = 0x0004 - LEFT_CTRL_PRESSED = 0x0008 - SHIFT_PRESSED = 0x0010 - NUMLOCK_ON = 0x0020 - SCROLLLOCK_ON = 0x0040 - CAPSLOCK_ON = 0x0080 - ENHANCED_KEY = 0x0100 -) - -type ansiCommand struct { - CommandBytes []byte - Command string - Parameters []string - IsSpecial bool -} - -func newAnsiCommand(command []byte) *ansiCommand { - - if isCharacterSelectionCmdChar(command[1]) { - // Is Character Set Selection commands - return &ansiCommand{ - CommandBytes: command, - Command: string(command), - IsSpecial: true, - } - } - - // last char is command character - lastCharIndex := len(command) - 1 - - ac := &ansiCommand{ - CommandBytes: command, - Command: string(command[lastCharIndex]), - IsSpecial: false, - } - - // more than a single escape - if lastCharIndex != 0 { - start := 1 - // skip if double char escape sequence - if command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_ESCAPE_SECONDARY { - start++ - } - // convert this to GetNextParam method - ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ansiterm.ANSI_PARAMETER_SEP) - } - - return ac -} - -func (ac *ansiCommand) paramAsSHORT(index int, defaultValue int16) int16 { - if index < 0 || index >= len(ac.Parameters) { - return defaultValue - } - - param, err := strconv.ParseInt(ac.Parameters[index], 10, 16) - if err != nil { - return defaultValue - } - - return int16(param) -} - -func (ac *ansiCommand) String() string { - return fmt.Sprintf("0x%v \"%v\" (\"%v\")", - bytesToHex(ac.CommandBytes), - ac.Command, - strings.Join(ac.Parameters, "\",\"")) -} - -// isAnsiCommandChar returns true if the passed byte falls within the range of ANSI commands. -// See http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html. -func isAnsiCommandChar(b byte) bool { - switch { - case ansiterm.ANSI_COMMAND_FIRST <= b && b <= ansiterm.ANSI_COMMAND_LAST && b != ansiterm.ANSI_ESCAPE_SECONDARY: - return true - case b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_OSC || b == ansiterm.ANSI_CMD_DECPAM || b == ansiterm.ANSI_CMD_DECPNM: - // non-CSI escape sequence terminator - return true - case b == ansiterm.ANSI_CMD_STR_TERM || b == ansiterm.ANSI_BEL: - // String escape sequence terminator - return true - } - return false -} - -func isXtermOscSequence(command []byte, current byte) bool { - return (len(command) >= 2 && command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_CMD_OSC && current != ansiterm.ANSI_BEL) -} - -func isCharacterSelectionCmdChar(b byte) bool { - return (b == ansiterm.ANSI_CMD_G0 || b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_G2 || b == ansiterm.ANSI_CMD_G3) -} - -// bytesToHex converts a slice of bytes to a human-readable string. -func bytesToHex(b []byte) string { - hex := make([]string, len(b)) - for i, ch := range b { - hex[i] = fmt.Sprintf("%X", ch) - } - return strings.Join(hex, "") -} - -// ensureInRange adjusts the passed value, if necessary, to ensure it is within -// the passed min / max range. -func ensureInRange(n int16, min int16, max int16) int16 { - if n < min { - return min - } else if n > max { - return max - } else { - return n - } -} - -func GetStdFile(nFile int) (*os.File, uintptr) { - var file *os.File - - // syscall uses negative numbers - // windows package uses very big uint32 - // Keep these switches split so we don't have to convert ints too much. - switch uint32(nFile) { - case windows.STD_INPUT_HANDLE: - file = os.Stdin - case windows.STD_OUTPUT_HANDLE: - file = os.Stdout - case windows.STD_ERROR_HANDLE: - file = os.Stderr - default: - switch nFile { - case syscall.STD_INPUT_HANDLE: - file = os.Stdin - case syscall.STD_OUTPUT_HANDLE: - file = os.Stdout - case syscall.STD_ERROR_HANDLE: - file = os.Stderr - default: - panic(fmt.Errorf("Invalid standard handle identifier: %v", nFile)) - } - } - - fd, err := syscall.GetStdHandle(nFile) - if err != nil { - panic(fmt.Errorf("Invalid standard handle identifier: %v -- %v", nFile, err)) - } - - return file, uintptr(fd) -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/api.go b/vendor/github.com/Azure/go-ansiterm/winterm/api.go deleted file mode 100644 index 6055e33b912..00000000000 --- 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 cbec8f728f4..00000000000 --- 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 3ee06ea7282..00000000000 --- 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 244b5fa25ef..00000000000 --- 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 2d27fa1d028..00000000000 --- 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 afa7635d77b..00000000000 --- 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 2d40fb75ad0..00000000000 --- 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/MakeNowJust/heredoc/LICENSE b/vendor/github.com/MakeNowJust/heredoc/LICENSE deleted file mode 100644 index 6d0eb9d5d68..00000000000 --- a/vendor/github.com/MakeNowJust/heredoc/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014-2019 TSUYUSATO Kitsune - -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/MakeNowJust/heredoc/README.md b/vendor/github.com/MakeNowJust/heredoc/README.md deleted file mode 100644 index e9924d2974a..00000000000 --- a/vendor/github.com/MakeNowJust/heredoc/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# heredoc - -[![Build Status](https://circleci.com/gh/MakeNowJust/heredoc.svg?style=svg)](https://circleci.com/gh/MakeNowJust/heredoc) [![GoDoc](https://godoc.org/github.com/MakeNowJusti/heredoc?status.svg)](https://godoc.org/github.com/MakeNowJust/heredoc) - -## About - -Package heredoc provides the here-document with keeping indent. - -## Install - -```console -$ go get github.com/MakeNowJust/heredoc -``` - -## Import - -```go -// usual -import "github.com/MakeNowJust/heredoc" -``` - -## Example - -```go -package main - -import ( - "fmt" - "github.com/MakeNowJust/heredoc" -) - -func main() { - fmt.Println(heredoc.Doc(` - Lorem ipsum dolor sit amet, consectetur adipisicing elit, - sed do eiusmod tempor incididunt ut labore et dolore magna - aliqua. Ut enim ad minim veniam, ... - `)) - // Output: - // Lorem ipsum dolor sit amet, consectetur adipisicing elit, - // sed do eiusmod tempor incididunt ut labore et dolore magna - // aliqua. Ut enim ad minim veniam, ... - // -} -``` - -## API Document - - - [heredoc - GoDoc](https://godoc.org/github.com/MakeNowJust/heredoc) - -## License - -This software is released under the MIT License, see LICENSE. diff --git a/vendor/github.com/MakeNowJust/heredoc/heredoc.go b/vendor/github.com/MakeNowJust/heredoc/heredoc.go deleted file mode 100644 index 1fc04695551..00000000000 --- a/vendor/github.com/MakeNowJust/heredoc/heredoc.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) 2014-2019 TSUYUSATO Kitsune -// This software is released under the MIT License. -// http://opensource.org/licenses/mit-license.php - -// Package heredoc provides creation of here-documents from raw strings. -// -// Golang supports raw-string syntax. -// -// doc := ` -// Foo -// Bar -// ` -// -// But raw-string cannot recognize indentation. Thus such content is an indented string, equivalent to -// -// "\n\tFoo\n\tBar\n" -// -// I dont't want this! -// -// However this problem is solved by package heredoc. -// -// doc := heredoc.Doc(` -// Foo -// Bar -// `) -// -// Is equivalent to -// -// "Foo\nBar\n" -package heredoc - -import ( - "fmt" - "strings" - "unicode" -) - -const maxInt = int(^uint(0) >> 1) - -// Doc returns un-indented string as here-document. -func Doc(raw string) string { - skipFirstLine := false - if len(raw) > 0 && raw[0] == '\n' { - raw = raw[1:] - } else { - skipFirstLine = true - } - - lines := strings.Split(raw, "\n") - - minIndentSize := getMinIndent(lines, skipFirstLine) - lines = removeIndentation(lines, minIndentSize, skipFirstLine) - - return strings.Join(lines, "\n") -} - -// getMinIndent calculates the minimum indentation in lines, excluding empty lines. -func getMinIndent(lines []string, skipFirstLine bool) int { - minIndentSize := maxInt - - for i, line := range lines { - if i == 0 && skipFirstLine { - continue - } - - indentSize := 0 - for _, r := range []rune(line) { - if unicode.IsSpace(r) { - indentSize += 1 - } else { - break - } - } - - if len(line) == indentSize { - if i == len(lines)-1 && indentSize < minIndentSize { - lines[i] = "" - } - } else if indentSize < minIndentSize { - minIndentSize = indentSize - } - } - return minIndentSize -} - -// removeIndentation removes n characters from the front of each line in lines. -// Skips first line if skipFirstLine is true, skips empty lines. -func removeIndentation(lines []string, n int, skipFirstLine bool) []string { - for i, line := range lines { - if i == 0 && skipFirstLine { - continue - } - - if len(lines[i]) >= n { - lines[i] = line[n:] - } - } - return lines -} - -// Docf returns unindented and formatted string as here-document. -// Formatting is done as for fmt.Printf(). -func Docf(raw string, args ...interface{}) string { - return fmt.Sprintf(Doc(raw), args...) -} diff --git a/vendor/github.com/evanphx/json-patch/.gitignore b/vendor/github.com/evanphx/json-patch/.gitignore new file mode 100644 index 00000000000..b7ed7f956df --- /dev/null +++ b/vendor/github.com/evanphx/json-patch/.gitignore @@ -0,0 +1,6 @@ +# editor and IDE paraphernalia +.idea +.vscode + +# macOS paraphernalia +.DS_Store diff --git a/vendor/github.com/evanphx/json-patch/patch.go b/vendor/github.com/evanphx/json-patch/patch.go index 18298549076..dc2b7e51e60 100644 --- a/vendor/github.com/evanphx/json-patch/patch.go +++ b/vendor/github.com/evanphx/json-patch/patch.go @@ -412,6 +412,17 @@ func (d *partialArray) set(key string, val *lazyNode) error { if err != nil { return err } + + if idx < 0 { + if !SupportNegativeIndices { + return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + } + if idx < -len(*d) { + return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + } + idx += len(*d) + } + (*d)[idx] = val return nil } @@ -462,6 +473,16 @@ func (d *partialArray) get(key string) (*lazyNode, error) { return nil, err } + if idx < 0 { + if !SupportNegativeIndices { + return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + } + if idx < -len(*d) { + return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + } + idx += len(*d) + } + if idx >= len(*d) { return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) } @@ -547,6 +568,29 @@ func (p Patch) replace(doc *container, op Operation) error { return errors.Wrapf(err, "replace operation failed to decode path") } + if path == "" { + val := op.value() + + if val.which == eRaw { + if !val.tryDoc() { + if !val.tryAry() { + return errors.Wrapf(err, "replace operation value must be object or array") + } + } + } + + switch val.which { + case eAry: + *doc = &val.ary + case eDoc: + *doc = &val.doc + case eRaw: + return errors.Wrapf(err, "replace operation hit impossible case") + } + + return nil + } + con, key := findObject(doc, path) if con == nil { @@ -613,6 +657,25 @@ func (p Patch) test(doc *container, op Operation) error { return errors.Wrapf(err, "test operation failed to decode path") } + if path == "" { + var self lazyNode + + switch sv := (*doc).(type) { + case *partialDoc: + self.doc = *sv + self.which = eDoc + case *partialArray: + self.ary = *sv + self.which = eAry + } + + if self.equal(op.value()) { + return nil + } + + return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + } + con, key := findObject(doc, path) if con == nil { diff --git a/vendor/github.com/exponent-io/jsonpath/.gitignore b/vendor/github.com/exponent-io/jsonpath/.gitignore deleted file mode 100644 index daf913b1b34..00000000000 --- a/vendor/github.com/exponent-io/jsonpath/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/exponent-io/jsonpath/.travis.yml b/vendor/github.com/exponent-io/jsonpath/.travis.yml deleted file mode 100644 index f4f458a416d..00000000000 --- a/vendor/github.com/exponent-io/jsonpath/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: go - -go: - - 1.5 - - tip diff --git a/vendor/github.com/exponent-io/jsonpath/LICENSE b/vendor/github.com/exponent-io/jsonpath/LICENSE deleted file mode 100644 index 54197725078..00000000000 --- a/vendor/github.com/exponent-io/jsonpath/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Exponent Labs LLC - -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/exponent-io/jsonpath/README.md b/vendor/github.com/exponent-io/jsonpath/README.md deleted file mode 100644 index 382fb3138cb..00000000000 --- a/vendor/github.com/exponent-io/jsonpath/README.md +++ /dev/null @@ -1,66 +0,0 @@ -[![GoDoc](https://godoc.org/github.com/exponent-io/jsonpath?status.svg)](https://godoc.org/github.com/exponent-io/jsonpath) -[![Build Status](https://travis-ci.org/exponent-io/jsonpath.svg?branch=master)](https://travis-ci.org/exponent-io/jsonpath) - -# jsonpath - -This package extends the [json.Decoder](https://golang.org/pkg/encoding/json/#Decoder) to support navigating a stream of JSON tokens. You should be able to use this extended Decoder places where a json.Decoder would have been used. - -This Decoder has the following enhancements... - * The [Scan](https://godoc.org/github.com/exponent-io/jsonpath/#Decoder.Scan) method supports scanning a JSON stream while extracting particular values along the way using [PathActions](https://godoc.org/github.com/exponent-io/jsonpath#PathActions). - * The [SeekTo](https://godoc.org/github.com/exponent-io/jsonpath#Decoder.SeekTo) method supports seeking forward in a JSON token stream to a particular path. - * The [Path](https://godoc.org/github.com/exponent-io/jsonpath#Decoder.Path) method returns the path of the most recently parsed token. - * The [Token](https://godoc.org/github.com/exponent-io/jsonpath#Decoder.Token) method has been modified to distinguish between strings that are object keys and strings that are values. Object key strings are returned as the [KeyString](https://godoc.org/github.com/exponent-io/jsonpath#KeyString) type rather than a native string. - -## Installation - - go get -u github.com/exponent-io/jsonpath - -## Example Usage - -#### SeekTo - -```go -import "github.com/exponent-io/jsonpath" - -var j = []byte(`[ - {"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}}, - {"Space": "RGB", "Point": {"R": 98, "G": 218, "B": 255}} -]`) - -w := json.NewDecoder(bytes.NewReader(j)) -var v interface{} - -w.SeekTo(1, "Point", "G") -w.Decode(&v) // v is 218 -``` - -#### Scan with PathActions - -```go -var j = []byte(`{"colors":[ - {"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10, "A": 58}}, - {"Space": "RGB", "Point": {"R": 98, "G": 218, "B": 255, "A": 231}} -]}`) - -var actions PathActions - -// Extract the value at Point.A -actions.Add(func(d *Decoder) error { - var alpha int - err := d.Decode(&alpha) - fmt.Printf("Alpha: %v\n", alpha) - return err -}, "Point", "A") - -w := NewDecoder(bytes.NewReader(j)) -w.SeekTo("colors", 0) - -var ok = true -var err error -for ok { - ok, err = w.Scan(&actions) - if err != nil && err != io.EOF { - panic(err) - } -} -``` diff --git a/vendor/github.com/exponent-io/jsonpath/decoder.go b/vendor/github.com/exponent-io/jsonpath/decoder.go deleted file mode 100644 index 31de46c7381..00000000000 --- a/vendor/github.com/exponent-io/jsonpath/decoder.go +++ /dev/null @@ -1,210 +0,0 @@ -package jsonpath - -import ( - "encoding/json" - "io" -) - -// KeyString is returned from Decoder.Token to represent each key in a JSON object value. -type KeyString string - -// Decoder extends the Go runtime's encoding/json.Decoder to support navigating in a stream of JSON tokens. -type Decoder struct { - json.Decoder - - path JsonPath - context jsonContext -} - -// NewDecoder creates a new instance of the extended JSON Decoder. -func NewDecoder(r io.Reader) *Decoder { - return &Decoder{Decoder: *json.NewDecoder(r)} -} - -// SeekTo causes the Decoder to move forward to a given path in the JSON structure. -// -// The path argument must consist of strings or integers. Each string specifies an JSON object key, and -// each integer specifies an index into a JSON array. -// -// Consider the JSON structure -// -// { "a": [0,"s",12e4,{"b":0,"v":35} ] } -// -// SeekTo("a",3,"v") will move to the value referenced by the "a" key in the current object, -// followed by a move to the 4th value (index 3) in the array, followed by a move to the value at key "v". -// In this example, a subsequent call to the decoder's Decode() would unmarshal the value 35. -// -// SeekTo returns a boolean value indicating whether a match was found. -// -// Decoder is intended to be used with a stream of tokens. As a result it navigates forward only. -func (d *Decoder) SeekTo(path ...interface{}) (bool, error) { - - if len(path) == 0 { - return len(d.path) == 0, nil - } - last := len(path) - 1 - if i, ok := path[last].(int); ok { - path[last] = i - 1 - } - - for { - if d.path.Equal(path) { - return true, nil - } - _, err := d.Token() - if err == io.EOF { - return false, nil - } else if err != nil { - return false, err - } - } -} - -// Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v. This is -// equivalent to encoding/json.Decode(). -func (d *Decoder) Decode(v interface{}) error { - switch d.context { - case objValue: - d.context = objKey - break - case arrValue: - d.path.incTop() - break - } - return d.Decoder.Decode(v) -} - -// Path returns a slice of string and/or int values representing the path from the root of the JSON object to the -// position of the most-recently parsed token. -func (d *Decoder) Path() JsonPath { - p := make(JsonPath, len(d.path)) - copy(p, d.path) - return p -} - -// Token is equivalent to the Token() method on json.Decoder. The primary difference is that it distinguishes -// between strings that are keys and and strings that are values. String tokens that are object keys are returned as a -// KeyString rather than as a native string. -func (d *Decoder) Token() (json.Token, error) { - t, err := d.Decoder.Token() - if err != nil { - return t, err - } - - if t == nil { - switch d.context { - case objValue: - d.context = objKey - break - case arrValue: - d.path.incTop() - break - } - return t, err - } - - switch t := t.(type) { - case json.Delim: - switch t { - case json.Delim('{'): - if d.context == arrValue { - d.path.incTop() - } - d.path.push("") - d.context = objKey - break - case json.Delim('}'): - d.path.pop() - d.context = d.path.inferContext() - break - case json.Delim('['): - if d.context == arrValue { - d.path.incTop() - } - d.path.push(-1) - d.context = arrValue - break - case json.Delim(']'): - d.path.pop() - d.context = d.path.inferContext() - break - } - case float64, json.Number, bool: - switch d.context { - case objValue: - d.context = objKey - break - case arrValue: - d.path.incTop() - break - } - break - case string: - switch d.context { - case objKey: - d.path.nameTop(t) - d.context = objValue - return KeyString(t), err - case objValue: - d.context = objKey - case arrValue: - d.path.incTop() - } - break - } - - return t, err -} - -// Scan moves forward over the JSON stream consuming all the tokens at the current level (current object, current array) -// invoking each matching PathAction along the way. -// -// Scan returns true if there are more contiguous values to scan (for example in an array). -func (d *Decoder) Scan(ext *PathActions) (bool, error) { - - rootPath := d.Path() - - // If this is an array path, increment the root path in our local copy. - if rootPath.inferContext() == arrValue { - rootPath.incTop() - } - - for { - // advance the token position - _, err := d.Token() - if err != nil { - return false, err - } - - match: - var relPath JsonPath - - // capture the new JSON path - path := d.Path() - - if len(path) > len(rootPath) { - // capture the path relative to where the scan started - relPath = path[len(rootPath):] - } else { - // if the path is not longer than the root, then we are done with this scan - // return boolean flag indicating if there are more items to scan at the same level - return d.Decoder.More(), nil - } - - // match the relative path against the path actions - if node := ext.node.match(relPath); node != nil { - if node.action != nil { - // we have a match so execute the action - err = node.action(d) - if err != nil { - return d.Decoder.More(), err - } - // The action may have advanced the decoder. If we are in an array, advancing it further would - // skip tokens. So, if we are scanning an array, jump to the top without advancing the token. - if d.path.inferContext() == arrValue && d.Decoder.More() { - goto match - } - } - } - } -} diff --git a/vendor/github.com/exponent-io/jsonpath/path.go b/vendor/github.com/exponent-io/jsonpath/path.go deleted file mode 100644 index d7db2ad336e..00000000000 --- a/vendor/github.com/exponent-io/jsonpath/path.go +++ /dev/null @@ -1,67 +0,0 @@ -// Extends the Go runtime's json.Decoder enabling navigation of a stream of json tokens. -package jsonpath - -import "fmt" - -type jsonContext int - -const ( - none jsonContext = iota - objKey - objValue - arrValue -) - -// AnyIndex can be used in a pattern to match any array index. -const AnyIndex = -2 - -// JsonPath is a slice of strings and/or integers. Each string specifies an JSON object key, and -// each integer specifies an index into a JSON array. -type JsonPath []interface{} - -func (p *JsonPath) push(n interface{}) { *p = append(*p, n) } -func (p *JsonPath) pop() { *p = (*p)[:len(*p)-1] } - -// increment the index at the top of the stack (must be an array index) -func (p *JsonPath) incTop() { (*p)[len(*p)-1] = (*p)[len(*p)-1].(int) + 1 } - -// name the key at the top of the stack (must be an object key) -func (p *JsonPath) nameTop(n string) { (*p)[len(*p)-1] = n } - -// infer the context from the item at the top of the stack -func (p *JsonPath) inferContext() jsonContext { - if len(*p) == 0 { - return none - } - t := (*p)[len(*p)-1] - switch t.(type) { - case string: - return objKey - case int: - return arrValue - default: - panic(fmt.Sprintf("Invalid stack type %T", t)) - } -} - -// Equal tests for equality between two JsonPath types. -func (p *JsonPath) Equal(o JsonPath) bool { - if len(*p) != len(o) { - return false - } - for i, v := range *p { - if v != o[i] { - return false - } - } - return true -} - -func (p *JsonPath) HasPrefix(o JsonPath) bool { - for i, v := range o { - if v != (*p)[i] { - return false - } - } - return true -} diff --git a/vendor/github.com/exponent-io/jsonpath/pathaction.go b/vendor/github.com/exponent-io/jsonpath/pathaction.go deleted file mode 100644 index 497ed686ca9..00000000000 --- a/vendor/github.com/exponent-io/jsonpath/pathaction.go +++ /dev/null @@ -1,61 +0,0 @@ -package jsonpath - -// pathNode is used to construct a trie of paths to be matched -type pathNode struct { - matchOn interface{} // string, or integer - childNodes []pathNode - action DecodeAction -} - -// match climbs the trie to find a node that matches the given JSON path. -func (n *pathNode) match(path JsonPath) *pathNode { - var node *pathNode = n - for _, ps := range path { - found := false - for i, n := range node.childNodes { - if n.matchOn == ps { - node = &node.childNodes[i] - found = true - break - } else if _, ok := ps.(int); ok && n.matchOn == AnyIndex { - node = &node.childNodes[i] - found = true - break - } - } - if !found { - return nil - } - } - return node -} - -// PathActions represents a collection of DecodeAction functions that should be called at certain path positions -// when scanning the JSON stream. PathActions can be created once and used many times in one or more JSON streams. -type PathActions struct { - node pathNode -} - -// DecodeAction handlers are called by the Decoder when scanning objects. See PathActions.Add for more detail. -type DecodeAction func(d *Decoder) error - -// Add specifies an action to call on the Decoder when the specified path is encountered. -func (je *PathActions) Add(action DecodeAction, path ...interface{}) { - - var node *pathNode = &je.node - for _, ps := range path { - found := false - for i, n := range node.childNodes { - if n.matchOn == ps { - node = &node.childNodes[i] - found = true - break - } - } - if !found { - node.childNodes = append(node.childNodes, pathNode{matchOn: ps}) - node = &node.childNodes[len(node.childNodes)-1] - } - } - node.action = action -} diff --git a/vendor/github.com/fatih/camelcase/.travis.yml b/vendor/github.com/fatih/camelcase/.travis.yml deleted file mode 100644 index 3489e38713c..00000000000 --- a/vendor/github.com/fatih/camelcase/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: go -go: 1.x - diff --git a/vendor/github.com/fatih/camelcase/LICENSE.md b/vendor/github.com/fatih/camelcase/LICENSE.md deleted file mode 100644 index aa4a536caf0..00000000000 --- a/vendor/github.com/fatih/camelcase/LICENSE.md +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 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. diff --git a/vendor/github.com/fatih/camelcase/README.md b/vendor/github.com/fatih/camelcase/README.md deleted file mode 100644 index 105a6ae33de..00000000000 --- a/vendor/github.com/fatih/camelcase/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# CamelCase [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/fatih/camelcase) [![Build Status](http://img.shields.io/travis/fatih/camelcase.svg?style=flat-square)](https://travis-ci.org/fatih/camelcase) - -CamelCase is a Golang (Go) package to split the words of a camelcase type -string into a slice of words. It can be used to convert a camelcase word (lower -or upper case) into any type of word. - -## Splitting rules: - -1. If string is not valid UTF-8, return it without splitting as - single item array. -2. Assign all unicode characters into one of 4 sets: lower case - letters, upper case letters, numbers, and all other characters. -3. Iterate through characters of string, introducing splits - between adjacent characters that belong to different sets. -4. Iterate through array of split strings, and if a given string - is upper case: - * if subsequent string is lower case: - * move last character of upper case string to beginning of - lower case string - -## Install - -```bash -go get github.com/fatih/camelcase -``` - -## Usage and examples - -```go -splitted := camelcase.Split("GolangPackage") - -fmt.Println(splitted[0], splitted[1]) // prints: "Golang", "Package" -``` - -Both lower camel case and upper camel case are supported. For more info please -check: [http://en.wikipedia.org/wiki/CamelCase](http://en.wikipedia.org/wiki/CamelCase) - -Below are some example cases: - -``` -"" => [] -"lowercase" => ["lowercase"] -"Class" => ["Class"] -"MyClass" => ["My", "Class"] -"MyC" => ["My", "C"] -"HTML" => ["HTML"] -"PDFLoader" => ["PDF", "Loader"] -"AString" => ["A", "String"] -"SimpleXMLParser" => ["Simple", "XML", "Parser"] -"vimRPCPlugin" => ["vim", "RPC", "Plugin"] -"GL11Version" => ["GL", "11", "Version"] -"99Bottles" => ["99", "Bottles"] -"May5" => ["May", "5"] -"BFG9000" => ["BFG", "9000"] -"BöseÜberraschung" => ["Böse", "Überraschung"] -"Two spaces" => ["Two", " ", "spaces"] -"BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"] -``` diff --git a/vendor/github.com/fatih/camelcase/camelcase.go b/vendor/github.com/fatih/camelcase/camelcase.go deleted file mode 100644 index 02160c9a435..00000000000 --- a/vendor/github.com/fatih/camelcase/camelcase.go +++ /dev/null @@ -1,90 +0,0 @@ -// Package camelcase is a micro package to split the words of a camelcase type -// string into a slice of words. -package camelcase - -import ( - "unicode" - "unicode/utf8" -) - -// Split splits the camelcase word and returns a list of words. It also -// supports digits. Both lower camel case and upper camel case are supported. -// For more info please check: http://en.wikipedia.org/wiki/CamelCase -// -// Examples -// -// "" => [""] -// "lowercase" => ["lowercase"] -// "Class" => ["Class"] -// "MyClass" => ["My", "Class"] -// "MyC" => ["My", "C"] -// "HTML" => ["HTML"] -// "PDFLoader" => ["PDF", "Loader"] -// "AString" => ["A", "String"] -// "SimpleXMLParser" => ["Simple", "XML", "Parser"] -// "vimRPCPlugin" => ["vim", "RPC", "Plugin"] -// "GL11Version" => ["GL", "11", "Version"] -// "99Bottles" => ["99", "Bottles"] -// "May5" => ["May", "5"] -// "BFG9000" => ["BFG", "9000"] -// "BöseÜberraschung" => ["Böse", "Überraschung"] -// "Two spaces" => ["Two", " ", "spaces"] -// "BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"] -// -// Splitting rules -// -// 1) If string is not valid UTF-8, return it without splitting as -// single item array. -// 2) Assign all unicode characters into one of 4 sets: lower case -// letters, upper case letters, numbers, and all other characters. -// 3) Iterate through characters of string, introducing splits -// between adjacent characters that belong to different sets. -// 4) Iterate through array of split strings, and if a given string -// is upper case: -// if subsequent string is lower case: -// move last character of upper case string to beginning of -// lower case string -func Split(src string) (entries []string) { - // don't split invalid utf8 - if !utf8.ValidString(src) { - return []string{src} - } - entries = []string{} - var runes [][]rune - lastClass := 0 - class := 0 - // split into fields based on class of unicode character - for _, r := range src { - switch true { - case unicode.IsLower(r): - class = 1 - case unicode.IsUpper(r): - class = 2 - case unicode.IsDigit(r): - class = 3 - default: - class = 4 - } - if class == lastClass { - runes[len(runes)-1] = append(runes[len(runes)-1], r) - } else { - runes = append(runes, []rune{r}) - } - lastClass = class - } - // handle upper case -> lower case sequences, e.g. - // "PDFL", "oader" -> "PDF", "Loader" - for i := 0; i < len(runes)-1; i++ { - if unicode.IsUpper(runes[i][0]) && unicode.IsLower(runes[i+1][0]) { - runes[i+1] = append([]rune{runes[i][len(runes[i])-1]}, runes[i+1]...) - runes[i] = runes[i][:len(runes[i])-1] - } - } - // construct []string from results - for _, s := range runes { - if len(s) > 0 { - entries = append(entries, string(s)) - } - } - return -} diff --git a/vendor/github.com/fatih/color/README.md b/vendor/github.com/fatih/color/README.md index d62e4024aa5..5c751f2158c 100644 --- a/vendor/github.com/fatih/color/README.md +++ b/vendor/github.com/fatih/color/README.md @@ -127,14 +127,16 @@ fmt.Println("All text will now be bold magenta.") There might be a case where you want to explicitly disable/enable color output. the `go-isatty` package will automatically disable color output for non-tty output streams -(for example if the output were piped directly to `less`) +(for example if the output were piped directly to `less`). -`Color` has support to disable/enable colors both globally and for single color -definitions. For example suppose you have a CLI app and a `--no-color` bool flag. You -can easily disable the color output with: +The `color` package also disables color output if the [`NO_COLOR`](https://no-color.org) environment +variable is set (regardless of its value). -```go +`Color` has support to disable/enable colors programatically both globally and +for single color definitions. For example suppose you have a CLI app and a +`--no-color` bool flag. You can easily disable the color output with: +```go var flagNoColor = flag.Bool("no-color", false, "Disable color output") if *flagNoColor { @@ -156,6 +158,10 @@ c.EnableColor() c.Println("This prints again cyan...") ``` +## GitHub Actions + +To output color in GitHub Actions (or other CI systems that support ANSI colors), make sure to set `color.NoColor = false` so that it bypasses the check for non-tty output streams. + ## Todo * Save/Return previous values @@ -170,4 +176,3 @@ c.Println("This prints again cyan...") ## License The MIT License (MIT) - see [`LICENSE.md`](https://github.com/fatih/color/blob/master/LICENSE.md) for more details - diff --git a/vendor/github.com/fatih/color/color.go b/vendor/github.com/fatih/color/color.go index 91c8e9f0620..98a60f3c88d 100644 --- a/vendor/github.com/fatih/color/color.go +++ b/vendor/github.com/fatih/color/color.go @@ -15,9 +15,11 @@ import ( var ( // NoColor defines if the output is colorized or not. It's dynamically set to // false or true based on the stdout's file descriptor referring to a terminal - // or not. This is a global option and affects all colors. For more control - // over each color block use the methods DisableColor() individually. - NoColor = os.Getenv("TERM") == "dumb" || + // or not. It's also set to true if the NO_COLOR environment variable is + // set (regardless of its value). This is a global option and affects all + // colors. For more control over each color block use the methods + // DisableColor() individually. + NoColor = noColorExists() || os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) // Output defines the standard output of the print functions. By default @@ -33,6 +35,12 @@ var ( colorsCacheMu sync.Mutex // protects colorsCache ) +// noColorExists returns true if the environment variable NO_COLOR exists. +func noColorExists() bool { + _, exists := os.LookupEnv("NO_COLOR") + return exists +} + // Color defines a custom color object which is defined by SGR parameters. type Color struct { params []Attribute @@ -108,7 +116,14 @@ const ( // New returns a newly created color object. func New(value ...Attribute) *Color { - c := &Color{params: make([]Attribute, 0)} + c := &Color{ + params: make([]Attribute, 0), + } + + if noColorExists() { + c.noColor = boolPtr(true) + } + c.Add(value...) return c } @@ -387,7 +402,7 @@ func (c *Color) EnableColor() { } func (c *Color) isNoColorSet() bool { - // check first if we have user setted action + // check first if we have user set action if c.noColor != nil { return *c.noColor } diff --git a/vendor/github.com/fatih/color/doc.go b/vendor/github.com/fatih/color/doc.go index cf1e96500f4..04541de786f 100644 --- a/vendor/github.com/fatih/color/doc.go +++ b/vendor/github.com/fatih/color/doc.go @@ -118,6 +118,8 @@ the color output with: color.NoColor = true // disables colorized output } +You can also disable the color by setting the NO_COLOR environment variable to any value. + It also has support for single color definitions (local). You can disable/enable color output on the fly: diff --git a/vendor/github.com/fsnotify/fsnotify/.mailmap b/vendor/github.com/fsnotify/fsnotify/.mailmap new file mode 100644 index 00000000000..a04f2907fed --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/.mailmap @@ -0,0 +1,2 @@ +Chris Howey +Nathan Youngman <4566+nathany@users.noreply.github.com> diff --git a/vendor/github.com/fsnotify/fsnotify/.travis.yml b/vendor/github.com/fsnotify/fsnotify/.travis.yml deleted file mode 100644 index a9c30165cdd..00000000000 --- a/vendor/github.com/fsnotify/fsnotify/.travis.yml +++ /dev/null @@ -1,36 +0,0 @@ -sudo: false -language: go - -go: - - "stable" - - "1.11.x" - - "1.10.x" - - "1.9.x" - -matrix: - include: - - go: "stable" - env: GOLINT=true - allow_failures: - - go: tip - fast_finish: true - - -before_install: - - if [ ! -z "${GOLINT}" ]; then go get -u golang.org/x/lint/golint; fi - -script: - - go test --race ./... - -after_script: - - test -z "$(gofmt -s -l -w . | tee /dev/stderr)" - - if [ ! -z "${GOLINT}" ]; then echo running golint; golint --set_exit_status ./...; else echo skipping golint; fi - - go vet ./... - -os: - - linux - - osx - - windows - -notifications: - email: false diff --git a/vendor/github.com/fsnotify/fsnotify/AUTHORS b/vendor/github.com/fsnotify/fsnotify/AUTHORS index 5ab5d41c547..6cbabe5ef50 100644 --- a/vendor/github.com/fsnotify/fsnotify/AUTHORS +++ b/vendor/github.com/fsnotify/fsnotify/AUTHORS @@ -4,35 +4,44 @@ # You can update this list using the following command: # -# $ git shortlog -se | awk '{print $2 " " $3 " " $4}' +# $ (head -n10 AUTHORS && git shortlog -se | sed -E 's/^\s+[0-9]+\t//') | tee AUTHORS # Please keep the list sorted. Aaron L Adrien Bustany +Alexey Kazakov Amit Krishnan Anmol Sethi Bjørn Erik Pedersen +Brian Goff Bruno Bigras Caleb Spare Case Nelson -Chris Howey +Chris Howey Christoffer Buchholz Daniel Wagner-Hall Dave Cheney +Eric Lin Evan Phoenix Francisco Souza +Gautam Dey Hari haran -John C Barstow +Ichinose Shogo +Johannes Ebke +John C Barstow Kelvin Fo Ken-ichirou MATSUZAWA Matt Layher +Matthias Stone Nathan Youngman Nickolai Zeldovich +Oliver Bristow Patrick Paul Hammond Pawel Knap Pieter Droogendijk +Pratik Shinde Pursuit92 Riku Voipio Rob Figueiredo @@ -41,6 +50,7 @@ Slawek Ligus Soge Zhang Tiffany Jernigan Tilak Sharma +Tobias Klauser Tom Payne Travis Cline Tudor Golubenco diff --git a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md index be4d7ea2c14..a438fe4b4a5 100644 --- a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md +++ b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md @@ -1,6 +1,28 @@ # Changelog -## v1.4.7 / 2018-01-09 +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [1.5.1] - 2021-08-24 + +* Revert Add AddRaw to not follow symlinks + +## [1.5.0] - 2021-08-20 + +* Go: Increase minimum required version to Go 1.12 [#381](https://github.com/fsnotify/fsnotify/pull/381) +* Feature: Add AddRaw method which does not follow symlinks when adding a watch [#289](https://github.com/fsnotify/fsnotify/pull/298) +* Windows: Follow symlinks by default like on all other systems [#289](https://github.com/fsnotify/fsnotify/pull/289) +* CI: Use GitHub Actions for CI and cover go 1.12-1.17 + [#378](https://github.com/fsnotify/fsnotify/pull/378) + [#381](https://github.com/fsnotify/fsnotify/pull/381) + [#385](https://github.com/fsnotify/fsnotify/pull/385) +* Go 1.14+: Fix unsafe pointer conversion [#325](https://github.com/fsnotify/fsnotify/pull/325) + +## [1.4.7] - 2018-01-09 * BSD/macOS: Fix possible deadlock on closing the watcher on kqueue (thanks @nhooyr and @glycerine) * Tests: Fix missing verb on format string (thanks @rchiossi) @@ -10,62 +32,62 @@ * Linux: Properly handle inotify's IN_Q_OVERFLOW event (thanks @zeldovich) * Docs: replace references to OS X with macOS -## v1.4.2 / 2016-10-10 +## [1.4.2] - 2016-10-10 * Linux: use InotifyInit1 with IN_CLOEXEC to stop leaking a file descriptor to a child process when using fork/exec [#178](https://github.com/fsnotify/fsnotify/pull/178) (thanks @pattyshack) -## v1.4.1 / 2016-10-04 +## [1.4.1] - 2016-10-04 * Fix flaky inotify stress test on Linux [#177](https://github.com/fsnotify/fsnotify/pull/177) (thanks @pattyshack) -## v1.4.0 / 2016-10-01 +## [1.4.0] - 2016-10-01 * add a String() method to Event.Op [#165](https://github.com/fsnotify/fsnotify/pull/165) (thanks @oozie) -## v1.3.1 / 2016-06-28 +## [1.3.1] - 2016-06-28 * Windows: fix for double backslash when watching the root of a drive [#151](https://github.com/fsnotify/fsnotify/issues/151) (thanks @brunoqc) -## v1.3.0 / 2016-04-19 +## [1.3.0] - 2016-04-19 * Support linux/arm64 by [patching](https://go-review.googlesource.com/#/c/21971/) x/sys/unix and switching to to it from syscall (thanks @suihkulokki) [#135](https://github.com/fsnotify/fsnotify/pull/135) -## v1.2.10 / 2016-03-02 +## [1.2.10] - 2016-03-02 * Fix golint errors in windows.go [#121](https://github.com/fsnotify/fsnotify/pull/121) (thanks @tiffanyfj) -## v1.2.9 / 2016-01-13 +## [1.2.9] - 2016-01-13 kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsnotify/pull/111) (thanks @bep) -## v1.2.8 / 2015-12-17 +## [1.2.8] - 2015-12-17 * kqueue: fix race condition in Close [#105](https://github.com/fsnotify/fsnotify/pull/105) (thanks @djui for reporting the issue and @ppknap for writing a failing test) * inotify: fix race in test * enable race detection for continuous integration (Linux, Mac, Windows) -## v1.2.5 / 2015-10-17 +## [1.2.5] - 2015-10-17 * inotify: use epoll_create1 for arm64 support (requires Linux 2.6.27 or later) [#100](https://github.com/fsnotify/fsnotify/pull/100) (thanks @suihkulokki) * inotify: fix path leaks [#73](https://github.com/fsnotify/fsnotify/pull/73) (thanks @chamaken) * kqueue: watch for rename events on subdirectories [#83](https://github.com/fsnotify/fsnotify/pull/83) (thanks @guotie) * kqueue: avoid infinite loops from symlinks cycles [#101](https://github.com/fsnotify/fsnotify/pull/101) (thanks @illicitonion) -## v1.2.1 / 2015-10-14 +## [1.2.1] - 2015-10-14 * kqueue: don't watch named pipes [#98](https://github.com/fsnotify/fsnotify/pull/98) (thanks @evanphx) -## v1.2.0 / 2015-02-08 +## [1.2.0] - 2015-02-08 * inotify: use epoll to wake up readEvents [#66](https://github.com/fsnotify/fsnotify/pull/66) (thanks @PieterD) * inotify: closing watcher should now always shut down goroutine [#63](https://github.com/fsnotify/fsnotify/pull/63) (thanks @PieterD) * kqueue: close kqueue after removing watches, fixes [#59](https://github.com/fsnotify/fsnotify/issues/59) -## v1.1.1 / 2015-02-05 +## [1.1.1] - 2015-02-05 * inotify: Retry read on EINTR [#61](https://github.com/fsnotify/fsnotify/issues/61) (thanks @PieterD) -## v1.1.0 / 2014-12-12 +## [1.1.0] - 2014-12-12 * kqueue: rework internals [#43](https://github.com/fsnotify/fsnotify/pull/43) * add low-level functions @@ -77,22 +99,22 @@ kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsn * kqueue: fix regression in rework causing subdirectories to be watched [#48](https://github.com/fsnotify/fsnotify/issues/48) * kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) -## v1.0.4 / 2014-09-07 +## [1.0.4] - 2014-09-07 * kqueue: add dragonfly to the build tags. * Rename source code files, rearrange code so exported APIs are at the top. * Add done channel to example code. [#37](https://github.com/fsnotify/fsnotify/pull/37) (thanks @chenyukang) -## v1.0.3 / 2014-08-19 +## [1.0.3] - 2014-08-19 * [Fix] Windows MOVED_TO now translates to Create like on BSD and Linux. [#36](https://github.com/fsnotify/fsnotify/issues/36) -## v1.0.2 / 2014-08-17 +## [1.0.2] - 2014-08-17 * [Fix] Missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) * [Fix] Make ./path and path equivalent. (thanks @zhsso) -## v1.0.0 / 2014-08-15 +## [1.0.0] - 2014-08-15 * [API] Remove AddWatch on Windows, use Add. * Improve documentation for exported identifiers. [#30](https://github.com/fsnotify/fsnotify/issues/30) @@ -146,51 +168,51 @@ kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsn * no tests for the current implementation * not fully implemented on Windows [#93](https://github.com/howeyc/fsnotify/issues/93#issuecomment-39285195) -## v0.9.3 / 2014-12-31 +## [0.9.3] - 2014-12-31 * kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) -## v0.9.2 / 2014-08-17 +## [0.9.2] - 2014-08-17 * [Backport] Fix missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) -## v0.9.1 / 2014-06-12 +## [0.9.1] - 2014-06-12 * Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) -## v0.9.0 / 2014-01-17 +## [0.9.0] - 2014-01-17 * IsAttrib() for events that only concern a file's metadata [#79][] (thanks @abustany) * [Fix] kqueue: fix deadlock [#77][] (thanks @cespare) * [NOTICE] Development has moved to `code.google.com/p/go.exp/fsnotify` in preparation for inclusion in the Go standard library. -## v0.8.12 / 2013-11-13 +## [0.8.12] - 2013-11-13 * [API] Remove FD_SET and friends from Linux adapter -## v0.8.11 / 2013-11-02 +## [0.8.11] - 2013-11-02 * [Doc] Add Changelog [#72][] (thanks @nathany) * [Doc] Spotlight and double modify events on macOS [#62][] (reported by @paulhammond) -## v0.8.10 / 2013-10-19 +## [0.8.10] - 2013-10-19 * [Fix] kqueue: remove file watches when parent directory is removed [#71][] (reported by @mdwhatcott) * [Fix] kqueue: race between Close and readEvents [#70][] (reported by @bernerdschaefer) * [Doc] specify OS-specific limits in README (thanks @debrando) -## v0.8.9 / 2013-09-08 +## [0.8.9] - 2013-09-08 * [Doc] Contributing (thanks @nathany) * [Doc] update package path in example code [#63][] (thanks @paulhammond) * [Doc] GoCI badge in README (Linux only) [#60][] * [Doc] Cross-platform testing with Vagrant [#59][] (thanks @nathany) -## v0.8.8 / 2013-06-17 +## [0.8.8] - 2013-06-17 * [Fix] Windows: handle `ERROR_MORE_DATA` on Windows [#49][] (thanks @jbowtie) -## v0.8.7 / 2013-06-03 +## [0.8.7] - 2013-06-03 * [API] Make syscall flags internal * [Fix] inotify: ignore event changes @@ -198,74 +220,74 @@ kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsn * [Fix] tests on Windows * lower case error messages -## v0.8.6 / 2013-05-23 +## [0.8.6] - 2013-05-23 * kqueue: Use EVT_ONLY flag on Darwin * [Doc] Update README with full example -## v0.8.5 / 2013-05-09 +## [0.8.5] - 2013-05-09 * [Fix] inotify: allow monitoring of "broken" symlinks (thanks @tsg) -## v0.8.4 / 2013-04-07 +## [0.8.4] - 2013-04-07 * [Fix] kqueue: watch all file events [#40][] (thanks @ChrisBuchholz) -## v0.8.3 / 2013-03-13 +## [0.8.3] - 2013-03-13 * [Fix] inoitfy/kqueue memory leak [#36][] (reported by @nbkolchin) * [Fix] kqueue: use fsnFlags for watching a directory [#33][] (reported by @nbkolchin) -## v0.8.2 / 2013-02-07 +## [0.8.2] - 2013-02-07 * [Doc] add Authors * [Fix] fix data races for map access [#29][] (thanks @fsouza) -## v0.8.1 / 2013-01-09 +## [0.8.1] - 2013-01-09 * [Fix] Windows path separators * [Doc] BSD License -## v0.8.0 / 2012-11-09 +## [0.8.0] - 2012-11-09 * kqueue: directory watching improvements (thanks @vmirage) * inotify: add `IN_MOVED_TO` [#25][] (requested by @cpisto) * [Fix] kqueue: deleting watched directory [#24][] (reported by @jakerr) -## v0.7.4 / 2012-10-09 +## [0.7.4] - 2012-10-09 * [Fix] inotify: fixes from https://codereview.appspot.com/5418045/ (ugorji) * [Fix] kqueue: preserve watch flags when watching for delete [#21][] (reported by @robfig) * [Fix] kqueue: watch the directory even if it isn't a new watch (thanks @robfig) * [Fix] kqueue: modify after recreation of file -## v0.7.3 / 2012-09-27 +## [0.7.3] - 2012-09-27 * [Fix] kqueue: watch with an existing folder inside the watched folder (thanks @vmirage) * [Fix] kqueue: no longer get duplicate CREATE events -## v0.7.2 / 2012-09-01 +## [0.7.2] - 2012-09-01 * kqueue: events for created directories -## v0.7.1 / 2012-07-14 +## [0.7.1] - 2012-07-14 * [Fix] for renaming files -## v0.7.0 / 2012-07-02 +## [0.7.0] - 2012-07-02 * [Feature] FSNotify flags * [Fix] inotify: Added file name back to event path -## v0.6.0 / 2012-06-06 +## [0.6.0] - 2012-06-06 * kqueue: watch files after directory created (thanks @tmc) -## v0.5.1 / 2012-05-22 +## [0.5.1] - 2012-05-22 * [Fix] inotify: remove all watches before Close() -## v0.5.0 / 2012-05-03 +## [0.5.0] - 2012-05-03 * [API] kqueue: return errors during watch instead of sending over channel * kqueue: match symlink behavior on Linux @@ -273,22 +295,22 @@ kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsn * [Fix] kqueue: handle EINTR (reported by @robfig) * [Doc] Godoc example [#1][] (thanks @davecheney) -## v0.4.0 / 2012-03-30 +## [0.4.0] - 2012-03-30 * Go 1 released: build with go tool * [Feature] Windows support using winfsnotify * Windows does not have attribute change notifications * Roll attribute notifications into IsModify -## v0.3.0 / 2012-02-19 +## [0.3.0] - 2012-02-19 * kqueue: add files when watch directory -## v0.2.0 / 2011-12-30 +## [0.2.0] - 2011-12-30 * update to latest Go weekly code -## v0.1.0 / 2011-10-19 +## [0.1.0] - 2011-10-19 * kqueue: add watch on file creation to match inotify * kqueue: create file event diff --git a/vendor/github.com/fsnotify/fsnotify/README.md b/vendor/github.com/fsnotify/fsnotify/README.md index b2629e5229c..df57b1b282c 100644 --- a/vendor/github.com/fsnotify/fsnotify/README.md +++ b/vendor/github.com/fsnotify/fsnotify/README.md @@ -12,9 +12,9 @@ Cross platform: Windows, Linux, BSD and macOS. | Adapter | OS | Status | | --------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -| inotify | Linux 2.6.27 or later, Android\* | Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify) | -| kqueue | BSD, macOS, iOS\* | Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify) | -| ReadDirectoryChangesW | Windows | Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify) | +| inotify | Linux 2.6.27 or later, Android\* | Supported | +| kqueue | BSD, macOS, iOS\* | Supported | +| ReadDirectoryChangesW | Windows | Supported | | FSEvents | macOS | [Planned](https://github.com/fsnotify/fsnotify/issues/11) | | FEN | Solaris 11 | [In Progress](https://github.com/fsnotify/fsnotify/issues/12) | | fanotify | Linux 2.6.37+ | [Planned](https://github.com/fsnotify/fsnotify/issues/114) | diff --git a/vendor/github.com/fsnotify/fsnotify/fen.go b/vendor/github.com/fsnotify/fsnotify/fen.go index ced39cb881e..b3ac3d8f55f 100644 --- a/vendor/github.com/fsnotify/fsnotify/fen.go +++ b/vendor/github.com/fsnotify/fsnotify/fen.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build solaris // +build solaris package fsnotify diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go index 89cab046d12..0f4ee52e8aa 100644 --- a/vendor/github.com/fsnotify/fsnotify/fsnotify.go +++ b/vendor/github.com/fsnotify/fsnotify/fsnotify.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 // +build !plan9 // Package fsnotify provides a platform-independent interface for file system notifications. diff --git a/vendor/github.com/fsnotify/fsnotify/inotify.go b/vendor/github.com/fsnotify/fsnotify/inotify.go index d9fd1b88a05..eb87699b5b4 100644 --- a/vendor/github.com/fsnotify/fsnotify/inotify.go +++ b/vendor/github.com/fsnotify/fsnotify/inotify.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build linux // +build linux package fsnotify @@ -272,7 +273,7 @@ func (w *Watcher) readEvents() { if nameLen > 0 { // Point "bytes" at the first byte of the filename - bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent])) + bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent]))[:nameLen:nameLen] // The filename is padded with NULL bytes. TrimRight() gets rid of those. name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000") } diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_poller.go b/vendor/github.com/fsnotify/fsnotify/inotify_poller.go index b33f2b4d4b7..e9ff9439f7f 100644 --- a/vendor/github.com/fsnotify/fsnotify/inotify_poller.go +++ b/vendor/github.com/fsnotify/fsnotify/inotify_poller.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build linux // +build linux package fsnotify diff --git a/vendor/github.com/fsnotify/fsnotify/kqueue.go b/vendor/github.com/fsnotify/fsnotify/kqueue.go index 86e76a3d676..368f5b790d4 100644 --- a/vendor/github.com/fsnotify/fsnotify/kqueue.go +++ b/vendor/github.com/fsnotify/fsnotify/kqueue.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build freebsd || openbsd || netbsd || dragonfly || darwin // +build freebsd openbsd netbsd dragonfly darwin package fsnotify diff --git a/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go b/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go index 2306c4620bf..36cc3845b6e 100644 --- a/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go +++ b/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build freebsd || openbsd || netbsd || dragonfly // +build freebsd openbsd netbsd dragonfly package fsnotify diff --git a/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go b/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go index 870c4d6d184..98cd8476ffb 100644 --- a/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go +++ b/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build darwin // +build darwin package fsnotify diff --git a/vendor/github.com/fsnotify/fsnotify/windows.go b/vendor/github.com/fsnotify/fsnotify/windows.go index 09436f31d82..c02b75f7c37 100644 --- a/vendor/github.com/fsnotify/fsnotify/windows.go +++ b/vendor/github.com/fsnotify/fsnotify/windows.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build windows // +build windows package fsnotify diff --git a/vendor/github.com/go-errors/errors/.travis.yml b/vendor/github.com/go-errors/errors/.travis.yml deleted file mode 100644 index 9d00fdd5d66..00000000000 --- a/vendor/github.com/go-errors/errors/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: go - -go: - - "1.8.x" - - "1.10.x" 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 c9a5b2eeb75..00000000000 --- 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/README.md b/vendor/github.com/go-errors/errors/README.md deleted file mode 100644 index 5d4f1873ddf..00000000000 --- a/vendor/github.com/go-errors/errors/README.md +++ /dev/null @@ -1,66 +0,0 @@ -go-errors/errors -================ - -[![Build Status](https://travis-ci.org/go-errors/errors.svg?branch=master)](https://travis-ci.org/go-errors/errors) - -Package errors adds stacktrace support to errors in go. - -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. - -Usage ------ - -Full documentation is available on -[godoc](https://godoc.org/github.com/go-errors/errors), but here's a simple -example: - -```go -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: - -```go -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) - } - } -} -``` - -Meta-fu -------- - -This package was original written to allow reporting to -[Bugsnag](https://bugsnag.com/) from -[bugsnag-go](https://github.com/bugsnag/bugsnag-go), but after I found similar -packages by Facebook and Dropbox, it was moved to one canonical location so -everyone can benefit. - -This package is licensed under the MIT license, see LICENSE.MIT for details. diff --git a/vendor/github.com/go-errors/errors/cover.out b/vendor/github.com/go-errors/errors/cover.out deleted file mode 100644 index ab18b0519fc..00000000000 --- a/vendor/github.com/go-errors/errors/cover.out +++ /dev/null @@ -1,89 +0,0 @@ -mode: set -github.com/go-errors/errors/stackframe.go:27.51,30.25 2 1 -github.com/go-errors/errors/stackframe.go:33.2,38.8 3 1 -github.com/go-errors/errors/stackframe.go:30.25,32.3 1 0 -github.com/go-errors/errors/stackframe.go:43.47,44.31 1 1 -github.com/go-errors/errors/stackframe.go:47.2,47.48 1 1 -github.com/go-errors/errors/stackframe.go:44.31,46.3 1 1 -github.com/go-errors/errors/stackframe.go:52.42,56.16 3 1 -github.com/go-errors/errors/stackframe.go:60.2,60.60 1 1 -github.com/go-errors/errors/stackframe.go:56.16,58.3 1 0 -github.com/go-errors/errors/stackframe.go:64.55,67.16 2 1 -github.com/go-errors/errors/stackframe.go:71.2,72.61 2 1 -github.com/go-errors/errors/stackframe.go:76.2,76.66 1 1 -github.com/go-errors/errors/stackframe.go:67.16,69.3 1 0 -github.com/go-errors/errors/stackframe.go:72.61,74.3 1 0 -github.com/go-errors/errors/stackframe.go:79.56,91.63 3 1 -github.com/go-errors/errors/stackframe.go:95.2,95.53 1 1 -github.com/go-errors/errors/stackframe.go:100.2,101.18 2 1 -github.com/go-errors/errors/stackframe.go:91.63,94.3 2 1 -github.com/go-errors/errors/stackframe.go:95.53,98.3 2 1 -github.com/go-errors/errors/error.go:70.32,73.23 2 1 -github.com/go-errors/errors/error.go:80.2,85.3 3 1 -github.com/go-errors/errors/error.go:74.2,75.10 1 1 -github.com/go-errors/errors/error.go:76.2,77.28 1 1 -github.com/go-errors/errors/error.go:92.43,95.23 2 1 -github.com/go-errors/errors/error.go:104.2,109.3 3 1 -github.com/go-errors/errors/error.go:96.2,97.11 1 1 -github.com/go-errors/errors/error.go:98.2,99.10 1 1 -github.com/go-errors/errors/error.go:100.2,101.28 1 1 -github.com/go-errors/errors/error.go:115.39,117.19 1 1 -github.com/go-errors/errors/error.go:121.2,121.29 1 1 -github.com/go-errors/errors/error.go:125.2,125.43 1 1 -github.com/go-errors/errors/error.go:129.2,129.14 1 1 -github.com/go-errors/errors/error.go:117.19,119.3 1 1 -github.com/go-errors/errors/error.go:121.29,123.3 1 1 -github.com/go-errors/errors/error.go:125.43,127.3 1 1 -github.com/go-errors/errors/error.go:135.53,137.2 1 1 -github.com/go-errors/errors/error.go:140.34,142.2 1 1 -github.com/go-errors/errors/error.go:146.34,149.42 2 1 -github.com/go-errors/errors/error.go:153.2,153.20 1 1 -github.com/go-errors/errors/error.go:149.42,151.3 1 1 -github.com/go-errors/errors/error.go:158.39,160.2 1 1 -github.com/go-errors/errors/error.go:164.46,165.23 1 1 -github.com/go-errors/errors/error.go:173.2,173.19 1 1 -github.com/go-errors/errors/error.go:165.23,168.32 2 1 -github.com/go-errors/errors/error.go:168.32,170.4 1 1 -github.com/go-errors/errors/error.go:177.37,178.42 1 1 -github.com/go-errors/errors/error.go:181.2,181.41 1 1 -github.com/go-errors/errors/error.go:178.42,180.3 1 1 -github.com/go-errors/errors/parse_panic.go:10.39,12.2 1 1 -github.com/go-errors/errors/parse_panic.go:16.46,24.34 5 1 -github.com/go-errors/errors/parse_panic.go:70.2,70.43 1 1 -github.com/go-errors/errors/parse_panic.go:73.2,73.55 1 0 -github.com/go-errors/errors/parse_panic.go:24.34,27.23 2 1 -github.com/go-errors/errors/parse_panic.go:27.23,28.42 1 1 -github.com/go-errors/errors/parse_panic.go:28.42,31.5 2 1 -github.com/go-errors/errors/parse_panic.go:31.6,33.5 1 0 -github.com/go-errors/errors/parse_panic.go:35.5,35.29 1 1 -github.com/go-errors/errors/parse_panic.go:35.29,36.86 1 1 -github.com/go-errors/errors/parse_panic.go:36.86,38.5 1 1 -github.com/go-errors/errors/parse_panic.go:40.5,40.32 1 1 -github.com/go-errors/errors/parse_panic.go:40.32,41.18 1 1 -github.com/go-errors/errors/parse_panic.go:45.4,46.46 2 1 -github.com/go-errors/errors/parse_panic.go:51.4,53.23 2 1 -github.com/go-errors/errors/parse_panic.go:57.4,58.18 2 1 -github.com/go-errors/errors/parse_panic.go:62.4,63.17 2 1 -github.com/go-errors/errors/parse_panic.go:41.18,43.10 2 1 -github.com/go-errors/errors/parse_panic.go:46.46,49.5 2 1 -github.com/go-errors/errors/parse_panic.go:53.23,55.5 1 0 -github.com/go-errors/errors/parse_panic.go:58.18,60.5 1 0 -github.com/go-errors/errors/parse_panic.go:63.17,65.10 2 1 -github.com/go-errors/errors/parse_panic.go:70.43,72.3 1 1 -github.com/go-errors/errors/parse_panic.go:80.85,82.29 2 1 -github.com/go-errors/errors/parse_panic.go:85.2,85.15 1 1 -github.com/go-errors/errors/parse_panic.go:88.2,90.63 2 1 -github.com/go-errors/errors/parse_panic.go:94.2,94.53 1 1 -github.com/go-errors/errors/parse_panic.go:99.2,101.36 2 1 -github.com/go-errors/errors/parse_panic.go:105.2,106.15 2 1 -github.com/go-errors/errors/parse_panic.go:109.2,112.49 3 1 -github.com/go-errors/errors/parse_panic.go:116.2,117.16 2 1 -github.com/go-errors/errors/parse_panic.go:121.2,126.8 1 1 -github.com/go-errors/errors/parse_panic.go:82.29,84.3 1 0 -github.com/go-errors/errors/parse_panic.go:85.15,87.3 1 1 -github.com/go-errors/errors/parse_panic.go:90.63,93.3 2 1 -github.com/go-errors/errors/parse_panic.go:94.53,97.3 2 1 -github.com/go-errors/errors/parse_panic.go:101.36,103.3 1 0 -github.com/go-errors/errors/parse_panic.go:106.15,108.3 1 0 -github.com/go-errors/errors/parse_panic.go:112.49,114.3 1 1 -github.com/go-errors/errors/parse_panic.go:117.16,119.3 1 0 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 60062a4372b..00000000000 --- 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 cc37052d786..00000000000 --- 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 750ab9a5215..00000000000 --- 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-logr/logr/.golangci.yaml b/vendor/github.com/go-logr/logr/.golangci.yaml new file mode 100644 index 00000000000..94ff801df1a --- /dev/null +++ b/vendor/github.com/go-logr/logr/.golangci.yaml @@ -0,0 +1,29 @@ +run: + timeout: 1m + tests: true + +linters: + disable-all: true + enable: + - asciicheck + - deadcode + - errcheck + - forcetypeassert + - gocritic + - gofmt + - goimports + - gosimple + - govet + - ineffassign + - misspell + - revive + - staticcheck + - structcheck + - typecheck + - unused + - varcheck + +issues: + exclude-use-default: false + max-issues-per-linter: 0 + max-same-issues: 10 diff --git a/vendor/github.com/go-logr/logr/CHANGELOG.md b/vendor/github.com/go-logr/logr/CHANGELOG.md new file mode 100644 index 00000000000..c3569600463 --- /dev/null +++ b/vendor/github.com/go-logr/logr/CHANGELOG.md @@ -0,0 +1,6 @@ +# CHANGELOG + +## v1.0.0-rc1 + +This is the first logged release. Major changes (including breaking changes) +have occurred since earlier tags. diff --git a/vendor/github.com/go-logr/logr/CONTRIBUTING.md b/vendor/github.com/go-logr/logr/CONTRIBUTING.md new file mode 100644 index 00000000000..5d37e294c5f --- /dev/null +++ b/vendor/github.com/go-logr/logr/CONTRIBUTING.md @@ -0,0 +1,17 @@ +# Contributing + +Logr is open to pull-requests, provided they fit within the intended scope of +the project. Specifically, this library aims to be VERY small and minimalist, +with no external dependencies. + +## Compatibility + +This project intends to follow [semantic versioning](http://semver.org) and +is very strict about compatibility. Any proposed changes MUST follow those +rules. + +## Performance + +As a logging library, logr must be as light-weight as possible. Any proposed +code change must include results of running the [benchmark](./benchmark) +before and after the change. diff --git a/vendor/github.com/go-logr/logr/README.md b/vendor/github.com/go-logr/logr/README.md index e9b5520a1c5..ad825f5f0ae 100644 --- a/vendor/github.com/go-logr/logr/README.md +++ b/vendor/github.com/go-logr/logr/README.md @@ -1,112 +1,182 @@ -# A more minimal logging API for Go +# A minimal logging API for Go -Before you consider this package, please read [this blog post by the -inimitable Dave Cheney][warning-makes-no-sense]. I really appreciate what -he has to say, and it largely aligns with my own experiences. Too many -choices of levels means inconsistent logs. +[![Go Reference](https://pkg.go.dev/badge/github.com/go-logr/logr.svg)](https://pkg.go.dev/github.com/go-logr/logr) + +logr offers an(other) opinion on how Go programs and libraries can do logging +without becoming coupled to a particular logging implementation. This is not +an implementation of logging - it is an API. In fact it is two APIs with two +different sets of users. + +The `Logger` type is intended for application and library authors. It provides +a relatively small API which can be used everywhere you want to emit logs. It +defers the actual act of writing logs (to files, to stdout, or whatever) to the +`LogSink` interface. + +The `LogSink` interface is intended for logging library implementers. It is a +pure interface which can be implemented by logging frameworks to provide the actual logging +functionality. + +This decoupling allows application and library developers to write code in +terms of `logr.Logger` (which has very low dependency fan-out) while the +implementation of logging is managed "up stack" (e.g. in or near `main()`.) +Application developers can then switch out implementations as necessary. + +Many people assert that libraries should not be logging, and as such efforts +like this are pointless. Those people are welcome to convince the authors of +the tens-of-thousands of libraries that *DO* write logs that they are all +wrong. In the meantime, logr takes a more practical approach. + +## Typical usage + +Somewhere, early in an application's life, it will make a decision about which +logging library (implementation) it actually wants to use. Something like: + +``` + func main() { + // ... other setup code ... + + // Create the "root" logger. We have chosen the "logimpl" implementation, + // which takes some initial parameters and returns a logr.Logger. + logger := logimpl.New(param1, param2) + + // ... other setup code ... +``` + +Most apps will call into other libraries, create structures to govern the flow, +etc. The `logr.Logger` object can be passed to these other libraries, stored +in structs, or even used as a package-global variable, if needed. For example: + +``` + app := createTheAppObject(logger) + app.Run() +``` + +Outside of this early setup, no other packages need to know about the choice of +implementation. They write logs in terms of the `logr.Logger` that they +received: -This package offers a purely abstract interface, based on these ideas but with -a few twists. Code can depend on just this interface and have the actual -logging implementation be injected from callers. Ideally only `main()` knows -what logging implementation is being used. +``` + type appObject struct { + // ... other fields ... + logger logr.Logger + // ... other fields ... + } -# Differences from Dave's ideas + func (app *appObject) Run() { + app.logger.Info("starting up", "timestamp", time.Now()) + + // ... app code ... +``` + +## Background + +If the Go standard library had defined an interface for logging, this project +probably would not be needed. Alas, here we are. + +### Inspiration + +Before you consider this package, please read [this blog post by the +inimitable Dave Cheney][warning-makes-no-sense]. We really appreciate what +he has to say, and it largely aligns with our own experiences. + +### Differences from Dave's ideas The main differences are: -1) Dave basically proposes doing away with the notion of a logging API in favor -of `fmt.Printf()`. I disagree, especially when you consider things like output -locations, timestamps, file and line decorations, and structured logging. I -restrict the API to just 2 types of logs: info and error. +1. Dave basically proposes doing away with the notion of a logging API in favor +of `fmt.Printf()`. We disagree, especially when you consider things like output +locations, timestamps, file and line decorations, and structured logging. This +package restricts the logging API to just 2 types of logs: info and error. Info logs are things you want to tell the user which are not errors. Error logs are, well, errors. If your code receives an `error` from a subordinate function call and is logging that `error` *and not returning it*, use error logs. -2) Verbosity-levels on info logs. This gives developers a chance to indicate +2. Verbosity-levels on info logs. This gives developers a chance to indicate arbitrary grades of importance for info logs, without assigning names with -semantic meaning such as "warning", "trace", and "debug". Superficially this +semantic meaning such as "warning", "trace", and "debug." Superficially this may feel very similar, but the primary difference is the lack of semantics. Because verbosity is a numerical value, it's safe to assume that an app running with higher verbosity means more (and less important) logs will be generated. -This is a BETA grade API. +## Implementations (non-exhaustive) There are implementations for the following logging libraries: +- **a function** (can bridge to non-structured libraries): [funcr](https://github.com/go-logr/logr/tree/master/funcr) - **github.com/google/glog**: [glogr](https://github.com/go-logr/glogr) -- **k8s.io/klog**: [klogr](https://git.k8s.io/klog/klogr) +- **k8s.io/klog** (for Kubernetes): [klogr](https://git.k8s.io/klog/klogr) - **go.uber.org/zap**: [zapr](https://github.com/go-logr/zapr) -- **log** (the Go standard library logger): - [stdr](https://github.com/go-logr/stdr) +- **log** (the Go standard library logger): [stdr](https://github.com/go-logr/stdr) - **github.com/sirupsen/logrus**: [logrusr](https://github.com/bombsimon/logrusr) - **github.com/wojas/genericr**: [genericr](https://github.com/wojas/genericr) (makes it easy to implement your own backend) - **logfmt** (Heroku style [logging](https://www.brandur.org/logfmt)): [logfmtr](https://github.com/iand/logfmtr) +- **github.com/rs/zerolog**: [zerologr](https://github.com/go-logr/zerologr) -# FAQ +## FAQ -## Conceptual +### Conceptual -## Why structured logging? +#### Why structured logging? -- **Structured logs are more easily queriable**: Since you've got +- **Structured logs are more easily queryable**: Since you've got key-value pairs, it's much easier to query your structured logs for particular values by filtering on the contents of a particular key -- think searching request logs for error codes, Kubernetes reconcilers for - the name and namespace of the reconciled object, etc + the name and namespace of the reconciled object, etc. -- **Structured logging makes it easier to have cross-referencable logs**: +- **Structured logging makes it easier to have cross-referenceable logs**: Similarly to searchability, if you maintain conventions around your keys, it becomes easy to gather all log lines related to a particular concept. - + - **Structured logs allow better dimensions of filtering**: if you have structure to your logs, you've got more precise control over how much information is logged -- you might choose in a particular configuration to log certain keys but not others, only log lines where a certain key - matches a certain value, etc, instead of just having v-levels and names + matches a certain value, etc., instead of just having v-levels and names to key off of. - **Structured logs better represent structured data**: sometimes, the data that you want to log is inherently structured (think tuple-link - objects). Structured logs allow you to preserve that structure when + objects.) Structured logs allow you to preserve that structure when outputting. -## Why V-levels? +#### Why V-levels? **V-levels give operators an easy way to control the chattiness of log operations**. V-levels provide a way for a given package to distinguish the relative importance or verbosity of a given log message. Then, if a particular logger or package is logging too many messages, the user -of the package can simply change the v-levels for that library. +of the package can simply change the v-levels for that library. -## Why not more named levels, like Warning? +#### Why not named levels, like Info/Warning/Error? Read [Dave Cheney's post][warning-makes-no-sense]. Then read [Differences from Dave's ideas](#differences-from-daves-ideas). -## Why not allow format strings, too? +#### Why not allow format strings, too? **Format strings negate many of the benefits of structured logs**: - They're not easily searchable without resorting to fuzzy searching, - regular expressions, etc + regular expressions, etc. - They don't store structured data well, since contents are flattened into - a string + a string. -- They're not cross-referencable +- They're not cross-referenceable. -- They don't compress easily, since the message is not constant +- They don't compress easily, since the message is not constant. -(unless you turn positional parameters into key-value pairs with numerical +(Unless you turn positional parameters into key-value pairs with numerical keys, at which point you've gotten key-value logging with meaningless -keys) +keys.) -## Practical +### Practical -## Why key-value pairs, and not a map? +#### Why key-value pairs, and not a map? Key-value pairs are *much* easier to optimize, especially around allocations. Zap (a structured logger that inspired logr's interface) has @@ -117,26 +187,26 @@ While the interface ends up being a little less obvious, you get potentially better performance, plus avoid making users type `map[string]string{}` every time they want to log. -## What if my V-levels differ between libraries? +#### What if my V-levels differ between libraries? That's fine. Control your V-levels on a per-logger basis, and use the -`WithName` function to pass different loggers to different libraries. +`WithName` method to pass different loggers to different libraries. Generally, you should take care to ensure that you have relatively consistent V-levels within a given logger, however, as this makes deciding on what verbosity of logs to request easier. -## But I *really* want to use a format string! +#### But I really want to use a format string! That's not actually a question. Assuming your question is "how do I convert my mental model of logging with format strings to logging with constant messages": -1. figure out what the error actually is, as you'd write in a TL;DR style, - and use that as a message +1. Figure out what the error actually is, as you'd write in a TL;DR style, + and use that as a message. 2. For every place you'd write a format specifier, look to the word before - it, and add that as a key value pair + it, and add that as a key value pair. For instance, consider the following examples (all taken from spots in the Kubernetes codebase): @@ -150,34 +220,59 @@ Kubernetes codebase): response when requesting url", "attempt", retries, "after seconds", seconds, "url", url)` -If you *really* must use a format string, place it as a key value, and -call `fmt.Sprintf` yourself -- for instance, `log.Printf("unable to +If you *really* must use a format string, use it in a key's value, and +call `fmt.Sprintf` yourself. For instance: `log.Printf("unable to reflect over type %T")` becomes `logger.Info("unable to reflect over type", "type", fmt.Sprintf("%T"))`. In general though, the cases where this is necessary should be few and far between. -## How do I choose my V-levels? +#### How do I choose my V-levels? This is basically the only hard constraint: increase V-levels to denote more verbose or more debug-y logs. Otherwise, you can start out with `0` as "you always want to see this", `1` as "common logging that you might *possibly* want to turn off", and -`10` as "I would like to performance-test your log collection stack". +`10` as "I would like to performance-test your log collection stack." Then gradually choose levels in between as you need them, working your way down from 10 (for debug and trace style logs) and up from 1 (for chattier -info-type logs). +info-type logs.) + +#### How do I choose my keys? -## How do I choose my keys +Keys are fairly flexible, and can hold more or less any string +value. For best compatibility with implementations and consistency +with existing code in other projects, there are a few conventions you +should consider. -- make your keys human-readable -- constant keys are generally a good idea -- be consistent across your codebase -- keys should naturally match parts of the message string +- Make your keys human-readable. +- Constant keys are generally a good idea. +- Be consistent across your codebase. +- Keys should naturally match parts of the message string. +- Use lower case for simple keys and + [lowerCamelCase](https://en.wiktionary.org/wiki/lowerCamelCase) for + more complex ones. Kubernetes is one example of a project that has + [adopted that + convention](https://github.com/kubernetes/community/blob/HEAD/contributors/devel/sig-instrumentation/migration-to-structured-logging.md#name-arguments). While key names are mostly unrestricted (and spaces are acceptable), it's generally a good idea to stick to printable ascii characters, or at least match the general character set of your log lines. +#### Why should keys be constant values? + +The point of structured logging is to make later log processing easier. Your +keys are, effectively, the schema of each log message. If you use different +keys across instances of the same log line, you will make your structured logs +much harder to use. `Sprintf()` is for values, not for keys! + +#### Why is this not a pure interface? + +The Logger type is implemented as a struct in order to allow the Go compiler to +optimize things like high-V `Info` logs that are not triggered. Not all of +these implementations are implemented yet, but this structure was suggested as +a way to ensure they *can* be implemented. All of the real work is behind the +`LogSink` interface. + [warning-makes-no-sense]: http://dave.cheney.net/2015/11/05/lets-talk-about-logging diff --git a/vendor/github.com/go-logr/logr/discard.go b/vendor/github.com/go-logr/logr/discard.go index 2bafb13d15c..9d92a38f1d7 100644 --- a/vendor/github.com/go-logr/logr/discard.go +++ b/vendor/github.com/go-logr/logr/discard.go @@ -16,36 +16,39 @@ limitations under the License. package logr -// Discard returns a valid Logger that discards all messages logged to it. -// It can be used whenever the caller is not interested in the logs. +// Discard returns a Logger that discards all messages logged to it. It can be +// used whenever the caller is not interested in the logs. Logger instances +// produced by this function always compare as equal. func Discard() Logger { - return DiscardLogger{} + return Logger{ + level: 0, + sink: discardLogSink{}, + } } -// DiscardLogger is a Logger that discards all messages. -type DiscardLogger struct{} +// discardLogSink is a LogSink that discards all messages. +type discardLogSink struct{} -func (l DiscardLogger) Enabled() bool { - return false +// Verify that it actually implements the interface +var _ LogSink = discardLogSink{} + +func (l discardLogSink) Init(RuntimeInfo) { } -func (l DiscardLogger) Info(msg string, keysAndValues ...interface{}) { +func (l discardLogSink) Enabled(int) bool { + return false } -func (l DiscardLogger) Error(err error, msg string, keysAndValues ...interface{}) { +func (l discardLogSink) Info(int, string, ...interface{}) { } -func (l DiscardLogger) V(level int) Logger { - return l +func (l discardLogSink) Error(error, string, ...interface{}) { } -func (l DiscardLogger) WithValues(keysAndValues ...interface{}) Logger { +func (l discardLogSink) WithValues(...interface{}) LogSink { return l } -func (l DiscardLogger) WithName(name string) Logger { +func (l discardLogSink) WithName(string) LogSink { return l } - -// Verify that it actually implements the interface -var _ Logger = DiscardLogger{} diff --git a/vendor/github.com/go-logr/logr/logr.go b/vendor/github.com/go-logr/logr/logr.go index 842428bd3a3..44cd398c9f8 100644 --- a/vendor/github.com/go-logr/logr/logr.go +++ b/vendor/github.com/go-logr/logr/logr.go @@ -16,83 +16,101 @@ limitations under the License. // This design derives from Dave Cheney's blog: // http://dave.cheney.net/2015/11/05/lets-talk-about-logging -// -// This is a BETA grade API. Until there is a significant 2nd implementation, -// I don't really know how it will change. -// Package logr defines abstract interfaces for logging. Packages can depend on -// these interfaces and callers can implement logging in whatever way is -// appropriate. +// Package logr defines a general-purpose logging API and abstract interfaces +// to back that API. Packages in the Go ecosystem can depend on this package, +// while callers can implement logging with whatever backend is appropriate. // // Usage // -// Logging is done using a Logger. Loggers can have name prefixes and named -// values attached, so that all log messages logged with that Logger have some -// base context associated. +// Logging is done using a Logger instance. Logger is a concrete type with +// methods, which defers the actual logging to a LogSink interface. The main +// methods of Logger are Info() and Error(). Arguments to Info() and Error() +// are key/value pairs rather than printf-style formatted strings, emphasizing +// "structured logging". // -// The term "key" is used to refer to the name associated with a particular -// value, to disambiguate it from the general Logger name. +// With Go's standard log package, we might write: +// log.Printf("setting target value %s", targetValue) // -// For instance, suppose we're trying to reconcile the state of an object, and -// we want to log that we've made some decision. +// With logr's structured logging, we'd write: +// logger.Info("setting target", "value", targetValue) // -// With the traditional log package, we might write: -// log.Printf("decided to set field foo to value %q for object %s/%s", -// targetValue, object.Namespace, object.Name) +// Errors are much the same. Instead of: +// log.Printf("failed to open the pod bay door for user %s: %v", user, err) // -// With logr's structured logging, we'd write: -// // elsewhere in the file, set up the logger to log with the prefix of -// // "reconcilers", and the named value target-type=Foo, for extra context. -// log := mainLogger.WithName("reconcilers").WithValues("target-type", "Foo") +// We'd write: +// logger.Error(err, "failed to open the pod bay door", "user", user) // -// // later on... -// log.Info("setting foo on object", "value", targetValue, "object", object) +// Info() and Error() are very similar, but they are separate methods so that +// LogSink implementations can choose to do things like attach additional +// information (such as stack traces) on calls to Error(). +// +// Verbosity +// +// Often we want to log information only when the application in "verbose +// mode". To write log lines that are more verbose, Logger has a V() method. +// The higher the V-level of a log line, the less critical it is considered. +// Log-lines with V-levels that are not enabled (as per the LogSink) will not +// be written. Level V(0) is the default, and logger.V(0).Info() has the same +// meaning as logger.Info(). Negative V-levels have the same meaning as V(0). +// +// Where we might have written: +// if flVerbose >= 2 { +// log.Printf("an unusual thing happened") +// } +// +// We can write: +// logger.V(2).Info("an unusual thing happened") +// +// Logger Names +// +// Logger instances can have name strings so that all messages logged through +// that instance have additional context. For example, you might want to add +// a subsystem name: // -// Depending on our logging implementation, we could then make logging decisions -// based on field values (like only logging such events for objects in a certain -// namespace), or copy the structured information into a structured log store. +// logger.WithName("compactor").Info("started", "time", time.Now()) // -// For logging errors, Logger has a method called Error. Suppose we wanted to -// log an error while reconciling. With the traditional log package, we might -// write: -// log.Errorf("unable to reconcile object %s/%s: %v", object.Namespace, object.Name, err) +// The WithName() method returns a new Logger, which can be passed to +// constructors or other functions for further use. Repeated use of WithName() +// will accumulate name "segments". These name segments will be joined in some +// way by the LogSink implementation. It is strongly recommended that name +// segments contain simple identifiers (letters, digits, and hyphen), and do +// not contain characters that could muddle the log output or confuse the +// joining operation (e.g. whitespace, commas, periods, slashes, brackets, +// quotes, etc). // -// With logr, we'd instead write: -// // assuming the above setup for log -// log.Error(err, "unable to reconcile object", "object", object) +// Saved Values // -// This functions similarly to: -// log.Info("unable to reconcile object", "error", err, "object", object) +// Logger instances can store any number of key/value pairs, which will be +// logged alongside all messages logged through that instance. For example, +// you might want to create a Logger instance per managed object: // -// However, it ensures that a standard key for the error value ("error") is used -// across all error logging. Furthermore, certain implementations may choose to -// attach additional information (such as stack traces) on calls to Error, so -// it's preferred to use Error to log errors. +// With the standard log package, we might write: +// log.Printf("decided to set field foo to value %q for object %s/%s", +// targetValue, object.Namespace, object.Name) // -// Parts of a log line +// With logr we'd write: +// // Elsewhere: set up the logger to log the object name. +// obj.logger = mainLogger.WithValues( +// "name", obj.name, "namespace", obj.namespace) // -// Each log message from a Logger has four types of context: -// logger name, log verbosity, log message, and the named values. +// // later on... +// obj.logger.Info("setting foo", "value", targetValue) // -// The Logger name consists of a series of name "segments" added by successive -// calls to WithName. These name segments will be joined in some way by the -// underlying implementation. It is strongly recommended that name segments -// contain simple identifiers (letters, digits, and hyphen), and do not contain -// characters that could muddle the log output or confuse the joining operation -// (e.g. whitespace, commas, periods, slashes, brackets, quotes, etc). +// Best Practices // -// Log verbosity represents how little a log matters. Level zero, the default, -// matters most. Increasing levels matter less and less. Try to avoid lots of -// different verbosity levels, and instead provide useful keys, logger names, -// and log messages for users to filter on. It's illegal to pass a log level -// below zero. +// Logger has very few hard rules, with the goal that LogSink implementations +// might have a lot of freedom to differentiate. There are, however, some +// things to consider. // // The log message consists of a constant message attached to the log line. // This should generally be a simple description of what's occurring, and should -// never be a format string. +// never be a format string. Variable information can then be attached using +// named values. // -// Variable information can then be attached using named values (key/value -// pairs). Keys are arbitrary strings, while values may be any Go value. +// Keys are arbitrary strings, but should generally be constant values. Values +// may be any Go value, but how the value is formatted is determined by the +// LogSink implementation. // // Key Naming Conventions // @@ -102,6 +120,7 @@ limitations under the License. // * be constant (not dependent on input data) // * contain only printable characters // * not contain whitespace or punctuation +// * use lower case for simple keys and lowerCamelCase for more complex ones // // These guidelines help ensure that log data is processed properly regardless // of the log implementation. For example, log implementations will try to @@ -110,21 +129,22 @@ limitations under the License. // While users are generally free to use key names of their choice, it's // generally best to avoid using the following keys, as they're frequently used // by implementations: -// -// * `"caller"`: the calling information (file/line) of a particular log line. -// * `"error"`: the underlying error value in the `Error` method. -// * `"level"`: the log level. -// * `"logger"`: the name of the associated logger. -// * `"msg"`: the log message. -// * `"stacktrace"`: the stack trace associated with a particular log line or -// error (often from the `Error` message). -// * `"ts"`: the timestamp for a log line. +// * "caller": the calling information (file/line) of a particular log line +// * "error": the underlying error value in the `Error` method +// * "level": the log level +// * "logger": the name of the associated logger +// * "msg": the log message +// * "stacktrace": the stack trace associated with a particular log line or +// error (often from the `Error` message) +// * "ts": the timestamp for a log line // // Implementations are encouraged to make use of these keys to represent the // above concepts, when necessary (for example, in a pure-JSON output form, it // would be necessary to represent at least message and timestamp as ordinary // named values). // +// Break Glass +// // Implementations may choose to give callers access to the underlying // logging implementation. The recommended pattern for this is: // // Underlier exposes access to the underlying logging implementation. @@ -134,81 +154,220 @@ limitations under the License. // type Underlier interface { // GetUnderlying() // } +// +// Logger grants access to the sink to enable type assertions like this: +// func DoSomethingWithImpl(log logr.Logger) { +// if underlier, ok := log.GetSink()(impl.Underlier) { +// implLogger := underlier.GetUnderlying() +// ... +// } +// } +// +// Custom `With*` functions can be implemented by copying the complete +// Logger struct and replacing the sink in the copy: +// // WithFooBar changes the foobar parameter in the log sink and returns a +// // new logger with that modified sink. It does nothing for loggers where +// // the sink doesn't support that parameter. +// func WithFoobar(log logr.Logger, foobar int) logr.Logger { +// if foobarLogSink, ok := log.GetSink()(FoobarSink); ok { +// log = log.WithSink(foobarLogSink.WithFooBar(foobar)) +// } +// return log +// } +// +// Don't use New to construct a new Logger with a LogSink retrieved from an +// existing Logger. Source code attribution might not work correctly and +// unexported fields in Logger get lost. +// +// Beware that the same LogSink instance may be shared by different logger +// instances. Calling functions that modify the LogSink will affect all of +// those. package logr import ( "context" ) -// TODO: consider adding back in format strings if they're really needed -// TODO: consider other bits of zap/zapcore functionality like ObjectMarshaller (for arbitrary objects) -// TODO: consider other bits of glog functionality like Flush, OutputStats +// New returns a new Logger instance. This is primarily used by libraries +// implementing LogSink, rather than end users. +func New(sink LogSink) Logger { + logger := Logger{} + logger.setSink(sink) + sink.Init(runtimeInfo) + return logger +} -// Logger represents the ability to log messages, both errors and not. -type Logger interface { - // Enabled tests whether this Logger is enabled. For example, commandline - // flags might be used to set the logging verbosity and disable some info - // logs. - Enabled() bool +// setSink stores the sink and updates any related fields. It mutates the +// logger and thus is only safe to use for loggers that are not currently being +// used concurrently. +func (l *Logger) setSink(sink LogSink) { + l.sink = sink +} - // Info logs a non-error message with the given key/value pairs as context. - // - // The msg argument should be used to add some constant description to - // the log line. The key/value pairs can then be used to add additional - // variable information. The key/value pairs should alternate string - // keys and arbitrary values. - Info(msg string, keysAndValues ...interface{}) - - // Error logs an error, with the given message and key/value pairs as context. - // It functions similarly to calling Info with the "error" named value, but may - // have unique behavior, and should be preferred for logging errors (see the - // package documentations for more information). - // - // The msg field should be used to add context to any underlying error, - // while the err field should be used to attach the actual error that - // triggered this log line, if present. - Error(err error, msg string, keysAndValues ...interface{}) +// GetSink returns the stored sink. +func (l Logger) GetSink() LogSink { + return l.sink +} + +// WithSink returns a copy of the logger with the new sink. +func (l Logger) WithSink(sink LogSink) Logger { + l.setSink(sink) + return l +} + +// Logger is an interface to an abstract logging implementation. This is a +// concrete type for performance reasons, but all the real work is passed on to +// a LogSink. Implementations of LogSink should provide their own constructors +// that return Logger, not LogSink. +// +// The underlying sink can be accessed through GetSink and be modified through +// WithSink. This enables the implementation of custom extensions (see "Break +// Glass" in the package documentation). Normally the sink should be used only +// indirectly. +type Logger struct { + sink LogSink + level int +} + +// Enabled tests whether this Logger is enabled. For example, commandline +// flags might be used to set the logging verbosity and disable some info logs. +func (l Logger) Enabled() bool { + return l.sink.Enabled(l.level) +} + +// Info logs a non-error message with the given key/value pairs as context. +// +// The msg argument should be used to add some constant description to the log +// line. The key/value pairs can then be used to add additional variable +// information. The key/value pairs must alternate string keys and arbitrary +// values. +func (l Logger) Info(msg string, keysAndValues ...interface{}) { + if l.Enabled() { + if withHelper, ok := l.sink.(CallStackHelperLogSink); ok { + withHelper.GetCallStackHelper()() + } + l.sink.Info(l.level, msg, keysAndValues...) + } +} + +// Error logs an error, with the given message and key/value pairs as context. +// It functions similarly to Info, but may have unique behavior, and should be +// preferred for logging errors (see the package documentations for more +// information). +// +// The msg argument should be used to add context to any underlying error, +// while the err argument should be used to attach the actual error that +// triggered this log line, if present. +func (l Logger) Error(err error, msg string, keysAndValues ...interface{}) { + if withHelper, ok := l.sink.(CallStackHelperLogSink); ok { + withHelper.GetCallStackHelper()() + } + l.sink.Error(err, msg, keysAndValues...) +} + +// V returns a new Logger instance for a specific verbosity level, relative to +// this Logger. In other words, V-levels are additive. A higher verbosity +// level means a log message is less important. Negative V-levels are treated +// as 0. +func (l Logger) V(level int) Logger { + if level < 0 { + level = 0 + } + l.level += level + return l +} + +// WithValues returns a new Logger instance with additional key/value pairs. +// See Info for documentation on how key/value pairs work. +func (l Logger) WithValues(keysAndValues ...interface{}) Logger { + l.setSink(l.sink.WithValues(keysAndValues...)) + return l +} - // V returns an Logger value for a specific verbosity level, relative to - // this Logger. In other words, V values are additive. V higher verbosity - // level means a log message is less important. It's illegal to pass a log - // level less than zero. - V(level int) Logger - - // WithValues adds some key-value pairs of context to a logger. - // See Info for documentation on how key/value pairs work. - WithValues(keysAndValues ...interface{}) Logger - - // WithName adds a new element to the logger's name. - // Successive calls with WithName continue to append - // suffixes to the logger's name. It's strongly recommended - // that name segments contain only letters, digits, and hyphens - // (see the package documentation for more information). - WithName(name string) Logger +// WithName returns a new Logger instance with the specified name element added +// to the Logger's name. Successive calls with WithName append additional +// suffixes to the Logger's name. It's strongly recommended that name segments +// contain only letters, digits, and hyphens (see the package documentation for +// more information). +func (l Logger) WithName(name string) Logger { + l.setSink(l.sink.WithName(name)) + return l } -// InfoLogger provides compatibility with code that relies on the v0.1.0 -// interface. +// WithCallDepth returns a Logger instance that offsets the call stack by the +// specified number of frames when logging call site information, if possible. +// This is useful for users who have helper functions between the "real" call +// site and the actual calls to Logger methods. If depth is 0 the attribution +// should be to the direct caller of this function. If depth is 1 the +// attribution should skip 1 call frame, and so on. Successive calls to this +// are additive. +// +// If the underlying log implementation supports a WithCallDepth(int) method, +// it will be called and the result returned. If the implementation does not +// support CallDepthLogSink, the original Logger will be returned. +// +// To skip one level, WithCallStackHelper() should be used instead of +// WithCallDepth(1) because it works with implementions that support the +// CallDepthLogSink and/or CallStackHelperLogSink interfaces. +func (l Logger) WithCallDepth(depth int) Logger { + if withCallDepth, ok := l.sink.(CallDepthLogSink); ok { + l.setSink(withCallDepth.WithCallDepth(depth)) + } + return l +} + +// WithCallStackHelper returns a new Logger instance that skips the direct +// caller when logging call site information, if possible. This is useful for +// users who have helper functions between the "real" call site and the actual +// calls to Logger methods and want to support loggers which depend on marking +// each individual helper function, like loggers based on testing.T. +// +// In addition to using that new logger instance, callers also must call the +// returned function. // -// Deprecated: InfoLogger is an artifact of early versions of this API. New -// users should never use it and existing users should use Logger instead. This -// will be removed in a future release. -type InfoLogger = Logger +// If the underlying log implementation supports a WithCallDepth(int) method, +// WithCallDepth(1) will be called to produce a new logger. If it supports a +// WithCallStackHelper() method, that will be also called. If the +// implementation does not support either of these, the original Logger will be +// returned. +func (l Logger) WithCallStackHelper() (func(), Logger) { + var helper func() + if withCallDepth, ok := l.sink.(CallDepthLogSink); ok { + l.setSink(withCallDepth.WithCallDepth(1)) + } + if withHelper, ok := l.sink.(CallStackHelperLogSink); ok { + helper = withHelper.GetCallStackHelper() + } else { + helper = func() {} + } + return helper, l +} +// contextKey is how we find Loggers in a context.Context. type contextKey struct{} -// FromContext returns a Logger constructed from ctx or nil if no -// logger details are found. -func FromContext(ctx context.Context) Logger { +// FromContext returns a Logger from ctx or an error if no Logger is found. +func FromContext(ctx context.Context) (Logger, error) { if v, ok := ctx.Value(contextKey{}).(Logger); ok { - return v + return v, nil } - return nil + return Logger{}, notFoundError{} } -// FromContextOrDiscard returns a Logger constructed from ctx or a Logger -// that discards all messages if no logger details are found. +// notFoundError exists to carry an IsNotFound method. +type notFoundError struct{} + +func (notFoundError) Error() string { + return "no logr.Logger was present" +} + +func (notFoundError) IsNotFound() bool { + return true +} + +// FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this +// returns a Logger that discards all log messages. func FromContextOrDiscard(ctx context.Context) Logger { if v, ok := ctx.Value(contextKey{}).(Logger); ok { return v @@ -217,12 +376,59 @@ func FromContextOrDiscard(ctx context.Context) Logger { return Discard() } -// NewContext returns a new context derived from ctx that embeds the Logger. -func NewContext(ctx context.Context, l Logger) context.Context { - return context.WithValue(ctx, contextKey{}, l) +// NewContext returns a new Context, derived from ctx, which carries the +// provided Logger. +func NewContext(ctx context.Context, logger Logger) context.Context { + return context.WithValue(ctx, contextKey{}, logger) } -// CallDepthLogger represents a Logger that knows how to climb the call stack +// RuntimeInfo holds information that the logr "core" library knows which +// LogSinks might want to know. +type RuntimeInfo struct { + // CallDepth is the number of call frames the logr library adds between the + // end-user and the LogSink. LogSink implementations which choose to print + // the original logging site (e.g. file & line) should climb this many + // additional frames to find it. + CallDepth int +} + +// runtimeInfo is a static global. It must not be changed at run time. +var runtimeInfo = RuntimeInfo{ + CallDepth: 1, +} + +// LogSink represents a logging implementation. End-users will generally not +// interact with this type. +type LogSink interface { + // Init receives optional information about the logr library for LogSink + // implementations that need it. + Init(info RuntimeInfo) + + // Enabled tests whether this LogSink is enabled at the specified V-level. + // For example, commandline flags might be used to set the logging + // verbosity and disable some info logs. + Enabled(level int) bool + + // Info logs a non-error message with the given key/value pairs as context. + // The level argument is provided for optional logging. This method will + // only be called when Enabled(level) is true. See Logger.Info for more + // details. + Info(level int, msg string, keysAndValues ...interface{}) + + // Error logs an error, with the given message and key/value pairs as + // context. See Logger.Error for more details. + Error(err error, msg string, keysAndValues ...interface{}) + + // WithValues returns a new LogSink with additional key/value pairs. See + // Logger.WithValues for more details. + WithValues(keysAndValues ...interface{}) LogSink + + // WithName returns a new LogSink with the specified name appended. See + // Logger.WithName for more details. + WithName(name string) LogSink +} + +// CallDepthLogSink represents a Logger that knows how to climb the call stack // to identify the original call site and can offset the depth by a specified // number of frames. This is useful for users who have helper functions // between the "real" call site and the actual calls to Logger methods. @@ -232,35 +438,59 @@ func NewContext(ctx context.Context, l Logger) context.Context { // // This is an optional interface and implementations are not required to // support it. -type CallDepthLogger interface { - Logger - - // WithCallDepth returns a Logger that will offset the call stack by the - // specified number of frames when logging call site information. If depth - // is 0 the attribution should be to the direct caller of this method. If - // depth is 1 the attribution should skip 1 call frame, and so on. +type CallDepthLogSink interface { + // WithCallDepth returns a LogSink that will offset the call + // stack by the specified number of frames when logging call + // site information. + // + // If depth is 0, the LogSink should skip exactly the number + // of call frames defined in RuntimeInfo.CallDepth when Info + // or Error are called, i.e. the attribution should be to the + // direct caller of Logger.Info or Logger.Error. + // + // If depth is 1 the attribution should skip 1 call frame, and so on. // Successive calls to this are additive. - WithCallDepth(depth int) Logger + WithCallDepth(depth int) LogSink } -// WithCallDepth returns a Logger that will offset the call stack by the -// specified number of frames when logging call site information, if possible. -// This is useful for users who have helper functions between the "real" call -// site and the actual calls to Logger methods. If depth is 0 the attribution -// should be to the direct caller of this function. If depth is 1 the -// attribution should skip 1 call frame, and so on. Successive calls to this -// are additive. +// CallStackHelperLogSink represents a Logger that knows how to climb +// the call stack to identify the original call site and can skip +// intermediate helper functions if they mark themselves as +// helper. Go's testing package uses that approach. // -// If the underlying log implementation supports the CallDepthLogger interface, -// the WithCallDepth method will be called and the result returned. If the -// implementation does not support CallDepthLogger, the original Logger will be -// returned. +// This is useful for users who have helper functions between the +// "real" call site and the actual calls to Logger methods. +// Implementations that log information about the call site (such as +// file, function, or line) would otherwise log information about the +// intermediate helper functions. // -// Callers which care about whether this was supported or not should test for -// CallDepthLogger support themselves. -func WithCallDepth(logger Logger, depth int) Logger { - if decorator, ok := logger.(CallDepthLogger); ok { - return decorator.WithCallDepth(depth) - } - return logger +// This is an optional interface and implementations are not required +// to support it. Implementations that choose to support this must not +// simply implement it as WithCallDepth(1), because +// Logger.WithCallStackHelper will call both methods if they are +// present. This should only be implemented for LogSinks that actually +// need it, as with testing.T. +type CallStackHelperLogSink interface { + // GetCallStackHelper returns a function that must be called + // to mark the direct caller as helper function when logging + // call site information. + GetCallStackHelper() func() +} + +// Marshaler is an optional interface that logged values may choose to +// implement. Loggers with structured output, such as JSON, should +// log the object return by the MarshalLog method instead of the +// original value. +type Marshaler interface { + // MarshalLog can be used to: + // - ensure that structs are not logged as strings when the original + // value has a String method: return a different type without a + // String method + // - select which fields of a complex type should get logged: + // return a simpler struct with fewer fields + // - log unexported fields: return a different struct + // with exported fields + // + // It may return any value of any type. + MarshalLog() interface{} } diff --git a/vendor/github.com/gobuffalo/flect/plural_rules.go b/vendor/github.com/gobuffalo/flect/plural_rules.go index 8cd3ba72e7a..ff67928438b 100644 --- a/vendor/github.com/gobuffalo/flect/plural_rules.go +++ b/vendor/github.com/gobuffalo/flect/plural_rules.go @@ -199,6 +199,7 @@ var singularToPluralSuffixList = []singularToPluralSuffix{ {"shoe", "shoes"}, {"stis", "stes"}, {"tive", "tives"}, + {"vice", "vices"}, {"wife", "wives"}, {"afe", "aves"}, {"bfe", "bves"}, diff --git a/vendor/github.com/google/btree/.travis.yml b/vendor/github.com/google/btree/.travis.yml deleted file mode 100644 index 4f2ee4d9733..00000000000 --- a/vendor/github.com/google/btree/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: go diff --git a/vendor/github.com/google/btree/LICENSE b/vendor/github.com/google/btree/LICENSE deleted file mode 100644 index d6456956733..00000000000 --- a/vendor/github.com/google/btree/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/google/btree/README.md b/vendor/github.com/google/btree/README.md deleted file mode 100644 index 6062a4dacd4..00000000000 --- a/vendor/github.com/google/btree/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# BTree implementation for Go - -![Travis CI Build Status](https://api.travis-ci.org/google/btree.svg?branch=master) - -This package provides an in-memory B-Tree implementation for Go, useful as -an ordered, mutable data structure. - -The API is based off of the wonderful -http://godoc.org/github.com/petar/GoLLRB/llrb, and is meant to allow btree to -act as a drop-in replacement for gollrb trees. - -See http://godoc.org/github.com/google/btree for documentation. diff --git a/vendor/github.com/google/btree/btree.go b/vendor/github.com/google/btree/btree.go deleted file mode 100644 index b83acdbc6d3..00000000000 --- a/vendor/github.com/google/btree/btree.go +++ /dev/null @@ -1,890 +0,0 @@ -// Copyright 2014 Google 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 btree implements in-memory B-Trees of arbitrary degree. -// -// btree implements an in-memory B-Tree for use as an ordered data structure. -// It is not meant for persistent storage solutions. -// -// It has a flatter structure than an equivalent red-black or other binary tree, -// which in some cases yields better memory usage and/or performance. -// See some discussion on the matter here: -// http://google-opensource.blogspot.com/2013/01/c-containers-that-save-memory-and-time.html -// Note, though, that this project is in no way related to the C++ B-Tree -// implementation written about there. -// -// Within this tree, each node contains a slice of items and a (possibly nil) -// slice of children. For basic numeric values or raw structs, this can cause -// efficiency differences when compared to equivalent C++ template code that -// stores values in arrays within the node: -// * Due to the overhead of storing values as interfaces (each -// value needs to be stored as the value itself, then 2 words for the -// interface pointing to that value and its type), resulting in higher -// memory use. -// * Since interfaces can point to values anywhere in memory, values are -// most likely not stored in contiguous blocks, resulting in a higher -// number of cache misses. -// These issues don't tend to matter, though, when working with strings or other -// heap-allocated structures, since C++-equivalent structures also must store -// pointers and also distribute their values across the heap. -// -// This implementation is designed to be a drop-in replacement to gollrb.LLRB -// trees, (http://github.com/petar/gollrb), an excellent and probably the most -// widely used ordered tree implementation in the Go ecosystem currently. -// Its functions, therefore, exactly mirror those of -// llrb.LLRB where possible. Unlike gollrb, though, we currently don't -// support storing multiple equivalent values. -package btree - -import ( - "fmt" - "io" - "sort" - "strings" - "sync" -) - -// Item represents a single object in the tree. -type Item interface { - // Less tests whether the current item is less than the given argument. - // - // This must provide a strict weak ordering. - // If !a.Less(b) && !b.Less(a), we treat this to mean a == b (i.e. we can only - // hold one of either a or b in the tree). - Less(than Item) bool -} - -const ( - DefaultFreeListSize = 32 -) - -var ( - nilItems = make(items, 16) - nilChildren = make(children, 16) -) - -// FreeList represents a free list of btree nodes. By default each -// BTree has its own FreeList, but multiple BTrees can share the same -// FreeList. -// Two Btrees using the same freelist are safe for concurrent write access. -type FreeList struct { - mu sync.Mutex - freelist []*node -} - -// NewFreeList creates a new free list. -// size is the maximum size of the returned free list. -func NewFreeList(size int) *FreeList { - return &FreeList{freelist: make([]*node, 0, size)} -} - -func (f *FreeList) newNode() (n *node) { - f.mu.Lock() - index := len(f.freelist) - 1 - if index < 0 { - f.mu.Unlock() - return new(node) - } - n = f.freelist[index] - f.freelist[index] = nil - f.freelist = f.freelist[:index] - f.mu.Unlock() - return -} - -// freeNode adds the given node to the list, returning true if it was added -// and false if it was discarded. -func (f *FreeList) freeNode(n *node) (out bool) { - f.mu.Lock() - if len(f.freelist) < cap(f.freelist) { - f.freelist = append(f.freelist, n) - out = true - } - f.mu.Unlock() - return -} - -// ItemIterator allows callers of Ascend* to iterate in-order over portions of -// the tree. When this function returns false, iteration will stop and the -// associated Ascend* function will immediately return. -type ItemIterator func(i Item) bool - -// New creates a new B-Tree with the given degree. -// -// New(2), for example, will create a 2-3-4 tree (each node contains 1-3 items -// and 2-4 children). -func New(degree int) *BTree { - return NewWithFreeList(degree, NewFreeList(DefaultFreeListSize)) -} - -// NewWithFreeList creates a new B-Tree that uses the given node free list. -func NewWithFreeList(degree int, f *FreeList) *BTree { - if degree <= 1 { - panic("bad degree") - } - return &BTree{ - degree: degree, - cow: ©OnWriteContext{freelist: f}, - } -} - -// items stores items in a node. -type items []Item - -// insertAt inserts a value into the given index, pushing all subsequent values -// forward. -func (s *items) insertAt(index int, item Item) { - *s = append(*s, nil) - if index < len(*s) { - copy((*s)[index+1:], (*s)[index:]) - } - (*s)[index] = item -} - -// removeAt removes a value at a given index, pulling all subsequent values -// back. -func (s *items) removeAt(index int) Item { - item := (*s)[index] - copy((*s)[index:], (*s)[index+1:]) - (*s)[len(*s)-1] = nil - *s = (*s)[:len(*s)-1] - return item -} - -// pop removes and returns the last element in the list. -func (s *items) pop() (out Item) { - index := len(*s) - 1 - out = (*s)[index] - (*s)[index] = nil - *s = (*s)[:index] - return -} - -// truncate truncates this instance at index so that it contains only the -// first index items. index must be less than or equal to length. -func (s *items) truncate(index int) { - var toClear items - *s, toClear = (*s)[:index], (*s)[index:] - for len(toClear) > 0 { - toClear = toClear[copy(toClear, nilItems):] - } -} - -// find returns the index where the given item should be inserted into this -// list. 'found' is true if the item already exists in the list at the given -// index. -func (s items) find(item Item) (index int, found bool) { - i := sort.Search(len(s), func(i int) bool { - return item.Less(s[i]) - }) - if i > 0 && !s[i-1].Less(item) { - return i - 1, true - } - return i, false -} - -// children stores child nodes in a node. -type children []*node - -// insertAt inserts a value into the given index, pushing all subsequent values -// forward. -func (s *children) insertAt(index int, n *node) { - *s = append(*s, nil) - if index < len(*s) { - copy((*s)[index+1:], (*s)[index:]) - } - (*s)[index] = n -} - -// removeAt removes a value at a given index, pulling all subsequent values -// back. -func (s *children) removeAt(index int) *node { - n := (*s)[index] - copy((*s)[index:], (*s)[index+1:]) - (*s)[len(*s)-1] = nil - *s = (*s)[:len(*s)-1] - return n -} - -// pop removes and returns the last element in the list. -func (s *children) pop() (out *node) { - index := len(*s) - 1 - out = (*s)[index] - (*s)[index] = nil - *s = (*s)[:index] - return -} - -// truncate truncates this instance at index so that it contains only the -// first index children. index must be less than or equal to length. -func (s *children) truncate(index int) { - var toClear children - *s, toClear = (*s)[:index], (*s)[index:] - for len(toClear) > 0 { - toClear = toClear[copy(toClear, nilChildren):] - } -} - -// node is an internal node in a tree. -// -// It must at all times maintain the invariant that either -// * len(children) == 0, len(items) unconstrained -// * len(children) == len(items) + 1 -type node struct { - items items - children children - cow *copyOnWriteContext -} - -func (n *node) mutableFor(cow *copyOnWriteContext) *node { - if n.cow == cow { - return n - } - out := cow.newNode() - if cap(out.items) >= len(n.items) { - out.items = out.items[:len(n.items)] - } else { - out.items = make(items, len(n.items), cap(n.items)) - } - copy(out.items, n.items) - // Copy children - if cap(out.children) >= len(n.children) { - out.children = out.children[:len(n.children)] - } else { - out.children = make(children, len(n.children), cap(n.children)) - } - copy(out.children, n.children) - return out -} - -func (n *node) mutableChild(i int) *node { - c := n.children[i].mutableFor(n.cow) - n.children[i] = c - return c -} - -// split splits the given node at the given index. The current node shrinks, -// and this function returns the item that existed at that index and a new node -// containing all items/children after it. -func (n *node) split(i int) (Item, *node) { - item := n.items[i] - next := n.cow.newNode() - next.items = append(next.items, n.items[i+1:]...) - n.items.truncate(i) - if len(n.children) > 0 { - next.children = append(next.children, n.children[i+1:]...) - n.children.truncate(i + 1) - } - return item, next -} - -// maybeSplitChild checks if a child should be split, and if so splits it. -// Returns whether or not a split occurred. -func (n *node) maybeSplitChild(i, maxItems int) bool { - if len(n.children[i].items) < maxItems { - return false - } - first := n.mutableChild(i) - item, second := first.split(maxItems / 2) - n.items.insertAt(i, item) - n.children.insertAt(i+1, second) - return true -} - -// insert inserts an item into the subtree rooted at this node, making sure -// no nodes in the subtree exceed maxItems items. Should an equivalent item be -// be found/replaced by insert, it will be returned. -func (n *node) insert(item Item, maxItems int) Item { - i, found := n.items.find(item) - if found { - out := n.items[i] - n.items[i] = item - return out - } - if len(n.children) == 0 { - n.items.insertAt(i, item) - return nil - } - if n.maybeSplitChild(i, maxItems) { - inTree := n.items[i] - switch { - case item.Less(inTree): - // no change, we want first split node - case inTree.Less(item): - i++ // we want second split node - default: - out := n.items[i] - n.items[i] = item - return out - } - } - return n.mutableChild(i).insert(item, maxItems) -} - -// get finds the given key in the subtree and returns it. -func (n *node) get(key Item) Item { - i, found := n.items.find(key) - if found { - return n.items[i] - } else if len(n.children) > 0 { - return n.children[i].get(key) - } - return nil -} - -// min returns the first item in the subtree. -func min(n *node) Item { - if n == nil { - return nil - } - for len(n.children) > 0 { - n = n.children[0] - } - if len(n.items) == 0 { - return nil - } - return n.items[0] -} - -// max returns the last item in the subtree. -func max(n *node) Item { - if n == nil { - return nil - } - for len(n.children) > 0 { - n = n.children[len(n.children)-1] - } - if len(n.items) == 0 { - return nil - } - return n.items[len(n.items)-1] -} - -// toRemove details what item to remove in a node.remove call. -type toRemove int - -const ( - removeItem toRemove = iota // removes the given item - removeMin // removes smallest item in the subtree - removeMax // removes largest item in the subtree -) - -// remove removes an item from the subtree rooted at this node. -func (n *node) remove(item Item, minItems int, typ toRemove) Item { - var i int - var found bool - switch typ { - case removeMax: - if len(n.children) == 0 { - return n.items.pop() - } - i = len(n.items) - case removeMin: - if len(n.children) == 0 { - return n.items.removeAt(0) - } - i = 0 - case removeItem: - i, found = n.items.find(item) - if len(n.children) == 0 { - if found { - return n.items.removeAt(i) - } - return nil - } - default: - panic("invalid type") - } - // If we get to here, we have children. - if len(n.children[i].items) <= minItems { - return n.growChildAndRemove(i, item, minItems, typ) - } - child := n.mutableChild(i) - // Either we had enough items to begin with, or we've done some - // merging/stealing, because we've got enough now and we're ready to return - // stuff. - if found { - // The item exists at index 'i', and the child we've selected can give us a - // predecessor, since if we've gotten here it's got > minItems items in it. - out := n.items[i] - // We use our special-case 'remove' call with typ=maxItem to pull the - // predecessor of item i (the rightmost leaf of our immediate left child) - // and set it into where we pulled the item from. - n.items[i] = child.remove(nil, minItems, removeMax) - return out - } - // Final recursive call. Once we're here, we know that the item isn't in this - // node and that the child is big enough to remove from. - return child.remove(item, minItems, typ) -} - -// growChildAndRemove grows child 'i' to make sure it's possible to remove an -// item from it while keeping it at minItems, then calls remove to actually -// remove it. -// -// Most documentation says we have to do two sets of special casing: -// 1) item is in this node -// 2) item is in child -// In both cases, we need to handle the two subcases: -// A) node has enough values that it can spare one -// B) node doesn't have enough values -// For the latter, we have to check: -// a) left sibling has node to spare -// b) right sibling has node to spare -// c) we must merge -// To simplify our code here, we handle cases #1 and #2 the same: -// If a node doesn't have enough items, we make sure it does (using a,b,c). -// We then simply redo our remove call, and the second time (regardless of -// whether we're in case 1 or 2), we'll have enough items and can guarantee -// that we hit case A. -func (n *node) growChildAndRemove(i int, item Item, minItems int, typ toRemove) Item { - if i > 0 && len(n.children[i-1].items) > minItems { - // Steal from left child - child := n.mutableChild(i) - stealFrom := n.mutableChild(i - 1) - stolenItem := stealFrom.items.pop() - child.items.insertAt(0, n.items[i-1]) - n.items[i-1] = stolenItem - if len(stealFrom.children) > 0 { - child.children.insertAt(0, stealFrom.children.pop()) - } - } else if i < len(n.items) && len(n.children[i+1].items) > minItems { - // steal from right child - child := n.mutableChild(i) - stealFrom := n.mutableChild(i + 1) - stolenItem := stealFrom.items.removeAt(0) - child.items = append(child.items, n.items[i]) - n.items[i] = stolenItem - if len(stealFrom.children) > 0 { - child.children = append(child.children, stealFrom.children.removeAt(0)) - } - } else { - if i >= len(n.items) { - i-- - } - child := n.mutableChild(i) - // merge with right child - mergeItem := n.items.removeAt(i) - mergeChild := n.children.removeAt(i + 1) - child.items = append(child.items, mergeItem) - child.items = append(child.items, mergeChild.items...) - child.children = append(child.children, mergeChild.children...) - n.cow.freeNode(mergeChild) - } - return n.remove(item, minItems, typ) -} - -type direction int - -const ( - descend = direction(-1) - ascend = direction(+1) -) - -// iterate provides a simple method for iterating over elements in the tree. -// -// When ascending, the 'start' should be less than 'stop' and when descending, -// the 'start' should be greater than 'stop'. Setting 'includeStart' to true -// will force the iterator to include the first item when it equals 'start', -// thus creating a "greaterOrEqual" or "lessThanEqual" rather than just a -// "greaterThan" or "lessThan" queries. -func (n *node) iterate(dir direction, start, stop Item, includeStart bool, hit bool, iter ItemIterator) (bool, bool) { - var ok, found bool - var index int - switch dir { - case ascend: - if start != nil { - index, _ = n.items.find(start) - } - for i := index; i < len(n.items); i++ { - if len(n.children) > 0 { - if hit, ok = n.children[i].iterate(dir, start, stop, includeStart, hit, iter); !ok { - return hit, false - } - } - if !includeStart && !hit && start != nil && !start.Less(n.items[i]) { - hit = true - continue - } - hit = true - if stop != nil && !n.items[i].Less(stop) { - return hit, false - } - if !iter(n.items[i]) { - return hit, false - } - } - if len(n.children) > 0 { - if hit, ok = n.children[len(n.children)-1].iterate(dir, start, stop, includeStart, hit, iter); !ok { - return hit, false - } - } - case descend: - if start != nil { - index, found = n.items.find(start) - if !found { - index = index - 1 - } - } else { - index = len(n.items) - 1 - } - for i := index; i >= 0; i-- { - if start != nil && !n.items[i].Less(start) { - if !includeStart || hit || start.Less(n.items[i]) { - continue - } - } - if len(n.children) > 0 { - if hit, ok = n.children[i+1].iterate(dir, start, stop, includeStart, hit, iter); !ok { - return hit, false - } - } - if stop != nil && !stop.Less(n.items[i]) { - return hit, false // continue - } - hit = true - if !iter(n.items[i]) { - return hit, false - } - } - if len(n.children) > 0 { - if hit, ok = n.children[0].iterate(dir, start, stop, includeStart, hit, iter); !ok { - return hit, false - } - } - } - return hit, true -} - -// Used for testing/debugging purposes. -func (n *node) print(w io.Writer, level int) { - fmt.Fprintf(w, "%sNODE:%v\n", strings.Repeat(" ", level), n.items) - for _, c := range n.children { - c.print(w, level+1) - } -} - -// BTree is an implementation of a B-Tree. -// -// BTree stores Item instances in an ordered structure, allowing easy insertion, -// removal, and iteration. -// -// Write operations are not safe for concurrent mutation by multiple -// goroutines, but Read operations are. -type BTree struct { - degree int - length int - root *node - cow *copyOnWriteContext -} - -// copyOnWriteContext pointers determine node ownership... a tree with a write -// context equivalent to a node's write context is allowed to modify that node. -// A tree whose write context does not match a node's is not allowed to modify -// it, and must create a new, writable copy (IE: it's a Clone). -// -// When doing any write operation, we maintain the invariant that the current -// node's context is equal to the context of the tree that requested the write. -// We do this by, before we descend into any node, creating a copy with the -// correct context if the contexts don't match. -// -// Since the node we're currently visiting on any write has the requesting -// tree's context, that node is modifiable in place. Children of that node may -// not share context, but before we descend into them, we'll make a mutable -// copy. -type copyOnWriteContext struct { - freelist *FreeList -} - -// Clone clones the btree, lazily. Clone should not be called concurrently, -// but the original tree (t) and the new tree (t2) can be used concurrently -// once the Clone call completes. -// -// The internal tree structure of b is marked read-only and shared between t and -// t2. Writes to both t and t2 use copy-on-write logic, creating new nodes -// whenever one of b's original nodes would have been modified. Read operations -// should have no performance degredation. Write operations for both t and t2 -// will initially experience minor slow-downs caused by additional allocs and -// copies due to the aforementioned copy-on-write logic, but should converge to -// the original performance characteristics of the original tree. -func (t *BTree) Clone() (t2 *BTree) { - // Create two entirely new copy-on-write contexts. - // This operation effectively creates three trees: - // the original, shared nodes (old b.cow) - // the new b.cow nodes - // the new out.cow nodes - cow1, cow2 := *t.cow, *t.cow - out := *t - t.cow = &cow1 - out.cow = &cow2 - return &out -} - -// maxItems returns the max number of items to allow per node. -func (t *BTree) maxItems() int { - return t.degree*2 - 1 -} - -// minItems returns the min number of items to allow per node (ignored for the -// root node). -func (t *BTree) minItems() int { - return t.degree - 1 -} - -func (c *copyOnWriteContext) newNode() (n *node) { - n = c.freelist.newNode() - n.cow = c - return -} - -type freeType int - -const ( - ftFreelistFull freeType = iota // node was freed (available for GC, not stored in freelist) - ftStored // node was stored in the freelist for later use - ftNotOwned // node was ignored by COW, since it's owned by another one -) - -// freeNode frees a node within a given COW context, if it's owned by that -// context. It returns what happened to the node (see freeType const -// documentation). -func (c *copyOnWriteContext) freeNode(n *node) freeType { - if n.cow == c { - // clear to allow GC - n.items.truncate(0) - n.children.truncate(0) - n.cow = nil - if c.freelist.freeNode(n) { - return ftStored - } else { - return ftFreelistFull - } - } else { - return ftNotOwned - } -} - -// ReplaceOrInsert adds the given item to the tree. If an item in the tree -// already equals the given one, it is removed from the tree and returned. -// Otherwise, nil is returned. -// -// nil cannot be added to the tree (will panic). -func (t *BTree) ReplaceOrInsert(item Item) Item { - if item == nil { - panic("nil item being added to BTree") - } - if t.root == nil { - t.root = t.cow.newNode() - t.root.items = append(t.root.items, item) - t.length++ - return nil - } else { - t.root = t.root.mutableFor(t.cow) - if len(t.root.items) >= t.maxItems() { - item2, second := t.root.split(t.maxItems() / 2) - oldroot := t.root - t.root = t.cow.newNode() - t.root.items = append(t.root.items, item2) - t.root.children = append(t.root.children, oldroot, second) - } - } - out := t.root.insert(item, t.maxItems()) - if out == nil { - t.length++ - } - return out -} - -// Delete removes an item equal to the passed in item from the tree, returning -// it. If no such item exists, returns nil. -func (t *BTree) Delete(item Item) Item { - return t.deleteItem(item, removeItem) -} - -// DeleteMin removes the smallest item in the tree and returns it. -// If no such item exists, returns nil. -func (t *BTree) DeleteMin() Item { - return t.deleteItem(nil, removeMin) -} - -// DeleteMax removes the largest item in the tree and returns it. -// If no such item exists, returns nil. -func (t *BTree) DeleteMax() Item { - return t.deleteItem(nil, removeMax) -} - -func (t *BTree) deleteItem(item Item, typ toRemove) Item { - if t.root == nil || len(t.root.items) == 0 { - return nil - } - t.root = t.root.mutableFor(t.cow) - out := t.root.remove(item, t.minItems(), typ) - if len(t.root.items) == 0 && len(t.root.children) > 0 { - oldroot := t.root - t.root = t.root.children[0] - t.cow.freeNode(oldroot) - } - if out != nil { - t.length-- - } - return out -} - -// AscendRange calls the iterator for every value in the tree within the range -// [greaterOrEqual, lessThan), until iterator returns false. -func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) { - if t.root == nil { - return - } - t.root.iterate(ascend, greaterOrEqual, lessThan, true, false, iterator) -} - -// AscendLessThan calls the iterator for every value in the tree within the range -// [first, pivot), until iterator returns false. -func (t *BTree) AscendLessThan(pivot Item, iterator ItemIterator) { - if t.root == nil { - return - } - t.root.iterate(ascend, nil, pivot, false, false, iterator) -} - -// AscendGreaterOrEqual calls the iterator for every value in the tree within -// the range [pivot, last], until iterator returns false. -func (t *BTree) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) { - if t.root == nil { - return - } - t.root.iterate(ascend, pivot, nil, true, false, iterator) -} - -// Ascend calls the iterator for every value in the tree within the range -// [first, last], until iterator returns false. -func (t *BTree) Ascend(iterator ItemIterator) { - if t.root == nil { - return - } - t.root.iterate(ascend, nil, nil, false, false, iterator) -} - -// DescendRange calls the iterator for every value in the tree within the range -// [lessOrEqual, greaterThan), until iterator returns false. -func (t *BTree) DescendRange(lessOrEqual, greaterThan Item, iterator ItemIterator) { - if t.root == nil { - return - } - t.root.iterate(descend, lessOrEqual, greaterThan, true, false, iterator) -} - -// DescendLessOrEqual calls the iterator for every value in the tree within the range -// [pivot, first], until iterator returns false. -func (t *BTree) DescendLessOrEqual(pivot Item, iterator ItemIterator) { - if t.root == nil { - return - } - t.root.iterate(descend, pivot, nil, true, false, iterator) -} - -// DescendGreaterThan calls the iterator for every value in the tree within -// the range [last, pivot), until iterator returns false. -func (t *BTree) DescendGreaterThan(pivot Item, iterator ItemIterator) { - if t.root == nil { - return - } - t.root.iterate(descend, nil, pivot, false, false, iterator) -} - -// Descend calls the iterator for every value in the tree within the range -// [last, first], until iterator returns false. -func (t *BTree) Descend(iterator ItemIterator) { - if t.root == nil { - return - } - t.root.iterate(descend, nil, nil, false, false, iterator) -} - -// Get looks for the key item in the tree, returning it. It returns nil if -// unable to find that item. -func (t *BTree) Get(key Item) Item { - if t.root == nil { - return nil - } - return t.root.get(key) -} - -// Min returns the smallest item in the tree, or nil if the tree is empty. -func (t *BTree) Min() Item { - return min(t.root) -} - -// Max returns the largest item in the tree, or nil if the tree is empty. -func (t *BTree) Max() Item { - return max(t.root) -} - -// Has returns true if the given key is in the tree. -func (t *BTree) Has(key Item) bool { - return t.Get(key) != nil -} - -// Len returns the number of items currently in the tree. -func (t *BTree) Len() int { - return t.length -} - -// Clear removes all items from the btree. If addNodesToFreelist is true, -// t's nodes are added to its freelist as part of this call, until the freelist -// is full. Otherwise, the root node is simply dereferenced and the subtree -// left to Go's normal GC processes. -// -// This can be much faster -// than calling Delete on all elements, because that requires finding/removing -// each element in the tree and updating the tree accordingly. It also is -// somewhat faster than creating a new tree to replace the old one, because -// nodes from the old tree are reclaimed into the freelist for use by the new -// one, instead of being lost to the garbage collector. -// -// This call takes: -// O(1): when addNodesToFreelist is false, this is a single operation. -// O(1): when the freelist is already full, it breaks out immediately -// O(freelist size): when the freelist is empty and the nodes are all owned -// by this tree, nodes are added to the freelist until full. -// O(tree size): when all nodes are owned by another tree, all nodes are -// iterated over looking for nodes to add to the freelist, and due to -// ownership, none are. -func (t *BTree) Clear(addNodesToFreelist bool) { - if t.root != nil && addNodesToFreelist { - t.root.reset(t.cow) - } - t.root, t.length = nil, 0 -} - -// reset returns a subtree to the freelist. It breaks out immediately if the -// freelist is full, since the only benefit of iterating is to fill that -// freelist up. Returns true if parent reset call should continue. -func (n *node) reset(c *copyOnWriteContext) bool { - for _, child := range n.children { - if !child.reset(c) { - return false - } - } - return c.freeNode(n) != ftFreelistFull -} - -// Int implements the Item interface for integers. -type Int int - -// Less returns true if int(a) < int(b). -func (a Int) Less(b Item) bool { - return a < b.(Int) -} diff --git a/vendor/github.com/google/go-cmp/cmp/path.go b/vendor/github.com/google/go-cmp/cmp/path.go index 3d45c1a47f2..f01eff318c5 100644 --- a/vendor/github.com/google/go-cmp/cmp/path.go +++ b/vendor/github.com/google/go-cmp/cmp/path.go @@ -315,7 +315,7 @@ func (tf Transform) Option() Option { return tf.trans } // pops the address from the stack. Thus, when traversing into a pointer from // reflect.Ptr, reflect.Slice element, or reflect.Map, we can detect cycles // by checking whether the pointer has already been visited. The cycle detection -// uses a seperate stack for the x and y values. +// uses a separate stack for the x and y values. // // If a cycle is detected we need to determine whether the two pointers // should be considered equal. The definition of equality chosen by Equal diff --git a/vendor/github.com/google/go-cmp/cmp/report_slices.go b/vendor/github.com/google/go-cmp/cmp/report_slices.go index 168f92f3c12..2ad3bc85ba8 100644 --- a/vendor/github.com/google/go-cmp/cmp/report_slices.go +++ b/vendor/github.com/google/go-cmp/cmp/report_slices.go @@ -7,6 +7,7 @@ package cmp import ( "bytes" "fmt" + "math" "reflect" "strconv" "strings" @@ -96,15 +97,16 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { } // Auto-detect the type of the data. - var isLinedText, isText, isBinary bool var sx, sy string + var ssx, ssy []string + var isString, isMostlyText, isPureLinedText, isBinary bool switch { case t.Kind() == reflect.String: sx, sy = vx.String(), vy.String() - isText = true // Initial estimate, verify later + isString = true case t.Kind() == reflect.Slice && t.Elem() == reflect.TypeOf(byte(0)): sx, sy = string(vx.Bytes()), string(vy.Bytes()) - isBinary = true // Initial estimate, verify later + isString = true case t.Kind() == reflect.Array: // Arrays need to be addressable for slice operations to work. vx2, vy2 := reflect.New(t).Elem(), reflect.New(t).Elem() @@ -112,13 +114,12 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { vy2.Set(vy) vx, vy = vx2, vy2 } - if isText || isBinary { - var numLines, lastLineIdx, maxLineLen int - isBinary = !utf8.ValidString(sx) || !utf8.ValidString(sy) + if isString { + var numTotalRunes, numValidRunes, numLines, lastLineIdx, maxLineLen int for i, r := range sx + sy { - if !(unicode.IsPrint(r) || unicode.IsSpace(r)) || r == utf8.RuneError { - isBinary = true - break + numTotalRunes++ + if (unicode.IsPrint(r) || unicode.IsSpace(r)) && r != utf8.RuneError { + numValidRunes++ } if r == '\n' { if maxLineLen < i-lastLineIdx { @@ -128,8 +129,26 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { numLines++ } } - isText = !isBinary - isLinedText = isText && numLines >= 4 && maxLineLen <= 1024 + isPureText := numValidRunes == numTotalRunes + isMostlyText = float64(numValidRunes) > math.Floor(0.90*float64(numTotalRunes)) + isPureLinedText = isPureText && numLines >= 4 && maxLineLen <= 1024 + isBinary = !isMostlyText + + // Avoid diffing by lines if it produces a significantly more complex + // edit script than diffing by bytes. + if isPureLinedText { + ssx = strings.Split(sx, "\n") + ssy = strings.Split(sy, "\n") + esLines := diff.Difference(len(ssx), len(ssy), func(ix, iy int) diff.Result { + return diff.BoolResult(ssx[ix] == ssy[iy]) + }) + esBytes := diff.Difference(len(sx), len(sy), func(ix, iy int) diff.Result { + return diff.BoolResult(sx[ix] == sy[iy]) + }) + efficiencyLines := float64(esLines.Dist()) / float64(len(esLines)) + efficiencyBytes := float64(esBytes.Dist()) / float64(len(esBytes)) + isPureLinedText = efficiencyLines < 4*efficiencyBytes + } } // Format the string into printable records. @@ -138,9 +157,7 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { switch { // If the text appears to be multi-lined text, // then perform differencing across individual lines. - case isLinedText: - ssx := strings.Split(sx, "\n") - ssy := strings.Split(sy, "\n") + case isPureLinedText: list = opts.formatDiffSlice( reflect.ValueOf(ssx), reflect.ValueOf(ssy), 1, "line", func(v reflect.Value, d diffMode) textRecord { @@ -229,7 +246,7 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { // If the text appears to be single-lined text, // then perform differencing in approximately fixed-sized chunks. // The output is printed as quoted strings. - case isText: + case isMostlyText: list = opts.formatDiffSlice( reflect.ValueOf(sx), reflect.ValueOf(sy), 64, "byte", func(v reflect.Value, d diffMode) textRecord { @@ -237,7 +254,6 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { return textRecord{Diff: d, Value: textLine(s)} }, ) - delim = "" // If the text appears to be binary data, // then perform differencing in approximately fixed-sized chunks. @@ -299,7 +315,7 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { // Wrap the output with appropriate type information. var out textNode = &textWrap{Prefix: "{", Value: list, Suffix: "}"} - if !isText { + if !isMostlyText { // The "{...}" byte-sequence literal is not valid Go syntax for strings. // Emit the type for extra clarity (e.g. "string{...}"). if t.Kind() == reflect.String { @@ -338,8 +354,11 @@ func (opts formatOptions) formatDiffSlice( vx, vy reflect.Value, chunkSize int, name string, makeRec func(reflect.Value, diffMode) textRecord, ) (list textList) { - es := diff.Difference(vx.Len(), vy.Len(), func(ix int, iy int) diff.Result { - return diff.BoolResult(vx.Index(ix).Interface() == vy.Index(iy).Interface()) + eq := func(ix, iy int) bool { + return vx.Index(ix).Interface() == vy.Index(iy).Interface() + } + es := diff.Difference(vx.Len(), vy.Len(), func(ix, iy int) diff.Result { + return diff.BoolResult(eq(ix, iy)) }) appendChunks := func(v reflect.Value, d diffMode) int { @@ -364,6 +383,7 @@ func (opts formatOptions) formatDiffSlice( groups := coalesceAdjacentEdits(name, es) groups = coalesceInterveningIdentical(groups, chunkSize/4) + groups = cleanupSurroundingIdentical(groups, eq) maxGroup := diffStats{Name: name} for i, ds := range groups { if maxLen >= 0 && numDiffs >= maxLen { @@ -416,25 +436,36 @@ func (opts formatOptions) formatDiffSlice( // coalesceAdjacentEdits coalesces the list of edits into groups of adjacent // equal or unequal counts. +// +// Example: +// +// Input: "..XXY...Y" +// Output: [ +// {NumIdentical: 2}, +// {NumRemoved: 2, NumInserted 1}, +// {NumIdentical: 3}, +// {NumInserted: 1}, +// ] +// func coalesceAdjacentEdits(name string, es diff.EditScript) (groups []diffStats) { - var prevCase int // Arbitrary index into which case last occurred - lastStats := func(i int) *diffStats { - if prevCase != i { + var prevMode byte + lastStats := func(mode byte) *diffStats { + if prevMode != mode { groups = append(groups, diffStats{Name: name}) - prevCase = i + prevMode = mode } return &groups[len(groups)-1] } for _, e := range es { switch e { case diff.Identity: - lastStats(1).NumIdentical++ + lastStats('=').NumIdentical++ case diff.UniqueX: - lastStats(2).NumRemoved++ + lastStats('!').NumRemoved++ case diff.UniqueY: - lastStats(2).NumInserted++ + lastStats('!').NumInserted++ case diff.Modified: - lastStats(2).NumModified++ + lastStats('!').NumModified++ } } return groups @@ -444,6 +475,35 @@ func coalesceAdjacentEdits(name string, es diff.EditScript) (groups []diffStats) // equal groups into adjacent unequal groups that currently result in a // dual inserted/removed printout. This acts as a high-pass filter to smooth // out high-frequency changes within the windowSize. +// +// Example: +// +// WindowSize: 16, +// Input: [ +// {NumIdentical: 61}, // group 0 +// {NumRemoved: 3, NumInserted: 1}, // group 1 +// {NumIdentical: 6}, // ├── coalesce +// {NumInserted: 2}, // ├── coalesce +// {NumIdentical: 1}, // ├── coalesce +// {NumRemoved: 9}, // └── coalesce +// {NumIdentical: 64}, // group 2 +// {NumRemoved: 3, NumInserted: 1}, // group 3 +// {NumIdentical: 6}, // ├── coalesce +// {NumInserted: 2}, // ├── coalesce +// {NumIdentical: 1}, // ├── coalesce +// {NumRemoved: 7}, // ├── coalesce +// {NumIdentical: 1}, // ├── coalesce +// {NumRemoved: 2}, // └── coalesce +// {NumIdentical: 63}, // group 4 +// ] +// Output: [ +// {NumIdentical: 61}, +// {NumIdentical: 7, NumRemoved: 12, NumInserted: 3}, +// {NumIdentical: 64}, +// {NumIdentical: 8, NumRemoved: 12, NumInserted: 3}, +// {NumIdentical: 63}, +// ] +// func coalesceInterveningIdentical(groups []diffStats, windowSize int) []diffStats { groups, groupsOrig := groups[:0], groups for i, ds := range groupsOrig { @@ -463,3 +523,91 @@ func coalesceInterveningIdentical(groups []diffStats, windowSize int) []diffStat } return groups } + +// cleanupSurroundingIdentical scans through all unequal groups, and +// moves any leading sequence of equal elements to the preceding equal group and +// moves and trailing sequence of equal elements to the succeeding equal group. +// +// This is necessary since coalesceInterveningIdentical may coalesce edit groups +// together such that leading/trailing spans of equal elements becomes possible. +// Note that this can occur even with an optimal diffing algorithm. +// +// Example: +// +// Input: [ +// {NumIdentical: 61}, +// {NumIdentical: 1 , NumRemoved: 11, NumInserted: 2}, // assume 3 leading identical elements +// {NumIdentical: 67}, +// {NumIdentical: 7, NumRemoved: 12, NumInserted: 3}, // assume 10 trailing identical elements +// {NumIdentical: 54}, +// ] +// Output: [ +// {NumIdentical: 64}, // incremented by 3 +// {NumRemoved: 9}, +// {NumIdentical: 67}, +// {NumRemoved: 9}, +// {NumIdentical: 64}, // incremented by 10 +// ] +// +func cleanupSurroundingIdentical(groups []diffStats, eq func(i, j int) bool) []diffStats { + var ix, iy int // indexes into sequence x and y + for i, ds := range groups { + // Handle equal group. + if ds.NumDiff() == 0 { + ix += ds.NumIdentical + iy += ds.NumIdentical + continue + } + + // Handle unequal group. + nx := ds.NumIdentical + ds.NumRemoved + ds.NumModified + ny := ds.NumIdentical + ds.NumInserted + ds.NumModified + var numLeadingIdentical, numTrailingIdentical int + for i := 0; i < nx && i < ny && eq(ix+i, iy+i); i++ { + numLeadingIdentical++ + } + for i := 0; i < nx && i < ny && eq(ix+nx-1-i, iy+ny-1-i); i++ { + numTrailingIdentical++ + } + if numIdentical := numLeadingIdentical + numTrailingIdentical; numIdentical > 0 { + if numLeadingIdentical > 0 { + // Remove leading identical span from this group and + // insert it into the preceding group. + if i-1 >= 0 { + groups[i-1].NumIdentical += numLeadingIdentical + } else { + // No preceding group exists, so prepend a new group, + // but do so after we finish iterating over all groups. + defer func() { + groups = append([]diffStats{{Name: groups[0].Name, NumIdentical: numLeadingIdentical}}, groups...) + }() + } + // Increment indexes since the preceding group would have handled this. + ix += numLeadingIdentical + iy += numLeadingIdentical + } + if numTrailingIdentical > 0 { + // Remove trailing identical span from this group and + // insert it into the succeeding group. + if i+1 < len(groups) { + groups[i+1].NumIdentical += numTrailingIdentical + } else { + // No succeeding group exists, so append a new group, + // but do so after we finish iterating over all groups. + defer func() { + groups = append(groups, diffStats{Name: groups[len(groups)-1].Name, NumIdentical: numTrailingIdentical}) + }() + } + // Do not increment indexes since the succeeding group will handle this. + } + + // Update this group since some identical elements were removed. + nx -= numIdentical + ny -= numIdentical + groups[i] = diffStats{Name: ds.Name, NumRemoved: nx, NumInserted: ny} + } + ix += nx + iy += ny + } + return groups +} diff --git a/vendor/github.com/google/shlex/COPYING b/vendor/github.com/google/shlex/COPYING deleted file mode 100644 index d6456956733..00000000000 --- a/vendor/github.com/google/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/google/shlex/README b/vendor/github.com/google/shlex/README deleted file mode 100644 index c86bcc066fd..00000000000 --- a/vendor/github.com/google/shlex/README +++ /dev/null @@ -1,2 +0,0 @@ -go-shlex is a simple lexer for go that supports shell-style quoting, -commenting, and escaping. diff --git a/vendor/github.com/google/shlex/shlex.go b/vendor/github.com/google/shlex/shlex.go deleted file mode 100644 index d98308bce38..00000000000 --- a/vendor/github.com/google/shlex/shlex.go +++ /dev/null @@ -1,416 +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 implements a simple lexer which splits input in to tokens using -shell-style rules for quoting and commenting. - -The basic use case uses the default ASCII lexer to split a string into sub-strings: - - shlex.Split("one \"two three\" four") -> []string{"one", "two three", "four"} - -To process a stream of strings: - - l := NewLexer(os.Stdin) - for ; token, err := l.Next(); err != nil { - // process token - } - -To access the raw token stream (which includes tokens for comments): - - t := NewTokenizer(os.Stdin) - for ; token, err := t.Next(); err != nil { - // process token - } - -*/ -package shlex - -import ( - "bufio" - "fmt" - "io" - "strings" -) - -// TokenType is a top-level token classification: A word, space, comment, unknown. -type TokenType int - -// runeTokenClass is the type of a UTF-8 character classification: A quote, space, escape. -type runeTokenClass int - -// the internal state used by the lexer state machine -type lexerState int - -// Token is a (type, value) pair representing a lexographical token. -type Token struct { - tokenType TokenType - value string -} - -// Equal reports whether tokens a, and b, are equal. -// Two tokens are equal if both their types and values are equal. A nil token can -// never be equal to 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 -} - -// Named classes of UTF-8 runes -const ( - spaceRunes = " \t\r\n" - escapingQuoteRunes = `"` - nonEscapingQuoteRunes = "'" - escapeRunes = `\` - commentRunes = "#" -) - -// Classes of rune token -const ( - unknownRuneClass runeTokenClass = iota - spaceRuneClass - escapingQuoteRuneClass - nonEscapingQuoteRuneClass - escapeRuneClass - commentRuneClass - eofRuneClass -) - -// Classes of lexographic token -const ( - UnknownToken TokenType = iota - WordToken - SpaceToken - CommentToken -) - -// Lexer state machine states -const ( - startState lexerState = iota // no runes have been seen - inWordState // processing regular runes in a word - escapingState // we have just consumed an escape rune; the next rune is literal - escapingQuotedState // we have just consumed an escape rune within a quoted string - quotingEscapingState // we are within a quoted string that supports escaping ("...") - quotingState // we are within a string that does not support escaping ('...') - commentState // we are within a comment (everything following an unquoted or unescaped # -) - -// tokenClassifier is used for classifying rune characters. -type tokenClassifier map[rune]runeTokenClass - -func (typeMap tokenClassifier) addRuneClass(runes string, tokenType runeTokenClass) { - for _, runeChar := range runes { - typeMap[runeChar] = tokenType - } -} - -// newDefaultClassifier creates a new classifier for ASCII characters. -func newDefaultClassifier() tokenClassifier { - t := tokenClassifier{} - t.addRuneClass(spaceRunes, spaceRuneClass) - t.addRuneClass(escapingQuoteRunes, escapingQuoteRuneClass) - t.addRuneClass(nonEscapingQuoteRunes, nonEscapingQuoteRuneClass) - t.addRuneClass(escapeRunes, escapeRuneClass) - t.addRuneClass(commentRunes, commentRuneClass) - return t -} - -// ClassifyRune classifiees a rune -func (t tokenClassifier) ClassifyRune(runeVal rune) runeTokenClass { - return t[runeVal] -} - -// Lexer turns an input stream into a sequence of tokens. Whitespace and comments are skipped. -type Lexer Tokenizer - -// NewLexer creates a new lexer from an input stream. -func NewLexer(r io.Reader) *Lexer { - - return (*Lexer)(NewTokenizer(r)) -} - -// Next returns the next word, or an error. If there are no more words, -// the error will be io.EOF. -func (l *Lexer) Next() (string, error) { - for { - token, err := (*Tokenizer)(l).Next() - if err != nil { - return "", err - } - switch token.tokenType { - case WordToken: - return token.value, nil - case CommentToken: - // skip comments - default: - return "", fmt.Errorf("Unknown token type: %v", token.tokenType) - } - } -} - -// Tokenizer turns an input stream into a sequence of typed tokens -type Tokenizer struct { - input bufio.Reader - classifier tokenClassifier -} - -// NewTokenizer creates a new tokenizer from an input stream. -func NewTokenizer(r io.Reader) *Tokenizer { - input := bufio.NewReader(r) - classifier := newDefaultClassifier() - return &Tokenizer{ - input: *input, - classifier: classifier} -} - -// scanStream scans the stream for the next token using the internal state machine. -// It will panic if it encounters a rune which it does not know how to handle. -func (t *Tokenizer) scanStream() (*Token, error) { - state := startState - var tokenType TokenType - var value []rune - var nextRune rune - var nextRuneType runeTokenClass - var err error - - for { - nextRune, _, err = t.input.ReadRune() - nextRuneType = t.classifier.ClassifyRune(nextRune) - - if err == io.EOF { - nextRuneType = eofRuneClass - err = nil - } else if err != nil { - return nil, err - } - - switch state { - case startState: // no runes read yet - { - switch nextRuneType { - case eofRuneClass: - { - return nil, io.EOF - } - case spaceRuneClass: - { - } - case escapingQuoteRuneClass: - { - tokenType = WordToken - state = quotingEscapingState - } - case nonEscapingQuoteRuneClass: - { - tokenType = WordToken - state = quotingState - } - case escapeRuneClass: - { - tokenType = WordToken - state = escapingState - } - case commentRuneClass: - { - tokenType = CommentToken - state = commentState - } - default: - { - tokenType = WordToken - value = append(value, nextRune) - state = inWordState - } - } - } - case inWordState: // in a regular word - { - switch nextRuneType { - case eofRuneClass: - { - token := &Token{ - tokenType: tokenType, - value: string(value)} - return token, err - } - case spaceRuneClass: - { - token := &Token{ - tokenType: tokenType, - value: string(value)} - return token, err - } - case escapingQuoteRuneClass: - { - state = quotingEscapingState - } - case nonEscapingQuoteRuneClass: - { - state = quotingState - } - case escapeRuneClass: - { - state = escapingState - } - default: - { - value = append(value, nextRune) - } - } - } - case escapingState: // the rune after an escape character - { - switch nextRuneType { - case eofRuneClass: - { - err = fmt.Errorf("EOF found after escape character") - token := &Token{ - tokenType: tokenType, - value: string(value)} - return token, err - } - default: - { - state = inWordState - value = append(value, nextRune) - } - } - } - case escapingQuotedState: // the next rune after an escape character, in double quotes - { - switch nextRuneType { - case eofRuneClass: - { - err = fmt.Errorf("EOF found after escape character") - token := &Token{ - tokenType: tokenType, - value: string(value)} - return token, err - } - default: - { - state = quotingEscapingState - value = append(value, nextRune) - } - } - } - case quotingEscapingState: // in escaping double quotes - { - switch nextRuneType { - case eofRuneClass: - { - err = fmt.Errorf("EOF found when expecting closing quote") - token := &Token{ - tokenType: tokenType, - value: string(value)} - return token, err - } - case escapingQuoteRuneClass: - { - state = inWordState - } - case escapeRuneClass: - { - state = escapingQuotedState - } - default: - { - value = append(value, nextRune) - } - } - } - case quotingState: // in non-escaping single quotes - { - switch nextRuneType { - case eofRuneClass: - { - err = fmt.Errorf("EOF found when expecting closing quote") - token := &Token{ - tokenType: tokenType, - value: string(value)} - return token, err - } - case nonEscapingQuoteRuneClass: - { - state = inWordState - } - default: - { - value = append(value, nextRune) - } - } - } - case commentState: // in a comment - { - switch nextRuneType { - case eofRuneClass: - { - token := &Token{ - tokenType: tokenType, - value: string(value)} - return token, err - } - case spaceRuneClass: - { - if nextRune == '\n' { - state = startState - token := &Token{ - tokenType: tokenType, - value: string(value)} - return token, err - } else { - value = append(value, nextRune) - } - } - default: - { - value = append(value, nextRune) - } - } - } - default: - { - return nil, fmt.Errorf("Unexpected state: %v", state) - } - } - } -} - -// Next returns the next token in the stream. -func (t *Tokenizer) Next() (*Token, error) { - return t.scanStream() -} - -// Split partitions a string into a slice of strings. -func Split(s string) ([]string, error) { - l := NewLexer(strings.NewReader(s)) - subStrings := make([]string, 0) - for { - word, err := l.Next() - if err != nil { - if err == io.EOF { - return subStrings, nil - } - return subStrings, err - } - subStrings = append(subStrings, word) - } -} diff --git a/vendor/github.com/gregjones/httpcache/.travis.yml b/vendor/github.com/gregjones/httpcache/.travis.yml deleted file mode 100644 index 597bc9996f0..00000000000 --- a/vendor/github.com/gregjones/httpcache/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -sudo: false -language: go -matrix: - allow_failures: - - go: master - fast_finish: true - include: - - go: 1.10.x - - go: 1.11.x - env: GOFMT=1 - - go: master -install: - - # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step). -script: - - go get -t -v ./... - - if test -n "${GOFMT}"; then gofmt -w -s . && git diff --exit-code; fi - - go tool vet . - - go test -v -race ./... diff --git a/vendor/github.com/gregjones/httpcache/LICENSE.txt b/vendor/github.com/gregjones/httpcache/LICENSE.txt deleted file mode 100644 index 81316beb0cb..00000000000 --- a/vendor/github.com/gregjones/httpcache/LICENSE.txt +++ /dev/null @@ -1,7 +0,0 @@ -Copyright © 2012 Greg Jones (greg.jones@gmail.com) - -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/gregjones/httpcache/README.md b/vendor/github.com/gregjones/httpcache/README.md deleted file mode 100644 index 51e7d23d094..00000000000 --- a/vendor/github.com/gregjones/httpcache/README.md +++ /dev/null @@ -1,29 +0,0 @@ -httpcache -========= - -[![Build Status](https://travis-ci.org/gregjones/httpcache.svg?branch=master)](https://travis-ci.org/gregjones/httpcache) [![GoDoc](https://godoc.org/github.com/gregjones/httpcache?status.svg)](https://godoc.org/github.com/gregjones/httpcache) - -Package httpcache provides a http.RoundTripper implementation that works as a mostly [RFC 7234](https://tools.ietf.org/html/rfc7234) compliant cache for http responses. - -It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client and not for a shared proxy). - -This project isn't actively maintained; it works for what I, and seemingly others, want to do with it, and I consider it "done". That said, if you find any issues, please open a Pull Request and I will try to review it. Any changes now that change the public API won't be considered. - -Cache Backends --------------- - -- The built-in 'memory' cache stores responses in an in-memory map. -- [`github.com/gregjones/httpcache/diskcache`](https://github.com/gregjones/httpcache/tree/master/diskcache) provides a filesystem-backed cache using the [diskv](https://github.com/peterbourgon/diskv) library. -- [`github.com/gregjones/httpcache/memcache`](https://github.com/gregjones/httpcache/tree/master/memcache) provides memcache implementations, for both App Engine and 'normal' memcache servers. -- [`sourcegraph.com/sourcegraph/s3cache`](https://sourcegraph.com/github.com/sourcegraph/s3cache) uses Amazon S3 for storage. -- [`github.com/gregjones/httpcache/leveldbcache`](https://github.com/gregjones/httpcache/tree/master/leveldbcache) provides a filesystem-backed cache using [leveldb](https://github.com/syndtr/goleveldb/leveldb). -- [`github.com/die-net/lrucache`](https://github.com/die-net/lrucache) provides an in-memory cache that will evict least-recently used entries. -- [`github.com/die-net/lrucache/twotier`](https://github.com/die-net/lrucache/tree/master/twotier) allows caches to be combined, for example to use lrucache above with a persistent disk-cache. -- [`github.com/birkelund/boltdbcache`](https://github.com/birkelund/boltdbcache) provides a BoltDB implementation (based on the [bbolt](https://github.com/coreos/bbolt) fork). - -If you implement any other backend and wish it to be linked here, please send a PR editing this file. - -License -------- - -- [MIT License](LICENSE.txt) diff --git a/vendor/github.com/gregjones/httpcache/diskcache/diskcache.go b/vendor/github.com/gregjones/httpcache/diskcache/diskcache.go deleted file mode 100644 index 42e3129d823..00000000000 --- a/vendor/github.com/gregjones/httpcache/diskcache/diskcache.go +++ /dev/null @@ -1,61 +0,0 @@ -// Package diskcache provides an implementation of httpcache.Cache that uses the diskv package -// to supplement an in-memory map with persistent storage -// -package diskcache - -import ( - "bytes" - "crypto/md5" - "encoding/hex" - "github.com/peterbourgon/diskv" - "io" -) - -// Cache is an implementation of httpcache.Cache that supplements the in-memory map with persistent storage -type Cache struct { - d *diskv.Diskv -} - -// Get returns the response corresponding to key if present -func (c *Cache) Get(key string) (resp []byte, ok bool) { - key = keyToFilename(key) - resp, err := c.d.Read(key) - if err != nil { - return []byte{}, false - } - return resp, true -} - -// Set saves a response to the cache as key -func (c *Cache) Set(key string, resp []byte) { - key = keyToFilename(key) - c.d.WriteStream(key, bytes.NewReader(resp), true) -} - -// Delete removes the response with key from the cache -func (c *Cache) Delete(key string) { - key = keyToFilename(key) - c.d.Erase(key) -} - -func keyToFilename(key string) string { - h := md5.New() - io.WriteString(h, key) - return hex.EncodeToString(h.Sum(nil)) -} - -// New returns a new Cache that will store files in basePath -func New(basePath string) *Cache { - return &Cache{ - d: diskv.New(diskv.Options{ - BasePath: basePath, - CacheSizeMax: 100 * 1024 * 1024, // 100MB - }), - } -} - -// NewWithDiskv returns a new Cache using the provided Diskv as underlying -// storage. -func NewWithDiskv(d *diskv.Diskv) *Cache { - return &Cache{d} -} diff --git a/vendor/github.com/gregjones/httpcache/httpcache.go b/vendor/github.com/gregjones/httpcache/httpcache.go deleted file mode 100644 index b41a63d1ff5..00000000000 --- a/vendor/github.com/gregjones/httpcache/httpcache.go +++ /dev/null @@ -1,551 +0,0 @@ -// Package httpcache provides a http.RoundTripper implementation that works as a -// mostly RFC-compliant cache for http responses. -// -// It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client -// and not for a shared proxy). -// -package httpcache - -import ( - "bufio" - "bytes" - "errors" - "io" - "io/ioutil" - "net/http" - "net/http/httputil" - "strings" - "sync" - "time" -) - -const ( - stale = iota - fresh - transparent - // XFromCache is the header added to responses that are returned from the cache - XFromCache = "X-From-Cache" -) - -// A Cache interface is used by the Transport to store and retrieve responses. -type Cache interface { - // Get returns the []byte representation of a cached response and a bool - // set to true if the value isn't empty - Get(key string) (responseBytes []byte, ok bool) - // Set stores the []byte representation of a response against a key - Set(key string, responseBytes []byte) - // Delete removes the value associated with the key - Delete(key string) -} - -// cacheKey returns the cache key for req. -func cacheKey(req *http.Request) string { - if req.Method == http.MethodGet { - return req.URL.String() - } else { - return req.Method + " " + req.URL.String() - } -} - -// CachedResponse returns the cached http.Response for req if present, and nil -// otherwise. -func CachedResponse(c Cache, req *http.Request) (resp *http.Response, err error) { - cachedVal, ok := c.Get(cacheKey(req)) - if !ok { - return - } - - b := bytes.NewBuffer(cachedVal) - return http.ReadResponse(bufio.NewReader(b), req) -} - -// MemoryCache is an implemtation of Cache that stores responses in an in-memory map. -type MemoryCache struct { - mu sync.RWMutex - items map[string][]byte -} - -// Get returns the []byte representation of the response and true if present, false if not -func (c *MemoryCache) Get(key string) (resp []byte, ok bool) { - c.mu.RLock() - resp, ok = c.items[key] - c.mu.RUnlock() - return resp, ok -} - -// Set saves response resp to the cache with key -func (c *MemoryCache) Set(key string, resp []byte) { - c.mu.Lock() - c.items[key] = resp - c.mu.Unlock() -} - -// Delete removes key from the cache -func (c *MemoryCache) Delete(key string) { - c.mu.Lock() - delete(c.items, key) - c.mu.Unlock() -} - -// NewMemoryCache returns a new Cache that will store items in an in-memory map -func NewMemoryCache() *MemoryCache { - c := &MemoryCache{items: map[string][]byte{}} - return c -} - -// Transport is an implementation of http.RoundTripper that will return values from a cache -// where possible (avoiding a network request) and will additionally add validators (etag/if-modified-since) -// to repeated requests allowing servers to return 304 / Not Modified -type Transport struct { - // The RoundTripper interface actually used to make requests - // If nil, http.DefaultTransport is used - Transport http.RoundTripper - Cache Cache - // If true, responses returned from the cache will be given an extra header, X-From-Cache - MarkCachedResponses bool -} - -// NewTransport returns a new Transport with the -// provided Cache implementation and MarkCachedResponses set to true -func NewTransport(c Cache) *Transport { - return &Transport{Cache: c, MarkCachedResponses: true} -} - -// Client returns an *http.Client that caches responses. -func (t *Transport) Client() *http.Client { - return &http.Client{Transport: t} -} - -// varyMatches will return false unless all of the cached values for the headers listed in Vary -// match the new request -func varyMatches(cachedResp *http.Response, req *http.Request) bool { - for _, header := range headerAllCommaSepValues(cachedResp.Header, "vary") { - header = http.CanonicalHeaderKey(header) - if header != "" && req.Header.Get(header) != cachedResp.Header.Get("X-Varied-"+header) { - return false - } - } - return true -} - -// RoundTrip takes a Request and returns a Response -// -// If there is a fresh Response already in cache, then it will be returned without connecting to -// the server. -// -// If there is a stale Response, then any validators it contains will be set on the new request -// to give the server a chance to respond with NotModified. If this happens, then the cached Response -// will be returned. -func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) { - cacheKey := cacheKey(req) - cacheable := (req.Method == "GET" || req.Method == "HEAD") && req.Header.Get("range") == "" - var cachedResp *http.Response - if cacheable { - cachedResp, err = CachedResponse(t.Cache, req) - } else { - // Need to invalidate an existing value - t.Cache.Delete(cacheKey) - } - - transport := t.Transport - if transport == nil { - transport = http.DefaultTransport - } - - if cacheable && cachedResp != nil && err == nil { - if t.MarkCachedResponses { - cachedResp.Header.Set(XFromCache, "1") - } - - if varyMatches(cachedResp, req) { - // Can only use cached value if the new request doesn't Vary significantly - freshness := getFreshness(cachedResp.Header, req.Header) - if freshness == fresh { - return cachedResp, nil - } - - if freshness == stale { - var req2 *http.Request - // Add validators if caller hasn't already done so - etag := cachedResp.Header.Get("etag") - if etag != "" && req.Header.Get("etag") == "" { - req2 = cloneRequest(req) - req2.Header.Set("if-none-match", etag) - } - lastModified := cachedResp.Header.Get("last-modified") - if lastModified != "" && req.Header.Get("last-modified") == "" { - if req2 == nil { - req2 = cloneRequest(req) - } - req2.Header.Set("if-modified-since", lastModified) - } - if req2 != nil { - req = req2 - } - } - } - - resp, err = transport.RoundTrip(req) - if err == nil && req.Method == "GET" && resp.StatusCode == http.StatusNotModified { - // Replace the 304 response with the one from cache, but update with some new headers - endToEndHeaders := getEndToEndHeaders(resp.Header) - for _, header := range endToEndHeaders { - cachedResp.Header[header] = resp.Header[header] - } - resp = cachedResp - } else if (err != nil || (cachedResp != nil && resp.StatusCode >= 500)) && - req.Method == "GET" && canStaleOnError(cachedResp.Header, req.Header) { - // In case of transport failure and stale-if-error activated, returns cached content - // when available - return cachedResp, nil - } else { - if err != nil || resp.StatusCode != http.StatusOK { - t.Cache.Delete(cacheKey) - } - if err != nil { - return nil, err - } - } - } else { - reqCacheControl := parseCacheControl(req.Header) - if _, ok := reqCacheControl["only-if-cached"]; ok { - resp = newGatewayTimeoutResponse(req) - } else { - resp, err = transport.RoundTrip(req) - if err != nil { - return nil, err - } - } - } - - if cacheable && canStore(parseCacheControl(req.Header), parseCacheControl(resp.Header)) { - for _, varyKey := range headerAllCommaSepValues(resp.Header, "vary") { - varyKey = http.CanonicalHeaderKey(varyKey) - fakeHeader := "X-Varied-" + varyKey - reqValue := req.Header.Get(varyKey) - if reqValue != "" { - resp.Header.Set(fakeHeader, reqValue) - } - } - switch req.Method { - case "GET": - // Delay caching until EOF is reached. - resp.Body = &cachingReadCloser{ - R: resp.Body, - OnEOF: func(r io.Reader) { - resp := *resp - resp.Body = ioutil.NopCloser(r) - respBytes, err := httputil.DumpResponse(&resp, true) - if err == nil { - t.Cache.Set(cacheKey, respBytes) - } - }, - } - default: - respBytes, err := httputil.DumpResponse(resp, true) - if err == nil { - t.Cache.Set(cacheKey, respBytes) - } - } - } else { - t.Cache.Delete(cacheKey) - } - return resp, nil -} - -// ErrNoDateHeader indicates that the HTTP headers contained no Date header. -var ErrNoDateHeader = errors.New("no Date header") - -// Date parses and returns the value of the Date header. -func Date(respHeaders http.Header) (date time.Time, err error) { - dateHeader := respHeaders.Get("date") - if dateHeader == "" { - err = ErrNoDateHeader - return - } - - return time.Parse(time.RFC1123, dateHeader) -} - -type realClock struct{} - -func (c *realClock) since(d time.Time) time.Duration { - return time.Since(d) -} - -type timer interface { - since(d time.Time) time.Duration -} - -var clock timer = &realClock{} - -// getFreshness will return one of fresh/stale/transparent based on the cache-control -// values of the request and the response -// -// fresh indicates the response can be returned -// stale indicates that the response needs validating before it is returned -// transparent indicates the response should not be used to fulfil the request -// -// Because this is only a private cache, 'public' and 'private' in cache-control aren't -// signficant. Similarly, smax-age isn't used. -func getFreshness(respHeaders, reqHeaders http.Header) (freshness int) { - respCacheControl := parseCacheControl(respHeaders) - reqCacheControl := parseCacheControl(reqHeaders) - if _, ok := reqCacheControl["no-cache"]; ok { - return transparent - } - if _, ok := respCacheControl["no-cache"]; ok { - return stale - } - if _, ok := reqCacheControl["only-if-cached"]; ok { - return fresh - } - - date, err := Date(respHeaders) - if err != nil { - return stale - } - currentAge := clock.since(date) - - var lifetime time.Duration - var zeroDuration time.Duration - - // If a response includes both an Expires header and a max-age directive, - // the max-age directive overrides the Expires header, even if the Expires header is more restrictive. - if maxAge, ok := respCacheControl["max-age"]; ok { - lifetime, err = time.ParseDuration(maxAge + "s") - if err != nil { - lifetime = zeroDuration - } - } else { - expiresHeader := respHeaders.Get("Expires") - if expiresHeader != "" { - expires, err := time.Parse(time.RFC1123, expiresHeader) - if err != nil { - lifetime = zeroDuration - } else { - lifetime = expires.Sub(date) - } - } - } - - if maxAge, ok := reqCacheControl["max-age"]; ok { - // the client is willing to accept a response whose age is no greater than the specified time in seconds - lifetime, err = time.ParseDuration(maxAge + "s") - if err != nil { - lifetime = zeroDuration - } - } - if minfresh, ok := reqCacheControl["min-fresh"]; ok { - // the client wants a response that will still be fresh for at least the specified number of seconds. - minfreshDuration, err := time.ParseDuration(minfresh + "s") - if err == nil { - currentAge = time.Duration(currentAge + minfreshDuration) - } - } - - if maxstale, ok := reqCacheControl["max-stale"]; ok { - // Indicates that the client is willing to accept a response that has exceeded its expiration time. - // If max-stale is assigned a value, then the client is willing to accept a response that has exceeded - // its expiration time by no more than the specified number of seconds. - // If no value is assigned to max-stale, then the client is willing to accept a stale response of any age. - // - // Responses served only because of a max-stale value are supposed to have a Warning header added to them, - // but that seems like a hassle, and is it actually useful? If so, then there needs to be a different - // return-value available here. - if maxstale == "" { - return fresh - } - maxstaleDuration, err := time.ParseDuration(maxstale + "s") - if err == nil { - currentAge = time.Duration(currentAge - maxstaleDuration) - } - } - - if lifetime > currentAge { - return fresh - } - - return stale -} - -// Returns true if either the request or the response includes the stale-if-error -// cache control extension: https://tools.ietf.org/html/rfc5861 -func canStaleOnError(respHeaders, reqHeaders http.Header) bool { - respCacheControl := parseCacheControl(respHeaders) - reqCacheControl := parseCacheControl(reqHeaders) - - var err error - lifetime := time.Duration(-1) - - if staleMaxAge, ok := respCacheControl["stale-if-error"]; ok { - if staleMaxAge != "" { - lifetime, err = time.ParseDuration(staleMaxAge + "s") - if err != nil { - return false - } - } else { - return true - } - } - if staleMaxAge, ok := reqCacheControl["stale-if-error"]; ok { - if staleMaxAge != "" { - lifetime, err = time.ParseDuration(staleMaxAge + "s") - if err != nil { - return false - } - } else { - return true - } - } - - if lifetime >= 0 { - date, err := Date(respHeaders) - if err != nil { - return false - } - currentAge := clock.since(date) - if lifetime > currentAge { - return true - } - } - - return false -} - -func getEndToEndHeaders(respHeaders http.Header) []string { - // These headers are always hop-by-hop - hopByHopHeaders := map[string]struct{}{ - "Connection": {}, - "Keep-Alive": {}, - "Proxy-Authenticate": {}, - "Proxy-Authorization": {}, - "Te": {}, - "Trailers": {}, - "Transfer-Encoding": {}, - "Upgrade": {}, - } - - for _, extra := range strings.Split(respHeaders.Get("connection"), ",") { - // any header listed in connection, if present, is also considered hop-by-hop - if strings.Trim(extra, " ") != "" { - hopByHopHeaders[http.CanonicalHeaderKey(extra)] = struct{}{} - } - } - endToEndHeaders := []string{} - for respHeader := range respHeaders { - if _, ok := hopByHopHeaders[respHeader]; !ok { - endToEndHeaders = append(endToEndHeaders, respHeader) - } - } - return endToEndHeaders -} - -func canStore(reqCacheControl, respCacheControl cacheControl) (canStore bool) { - if _, ok := respCacheControl["no-store"]; ok { - return false - } - if _, ok := reqCacheControl["no-store"]; ok { - return false - } - return true -} - -func newGatewayTimeoutResponse(req *http.Request) *http.Response { - var braw bytes.Buffer - braw.WriteString("HTTP/1.1 504 Gateway Timeout\r\n\r\n") - resp, err := http.ReadResponse(bufio.NewReader(&braw), req) - if err != nil { - panic(err) - } - return resp -} - -// cloneRequest returns a clone of the provided *http.Request. -// The clone is a shallow copy of the struct and its Header map. -// (This function copyright goauth2 authors: https://code.google.com/p/goauth2) -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) - for k, s := range r.Header { - r2.Header[k] = s - } - return r2 -} - -type cacheControl map[string]string - -func parseCacheControl(headers http.Header) cacheControl { - cc := cacheControl{} - ccHeader := headers.Get("Cache-Control") - for _, part := range strings.Split(ccHeader, ",") { - part = strings.Trim(part, " ") - if part == "" { - continue - } - if strings.ContainsRune(part, '=') { - keyval := strings.Split(part, "=") - cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") - } else { - cc[part] = "" - } - } - return cc -} - -// headerAllCommaSepValues returns all comma-separated values (each -// with whitespace trimmed) for header name in headers. According to -// Section 4.2 of the HTTP/1.1 spec -// (http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2), -// values from multiple occurrences of a header should be concatenated, if -// the header's value is a comma-separated list. -func headerAllCommaSepValues(headers http.Header, name string) []string { - var vals []string - for _, val := range headers[http.CanonicalHeaderKey(name)] { - fields := strings.Split(val, ",") - for i, f := range fields { - fields[i] = strings.TrimSpace(f) - } - vals = append(vals, fields...) - } - return vals -} - -// cachingReadCloser is a wrapper around ReadCloser R that calls OnEOF -// handler with a full copy of the content read from R when EOF is -// reached. -type cachingReadCloser struct { - // Underlying ReadCloser. - R io.ReadCloser - // OnEOF is called with a copy of the content of R when EOF is reached. - OnEOF func(io.Reader) - - buf bytes.Buffer // buf stores a copy of the content of R. -} - -// Read reads the next len(p) bytes from R or until R is drained. The -// return value n is the number of bytes read. If R has no data to -// return, err is io.EOF and OnEOF is called with a full copy of what -// has been read so far. -func (r *cachingReadCloser) Read(p []byte) (n int, err error) { - n, err = r.R.Read(p) - r.buf.Write(p[:n]) - if err == io.EOF { - r.OnEOF(bytes.NewReader(r.buf.Bytes())) - } - return n, err -} - -func (r *cachingReadCloser) Close() error { - return r.R.Close() -} - -// NewMemoryCacheTransport returns a new Transport using the in-memory cache implementation -func NewMemoryCacheTransport() *Transport { - c := NewMemoryCache() - t := NewTransport(c) - return t -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/LICENSE b/vendor/github.com/hashicorp/terraform-provider-kubernetes/LICENSE deleted file mode 100644 index a612ad9813b..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_all_namespaces.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_all_namespaces.go deleted file mode 100644 index 3b5ee8d6df6..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_all_namespaces.go +++ /dev/null @@ -1,61 +0,0 @@ -package kubernetes - -import ( - "context" - "crypto/sha256" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func dataSourceKubernetesAllNamespaces() *schema.Resource { - return &schema.Resource{ - Read: dataSourceKubernetesAllNamespacesRead, - Schema: map[string]*schema.Schema{ - "namespaces": { - Type: schema.TypeList, - Description: "List of all namespaces in a cluster.", - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - } -} - -func dataSourceKubernetesAllNamespacesRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - log.Printf("[INFO] Listing namespaces") - nsRaw, err := conn.CoreV1().Namespaces().List(ctx, metav1.ListOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - namespaces := make([]string, len(nsRaw.Items)) - for i, v := range nsRaw.Items { - namespaces[i] = v.Name - } - log.Printf("[INFO] Received namespaces: %#v", namespaces) - err = d.Set("namespaces", namespaces) - if err != nil { - return err - } - idsum := sha256.New() - for _, v := range namespaces { - _, err := idsum.Write([]byte(v)) - if err != nil { - return err - } - } - id := fmt.Sprintf("%x", idsum.Sum(nil)) - d.SetId(id) - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_config_map.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_config_map.go deleted file mode 100644 index 2dcf81bc60e..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_config_map.go +++ /dev/null @@ -1,36 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func dataSourceKubernetesConfigMap() *schema.Resource { - return &schema.Resource{ - Read: dataSourceKubernetesConfigMapRead, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("config_map", false), - "data": { - Type: schema.TypeMap, - Description: "A map of the config map data.", - Computed: true, - }, - "binary_data": { - Type: schema.TypeMap, - Description: "A map of the config map binary data.", - Computed: true, - }, - }, - } -} - -func dataSourceKubernetesConfigMapRead(d *schema.ResourceData, meta interface{}) error { - om := meta_v1.ObjectMeta{ - Namespace: d.Get("metadata.0.namespace").(string), - Name: d.Get("metadata.0.name").(string), - } - d.SetId(buildId(om)) - - return resourceKubernetesConfigMapRead(d, meta) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_ingress.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_ingress.go deleted file mode 100644 index 1b8d0e42707..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_ingress.go +++ /dev/null @@ -1,124 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - networking "k8s.io/api/networking/v1beta1" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func dataSourceKubernetesIngress() *schema.Resource { - docHTTPIngressPath := networking.HTTPIngressPath{}.SwaggerDoc() - docHTTPIngressRuleValue := networking.HTTPIngressPath{}.SwaggerDoc() - docIngress := networking.Ingress{}.SwaggerDoc() - docIngressTLS := networking.IngressTLS{}.SwaggerDoc() - docIngressRule := networking.IngressRule{}.SwaggerDoc() - docIngressSpec := networking.IngressSpec{}.SwaggerDoc() - - return &schema.Resource{ - Read: dataSourceKubernetesIngressRead, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("ingress", false), - "spec": { - Type: schema.TypeList, - Description: docIngress["spec"], - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "backend": backendSpecFields(defaultBackendDescription), - // FIXME: this field is inconsistent with the k8s API 'rules' - "rule": { - Type: schema.TypeList, - Description: docIngressSpec["rules"], - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "host": { - Type: schema.TypeString, - Description: docIngressRule["host"], - Computed: true, - }, - "http": { - Type: schema.TypeList, - Computed: true, - MaxItems: 1, - Description: docIngressRule[""], - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - // FIXME: this field is inconsistent with the k8s API 'paths' - "path": { - Type: schema.TypeList, - Computed: true, - Description: docHTTPIngressRuleValue["paths"], - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "path": { - Type: schema.TypeString, - Description: docHTTPIngressPath["path"], - Computed: true, - }, - "backend": backendSpecFields(ruleBackedDescription), - }, - }, - }, - }, - }, - }, - }, - }, - }, - "tls": { - Type: schema.TypeList, - Description: docIngressSpec["tls"], - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "hosts": { - Type: schema.TypeList, - Description: docIngressTLS["hosts"], - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "secret_name": { - Type: schema.TypeString, - Description: docIngressTLS["secretName"], - Computed: true, - }, - }, - }, - }, - }, - }, - }, - "load_balancer_ingress": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ip": { - Type: schema.TypeString, - Computed: true, - }, - "hostname": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - }, - } -} - -func dataSourceKubernetesIngressRead(d *schema.ResourceData, meta interface{}) error { - metadata := expandMetadata(d.Get("metadata").([]interface{})) - - om := meta_v1.ObjectMeta{ - Namespace: metadata.Namespace, - Name: metadata.Name, - } - d.SetId(buildId(om)) - - return resourceKubernetesIngressRead(d, meta) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_namespace.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_namespace.go deleted file mode 100644 index c79697e8cfc..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_namespace.go +++ /dev/null @@ -1,77 +0,0 @@ -package kubernetes - -import ( - "context" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - v1 "k8s.io/api/core/v1" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "log" -) - -func dataSourceKubernetesNamespace() *schema.Resource { - return &schema.Resource{ - Read: dataSourceKubernetesNamespaceRead, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("namespace", false), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the behavior of the Namespace.", - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "finalizers": { - Type: schema.TypeList, - Description: "Finalizers is an opaque list of values that must be empty to permanently remove object from storage.", - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - }, - }, - }, - } -} - -func dataSourceKubernetesNamespaceRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - d.SetId(metadata.Name) - - namespace, err := conn.CoreV1().Namespaces().Get(ctx, metadata.Name, meta_v1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received namespace: %#v", namespace) - err = d.Set("metadata", flattenMetadata(namespace.ObjectMeta, d)) - if err != nil { - return err - } - err = d.Set("spec", flattenNamespaceSpec(&namespace.Spec)) - if err != nil { - return err - } - return nil -} - -func flattenNamespaceSpec(in *v1.NamespaceSpec) []interface{} { - if in == nil || len(in.Finalizers) == 0 { - return []interface{}{} - } - spec := make(map[string]interface{}) - fin := make([]string, len(in.Finalizers)) - for i, f := range in.Finalizers { - fin[i] = string(f) - } - spec["finalizers"] = fin - return []interface{}{spec} -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_persistent_volume_claim.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_persistent_volume_claim.go deleted file mode 100644 index 0a7a0eca4ed..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_persistent_volume_claim.go +++ /dev/null @@ -1,94 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func dataSourceKubernetesPersistentVolumeClaim() *schema.Resource { - return &schema.Resource{ - Read: dataSourceKubernetesPersistentVolumeClaimRead, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("persistent volume claim", true), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the desired characteristics of a volume requested by a pod author. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#persistentvolumeclaims", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "access_modes": { - Type: schema.TypeSet, - Description: "A set of the desired access modes the volume should have. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#access-modes-1", - Computed: true, - ForceNew: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - Set: schema.HashString, - }, - "resources": { - Type: schema.TypeList, - Description: "A list of the minimum resources the volume should have. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#resources", - Computed: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "limits": { - Type: schema.TypeMap, - Description: "Map describing the maximum amount of compute resources allowed. More info: http://kubernetes.io/docs/user-guide/compute-resources/", - Optional: true, - ForceNew: true, - }, - "requests": { - Type: schema.TypeMap, - Description: "Map describing the minimum amount of compute resources required. If this is omitted for a container, it defaults to `limits` if that is explicitly specified, otherwise to an implementation-defined value. More info: http://kubernetes.io/docs/user-guide/compute-resources/", - Optional: true, - ForceNew: true, - }, - }, - }, - }, - "selector": { - Type: schema.TypeList, - Description: "A label query over volumes to consider for binding.", - Optional: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(false), - }, - }, - "volume_name": { - Type: schema.TypeString, - Description: "The binding reference to the PersistentVolume backing this claim.", - Optional: true, - ForceNew: true, - Computed: true, - }, - "storage_class_name": { - Type: schema.TypeString, - Description: "Name of the storage class requested by the claim", - Optional: true, - Computed: true, - ForceNew: true, - }, - }, - }, - }, - }, - } -} - -func dataSourceKubernetesPersistentVolumeClaimRead(d *schema.ResourceData, meta interface{}) error { - metadata := expandMetadata(d.Get("metadata").([]interface{})) - - om := meta_v1.ObjectMeta{ - Namespace: metadata.Namespace, - Name: metadata.Name, - } - d.SetId(buildId(om)) - - return resourceKubernetesPersistentVolumeClaimRead(d, meta) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_pod.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_pod.go deleted file mode 100644 index 67125cfd224..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_pod.go +++ /dev/null @@ -1,80 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "log" -) - -func dataSourceKubernetesPod() *schema.Resource { - podSpecFields := podSpecFields(false, false, false) - // Setting this default to false prevents a perpetual diff caused by volume_mounts - // being mutated on the server side as Kubernetes automatically adds a mount - // for the service account token - return &schema.Resource{ - Read: dataSourceKubernetesPodRead, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("pod", true), - "spec": { - Type: schema.TypeList, - Description: "Specification of the desired behavior of the pod.", - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: podSpecFields, - }, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - }, - } -} - -func dataSourceKubernetesPodRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - - om := meta_v1.ObjectMeta{ - Namespace: metadata.Namespace, - Name: metadata.Name, - } - d.SetId(buildId(om)) - - log.Printf("[INFO] Reading pod %s", metadata.Name) - pod, err := conn.CoreV1().Pods(metadata.Namespace).Get(ctx, metadata.Name, meta_v1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received pod: %#v", pod) - - err = d.Set("metadata", flattenMetadata(pod.ObjectMeta, d)) - if err != nil { - return err - } - - podSpec, err := flattenPodSpec(pod.Spec) - if err != nil { - return err - } - - err = d.Set("spec", podSpec) - if err != nil { - return err - } - statusPhase := fmt.Sprintf("%v", pod.Status.Phase) - d.Set("status", statusPhase) - - return nil - -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_secret.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_secret.go deleted file mode 100644 index ead47c5592f..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_secret.go +++ /dev/null @@ -1,37 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func dataSourceKubernetesSecret() *schema.Resource { - return &schema.Resource{ - Read: dataSourceKubernetesSecretRead, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("secret", false), - "data": { - Type: schema.TypeMap, - Description: "A map of the secret data.", - Computed: true, - Sensitive: true, - }, - "type": { - Type: schema.TypeString, - Description: "Type of secret", - Computed: true, - }, - }, - } -} - -func dataSourceKubernetesSecretRead(d *schema.ResourceData, meta interface{}) error { - om := meta_v1.ObjectMeta{ - Namespace: d.Get("metadata.0.namespace").(string), - Name: d.Get("metadata.0.name").(string), - } - d.SetId(buildId(om)) - - return resourceKubernetesSecretRead(d, meta) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_service.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_service.go deleted file mode 100644 index 6f02729af1e..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_service.go +++ /dev/null @@ -1,150 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func dataSourceKubernetesService() *schema.Resource { - return &schema.Resource{ - Read: dataSourceKubernetesServiceRead, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("service", false), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the behavior of a service. https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - MaxItems: 1, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cluster_ip": { - Type: schema.TypeString, - Description: "The IP address of the service. It is usually assigned randomly by the master. If an address is specified manually and is not in use by others, it will be allocated to the service; otherwise, creation of the service will fail. `None` can be specified for headless services when proxying is not required. Ignored if type is `ExternalName`. More info: http://kubernetes.io/docs/user-guide/services#virtual-ips-and-service-proxies", - Computed: true, - }, - "external_ips": { - Type: schema.TypeSet, - Description: "A list of IP addresses for which nodes in the cluster will also accept traffic for this service. These IPs are not managed by Kubernetes. The user is responsible for ensuring that traffic arrives at a node with this IP. A common example is external load-balancers that are not part of the Kubernetes system.", - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - Computed: true, - }, - "external_name": { - Type: schema.TypeString, - Description: "The external reference that kubedns or equivalent will return as a CNAME record for this service. No proxying will be involved. Must be a valid DNS name and requires `type` to be `ExternalName`.", - Computed: true, - }, - "external_traffic_policy": { - Type: schema.TypeString, - Description: "Denotes if this Service desires to route external traffic to node-local or cluster-wide endpoints. `Local` preserves the client source IP and avoids a second hop for LoadBalancer and Nodeport type services, but risks potentially imbalanced traffic spreading. `Cluster` obscures the client source IP and may cause a second hop to another node, but should have good overall load-spreading. More info: https://kubernetes.io/docs/tutorials/services/source-ip/", - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice([]string{"Local", "Cluster"}, false), - }, - "load_balancer_ip": { - Type: schema.TypeString, - Description: "Only applies to `type = LoadBalancer`. LoadBalancer will get created with the IP specified in this field. This feature depends on whether the underlying cloud-provider supports specifying this field when a load balancer is created. This field will be ignored if the cloud-provider does not support the feature.", - Computed: true, - }, - "load_balancer_source_ranges": { - Type: schema.TypeSet, - Description: "If specified and supported by the platform, this will restrict traffic through the cloud-provider load-balancer will be restricted to the specified client IPs. This field will be ignored if the cloud-provider does not support the feature. More info: http://kubernetes.io/docs/user-guide/services-firewalls", - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - Computed: true, - }, - "port": { - Type: schema.TypeList, - Description: "The list of ports that are exposed by this service. More info: http://kubernetes.io/docs/user-guide/services#virtual-ips-and-service-proxies", - MinItems: 1, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "The name of this port within the service. All ports within the service must have unique names. Optional if only one ServicePort is defined on this service.", - Computed: true, - }, - "node_port": { - Type: schema.TypeInt, - Description: "The port on each node on which this service is exposed when `type` is `NodePort` or `LoadBalancer`. Usually assigned by the system. If specified, it will be allocated to the service if unused or else creation of the service will fail. Default is to auto-allocate a port if the `type` of this service requires one. More info: http://kubernetes.io/docs/user-guide/services#type--nodeport", - Computed: true, - }, - "port": { - Type: schema.TypeInt, - Description: "The port that will be exposed by this service.", - Computed: true, - }, - "protocol": { - Type: schema.TypeString, - Description: "The IP protocol for this port. Supports `TCP` and `UDP`. Default is `TCP`.", - Computed: true, - }, - "target_port": { - Type: schema.TypeString, - Description: "Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. This field is ignored for services with `cluster_ip = \"None\"`. More info: http://kubernetes.io/docs/user-guide/services#defining-a-service", - Computed: true, - }, - }, - }, - }, - "publish_not_ready_addresses": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "When set to true, indicates that DNS implementations must publish the `notReadyAddresses` of subsets for the Endpoints associated with the Service. The default value is `false`. The primary use case for setting this field is to use a StatefulSet's Headless Service to propagate `SRV` records for its Pods without respect to their readiness for purpose of peer discovery.", - }, - "selector": { - Type: schema.TypeMap, - Description: "Route service traffic to pods with label keys and values matching this selector. Only applies to types `ClusterIP`, `NodePort`, and `LoadBalancer`. More info: http://kubernetes.io/docs/user-guide/services#overview", - Computed: true, - }, - "session_affinity": { - Type: schema.TypeString, - Description: "Used to maintain session affinity. Supports `ClientIP` and `None`. Defaults to `None`. More info: http://kubernetes.io/docs/user-guide/services#virtual-ips-and-service-proxies", - Computed: true, - }, - "type": { - Type: schema.TypeString, - Description: "Determines how the service is exposed. Defaults to `ClusterIP`. Valid options are `ExternalName`, `ClusterIP`, `NodePort`, and `LoadBalancer`. `ExternalName` maps to the specified `external_name`. More info: http://kubernetes.io/docs/user-guide/services#overview", - Computed: true, - }, - "health_check_node_port": { - Type: schema.TypeInt, - Description: "Specifies the Healthcheck NodePort for the service. Only effects when type is set to `LoadBalancer` and external_traffic_policy is set to `Local`.", - Computed: true, - }, - }, - }, - }, - "load_balancer_ingress": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ip": { - Type: schema.TypeString, - Computed: true, - }, - "hostname": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - }, - } -} - -func dataSourceKubernetesServiceRead(d *schema.ResourceData, meta interface{}) error { - om := meta_v1.ObjectMeta{ - Namespace: d.Get("metadata.0.namespace").(string), - Name: d.Get("metadata.0.name").(string), - } - d.SetId(buildId(om)) - - return resourceKubernetesServiceRead(d, meta) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_service_account.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_service_account.go deleted file mode 100644 index 44b20728b95..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_service_account.go +++ /dev/null @@ -1,83 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func dataSourceKubernetesServiceAccount() *schema.Resource { - return &schema.Resource{ - Read: dataSourceKubernetesServiceAccountRead, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("service account", false), - "image_pull_secret": { - Type: schema.TypeList, - Description: "A list of references to secrets in the same namespace to use for pulling any images in pods that reference this Service Account. More info: http://kubernetes.io/docs/user-guide/secrets#manually-specifying-an-imagepullsecret", - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - Computed: true, - }, - }, - }, - }, - "secret": { - Type: schema.TypeList, - Description: "A list of secrets allowed to be used by pods running using this Service Account. More info: http://kubernetes.io/docs/user-guide/secrets", - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - Computed: true, - }, - }, - }, - }, - "automount_service_account_token": { - Type: schema.TypeBool, - Description: "True to enable automatic mounting of the service account token", - Computed: true, - }, - "default_secret_name": { - Type: schema.TypeString, - Computed: true, - }, - }, - } -} - -func dataSourceKubernetesServiceAccountRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - sa, err := conn.CoreV1().ServiceAccounts(metadata.Namespace).Get(ctx, metadata.Name, metav1.GetOptions{}) - if err != nil { - return fmt.Errorf("Unable to fetch service account from Kubernetes: %s", err) - } - - defaultSecret, err := findDefaultServiceAccount(ctx, sa, conn) - if err != nil { - return fmt.Errorf("Failed to discover the default service account token: %s", err) - } - - err = d.Set("default_secret_name", defaultSecret) - if err != nil { - return fmt.Errorf("Unable to set default_secret_name: %s", err) - } - - d.SetId(buildId(sa.ObjectMeta)) - - return resourceKubernetesServiceAccountRead(d, meta) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_storage_class.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_storage_class.go deleted file mode 100644 index 159a96f2c68..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/data_source_kubernetes_storage_class.go +++ /dev/null @@ -1,47 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -func dataSourceKubernetesStorageClass() *schema.Resource { - return &schema.Resource{ - Read: dataSourceKubernetesStorageClassRead, - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("storage class", false), - "parameters": { - Type: schema.TypeMap, - Description: "The parameters for the provisioner that should create volumes of this storage class", - Computed: true, - }, - "storage_provisioner": { - Type: schema.TypeString, - Description: "Indicates the type of the provisioner", - Computed: true, - }, - "reclaim_policy": { - Type: schema.TypeString, - Description: "Indicates the type of the reclaim policy", - Computed: true, - }, - "allow_volume_expansion": { - Type: schema.TypeBool, - Description: "Indicates whether the storage class allow volume expand", - Computed: true, - }, - "mount_options": { - Type: schema.TypeSet, - Description: "Persistent Volumes that are dynamically created by a storage class will have the mount options specified", - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - Computed: true, - }, - }, - } -} - -func dataSourceKubernetesStorageClassRead(d *schema.ResourceData, meta interface{}) error { - name := d.Get("metadata.0.name").(string) - d.SetId(name) - return resourceKubernetesStorageClassRead(d, meta) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/diff_supress_funcs.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/diff_supress_funcs.go deleted file mode 100644 index 09b2a1a208b..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/diff_supress_funcs.go +++ /dev/null @@ -1,18 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "k8s.io/apimachinery/pkg/api/resource" -) - -func suppressEquivalentResourceQuantity(k, old, new string, d *schema.ResourceData) bool { - oldQ, err := resource.ParseQuantity(old) - if err != nil { - return false - } - newQ, err := resource.ParseQuantity(new) - if err != nil { - return false - } - return oldQ.Cmp(newQ) == 0 -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/event_helpers.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/event_helpers.go deleted file mode 100644 index 762461bae58..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/event_helpers.go +++ /dev/null @@ -1,74 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "sort" - - api "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/fields" - "k8s.io/client-go/kubernetes" -) - -func getLastWarningsForObject(ctx context.Context, conn *kubernetes.Clientset, metadata metav1.ObjectMeta, kind string, limit int) ([]api.Event, error) { - m := map[string]string{ - "involvedObject.name": metadata.Name, - "involvedObject.kind": kind, - } - if metadata.Namespace != "" { - m["involvedObject.namespace"] = metadata.Namespace - } - - fs := fields.Set(m).String() - log.Printf("[DEBUG] Looking up events via this selector: %q", fs) - out, err := conn.CoreV1().Events(metadata.Namespace).List(ctx, metav1.ListOptions{ - FieldSelector: fs, - }) - if err != nil { - return nil, err - } - - // It would be better to sort & filter on the server-side - // but API doesn't seem to support it - var warnings []api.Event - - // Bring latest events to the top, for easy access - sort.Slice(out.Items, func(i, j int) bool { - return out.Items[i].LastTimestamp.After(out.Items[j].LastTimestamp.Time) - }) - - log.Printf("[DEBUG] Received %d events for %s/%s (%s)", - len(out.Items), metadata.Namespace, metadata.Name, kind) - - warnCount := 0 - uniqueWarnings := make(map[string]api.Event, 0) - for _, e := range out.Items { - if warnCount >= limit { - break - } - - if e.Type == api.EventTypeWarning { - _, found := uniqueWarnings[e.Message] - if found { - continue - } - warnings = append(warnings, e) - uniqueWarnings[e.Message] = e - warnCount++ - } - } - - return warnings, nil -} - -func stringifyEvents(events []api.Event) string { - var output string - for _, e := range events { - output += fmt.Sprintf("\n * %s (%s): %s: %s", - e.InvolvedObject.Name, e.InvolvedObject.Kind, - e.Reason, e.Message) - } - return output -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/options_helpers.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/options_helpers.go deleted file mode 100644 index 7425a298def..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/options_helpers.go +++ /dev/null @@ -1,10 +0,0 @@ -package kubernetes - -import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - -var ( - cascadeDeletePolicy = metav1.DeletePropagationForeground - deleteOptions = metav1.DeleteOptions{ - PropagationPolicy: &cascadeDeletePolicy, - } -) diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/patch_operations.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/patch_operations.go deleted file mode 100644 index 67f2f38652a..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/patch_operations.go +++ /dev/null @@ -1,154 +0,0 @@ -package kubernetes - -import ( - "encoding/json" - "reflect" - "sort" - "strings" -) - -func diffStringMap(pathPrefix string, oldV, newV map[string]interface{}) PatchOperations { - ops := make([]PatchOperation, 0, 0) - - pathPrefix = strings.TrimRight(pathPrefix, "/") - - // If old value was empty, just create the object - if len(oldV) == 0 { - ops = append(ops, &AddOperation{ - Path: pathPrefix, - Value: newV, - }) - return ops - } - - // This is suboptimal for adding whole new map from scratch - // or deleting the whole map, but it's actually intention. - // There may be some other map items managed outside of TF - // and we don't want to touch these. - - for k := range oldV { - if _, ok := newV[k]; ok { - continue - } - ops = append(ops, &RemoveOperation{ - Path: pathPrefix + "/" + escapeJsonPointer(k), - }) - } - - for k, v := range newV { - newValue := v.(string) - - if oldValue, ok := oldV[k].(string); ok { - if oldValue == newValue { - continue - } - - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/" + escapeJsonPointer(k), - Value: newValue, - }) - continue - } - - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/" + escapeJsonPointer(k), - Value: newValue, - }) - } - - return ops -} - -// escapeJsonPointer escapes string per RFC 6901 -// so it can be used as path in JSON patch operations -func escapeJsonPointer(path string) string { - path = strings.Replace(path, "~", "~0", -1) - path = strings.Replace(path, "/", "~1", -1) - return path -} - -type PatchOperations []PatchOperation - -func (po PatchOperations) MarshalJSON() ([]byte, error) { - var v []PatchOperation = po - return json.Marshal(v) -} - -func (po PatchOperations) Equal(ops []PatchOperation) bool { - var v []PatchOperation = po - - sort.Slice(v, sortByPathAsc(v)) - sort.Slice(ops, sortByPathAsc(ops)) - - return reflect.DeepEqual(v, ops) -} - -func sortByPathAsc(ops []PatchOperation) func(i, j int) bool { - return func(i, j int) bool { - return ops[i].GetPath() < ops[j].GetPath() - } -} - -type PatchOperation interface { - MarshalJSON() ([]byte, error) - GetPath() string -} - -type ReplaceOperation struct { - Path string `json:"path"` - Value interface{} `json:"value"` - Op string `json:"op"` -} - -func (o *ReplaceOperation) GetPath() string { - return o.Path -} - -func (o *ReplaceOperation) MarshalJSON() ([]byte, error) { - o.Op = "replace" - return json.Marshal(*o) -} - -func (o *ReplaceOperation) String() string { - b, _ := o.MarshalJSON() - return string(b) -} - -type AddOperation struct { - Path string `json:"path"` - Value interface{} `json:"value"` - Op string `json:"op"` -} - -func (o *AddOperation) GetPath() string { - return o.Path -} - -func (o *AddOperation) MarshalJSON() ([]byte, error) { - o.Op = "add" - return json.Marshal(*o) -} - -func (o *AddOperation) String() string { - b, _ := o.MarshalJSON() - return string(b) -} - -type RemoveOperation struct { - Path string `json:"path"` - Op string `json:"op"` -} - -func (o *RemoveOperation) GetPath() string { - return o.Path -} - -func (o *RemoveOperation) MarshalJSON() ([]byte, error) { - o.Op = "remove" - return json.Marshal(*o) -} - -func (o *RemoveOperation) String() string { - b, _ := o.MarshalJSON() - return string(b) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/provider.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/provider.go deleted file mode 100644 index f804be1687f..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/provider.go +++ /dev/null @@ -1,415 +0,0 @@ -package kubernetes - -import ( - "bytes" - "fmt" - "log" - "net/http" - - "github.com/hashicorp/terraform-plugin-sdk/helper/logging" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/mitchellh/go-homedir" - apimachineryschema "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/client-go/discovery" - "k8s.io/client-go/kubernetes" - _ "k8s.io/client-go/plugin/pkg/client/auth" - restclient "k8s.io/client-go/rest" - - "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - aggregator "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset" -) - -func Provider() terraform.ResourceProvider { - p := &schema.Provider{ - Schema: map[string]*schema.Schema{ - "host": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_HOST", ""), - Description: "The hostname (in form of URI) of Kubernetes master.", - }, - "username": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_USER", ""), - Description: "The username to use for HTTP basic authentication when accessing the Kubernetes master endpoint.", - }, - "password": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_PASSWORD", ""), - Description: "The password to use for HTTP basic authentication when accessing the Kubernetes master endpoint.", - }, - "insecure": { - Type: schema.TypeBool, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_INSECURE", false), - Description: "Whether server should be accessed without verifying the TLS certificate.", - }, - "client_certificate": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_CLIENT_CERT_DATA", ""), - Description: "PEM-encoded client certificate for TLS authentication.", - }, - "client_key": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_CLIENT_KEY_DATA", ""), - Description: "PEM-encoded client certificate key for TLS authentication.", - }, - "cluster_ca_certificate": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_CLUSTER_CA_CERT_DATA", ""), - Description: "PEM-encoded root certificates bundle for TLS authentication.", - }, - "config_path": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.MultiEnvDefaultFunc( - []string{ - "KUBE_CONFIG", - "KUBECONFIG", - }, - "~/.kube/config"), - Description: "Path to the kube config file, defaults to ~/.kube/config", - }, - "config_context": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_CTX", ""), - }, - "config_context_auth_info": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_CTX_AUTH_INFO", ""), - Description: "", - }, - "config_context_cluster": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_CTX_CLUSTER", ""), - Description: "", - }, - "token": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_TOKEN", ""), - Description: "Token to authenticate an service account", - }, - "load_config_file": { - Type: schema.TypeBool, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("KUBE_LOAD_CONFIG_FILE", true), - Description: "Load local kubeconfig.", - }, - "exec": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "api_version": { - Type: schema.TypeString, - Required: true, - }, - "command": { - Type: schema.TypeString, - Required: true, - }, - "env": { - Type: schema.TypeMap, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "args": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }, - }, - Description: "", - }, - }, - - DataSourcesMap: map[string]*schema.Resource{ - "kubernetes_all_namespaces": dataSourceKubernetesAllNamespaces(), - "kubernetes_config_map": dataSourceKubernetesConfigMap(), - "kubernetes_ingress": dataSourceKubernetesIngress(), - "kubernetes_namespace": dataSourceKubernetesNamespace(), - "kubernetes_secret": dataSourceKubernetesSecret(), - "kubernetes_service": dataSourceKubernetesService(), - "kubernetes_service_account": dataSourceKubernetesServiceAccount(), - "kubernetes_storage_class": dataSourceKubernetesStorageClass(), - "kubernetes_pod": dataSourceKubernetesPod(), - "kubernetes_persistent_volume_claim": dataSourceKubernetesPersistentVolumeClaim(), - }, - - ResourcesMap: map[string]*schema.Resource{ - "kubernetes_api_service": resourceKubernetesAPIService(), - "kubernetes_certificate_signing_request": resourceKubernetesCertificateSigningRequest(), - "kubernetes_cluster_role": resourceKubernetesClusterRole(), - "kubernetes_cluster_role_binding": resourceKubernetesClusterRoleBinding(), - "kubernetes_config_map": resourceKubernetesConfigMap(), - "kubernetes_cron_job": resourceKubernetesCronJob(), - "kubernetes_csi_driver": resourceKubernetesCSIDriver(), - "kubernetes_daemonset": resourceKubernetesDaemonSet(), - "kubernetes_default_service_account": resourceKubernetesDefaultServiceAccount(), - "kubernetes_deployment": resourceKubernetesDeployment(), - "kubernetes_endpoints": resourceKubernetesEndpoints(), - "kubernetes_horizontal_pod_autoscaler": resourceKubernetesHorizontalPodAutoscaler(), - "kubernetes_ingress": resourceKubernetesIngress(), - "kubernetes_job": resourceKubernetesJob(), - "kubernetes_limit_range": resourceKubernetesLimitRange(), - "kubernetes_namespace": resourceKubernetesNamespace(), - "kubernetes_network_policy": resourceKubernetesNetworkPolicy(), - "kubernetes_persistent_volume": resourceKubernetesPersistentVolume(), - "kubernetes_persistent_volume_claim": resourceKubernetesPersistentVolumeClaim(), - "kubernetes_pod": resourceKubernetesPod(), - "kubernetes_pod_disruption_budget": resourceKubernetesPodDisruptionBudget(), - "kubernetes_pod_security_policy": resourceKubernetesPodSecurityPolicy(), - "kubernetes_priority_class": resourceKubernetesPriorityClass(), - "kubernetes_replication_controller": resourceKubernetesReplicationController(), - "kubernetes_role_binding": resourceKubernetesRoleBinding(), - "kubernetes_resource_quota": resourceKubernetesResourceQuota(), - "kubernetes_role": resourceKubernetesRole(), - "kubernetes_secret": resourceKubernetesSecret(), - "kubernetes_service": resourceKubernetesService(), - "kubernetes_service_account": resourceKubernetesServiceAccount(), - "kubernetes_stateful_set": resourceKubernetesStatefulSet(), - "kubernetes_storage_class": resourceKubernetesStorageClass(), - "kubernetes_validating_webhook_configuration": resourceKubernetesValidatingWebhookConfiguration(), - "kubernetes_mutating_webhook_configuration": resourceKubernetesMutatingWebhookConfiguration(), - }, - } - - p.ConfigureFunc = func(d *schema.ResourceData) (interface{}, error) { - terraformVersion := p.TerraformVersion - if terraformVersion == "" { - // Terraform 0.12 introduced this field to the protocol - // We can therefore assume that if it's missing it's 0.10 or 0.11 - terraformVersion = "0.11+compatible" - } - return providerConfigure(d, terraformVersion) - } - - return p -} - -type KubeClientsets interface { - MainClientset() (*kubernetes.Clientset, error) - AggregatorClientset() (*aggregator.Clientset, error) -} - -type kubeClientsets struct { - config *restclient.Config - mainClientset *kubernetes.Clientset - aggregatorClientset *aggregator.Clientset -} - -func (k kubeClientsets) MainClientset() (*kubernetes.Clientset, error) { - if k.mainClientset != nil { - return k.mainClientset, nil - } - if k.config != nil { - kc, err := kubernetes.NewForConfig(k.config) - if err != nil { - return nil, fmt.Errorf("Failed to configure client: %s", err) - } - k.mainClientset = kc - } - return k.mainClientset, nil -} - -func (k kubeClientsets) AggregatorClientset() (*aggregator.Clientset, error) { - if k.aggregatorClientset != nil { - return k.aggregatorClientset, nil - } - if k.config != nil { - ac, err := aggregator.NewForConfig(k.config) - if err != nil { - return nil, fmt.Errorf("Failed to configure client: %s", err) - } - k.aggregatorClientset = ac - } - return k.aggregatorClientset, nil -} - -func providerConfigure(d *schema.ResourceData, terraformVersion string) (interface{}, error) { - - // Config initialization - cfg, err := initializeConfiguration(d) - if err != nil { - return nil, err - } - if cfg == nil { - // This is a TEMPORARY measure to work around https://github.com/hashicorp/terraform/issues/24055 - // IMPORTANT: this will NOT enable a workaround of issue: https://github.com/hashicorp/terraform/issues/4149 - // IMPORTANT: if the supplied configuration is incomplete or invalid - ///IMPORTANT: provider operations will fail or attempt to connect to localhost endpoints - cfg = &restclient.Config{} - } - - cfg.UserAgent = fmt.Sprintf("HashiCorp/1.0 Terraform/%s", terraformVersion) - - if logging.IsDebugOrHigher() { - log.Printf("[DEBUG] Enabling HTTP requests/responses tracing") - cfg.WrapTransport = func(rt http.RoundTripper) http.RoundTripper { - return logging.NewTransport("Kubernetes", rt) - } - } - - m := kubeClientsets{ - config: cfg, - mainClientset: nil, - aggregatorClientset: nil, - } - return m, nil -} - -func initializeConfiguration(d *schema.ResourceData) (*restclient.Config, error) { - overrides := &clientcmd.ConfigOverrides{} - loader := &clientcmd.ClientConfigLoadingRules{} - - if d.Get("load_config_file").(bool) { - log.Printf("[DEBUG] Trying to load configuration from file") - if configPath, ok := d.GetOk("config_path"); ok && configPath.(string) != "" { - path, err := homedir.Expand(configPath.(string)) - if err != nil { - return nil, err - } - log.Printf("[DEBUG] Configuration file is: %s", path) - loader.ExplicitPath = path - - ctxSuffix := "; default context" - - ctx, ctxOk := d.GetOk("config_context") - authInfo, authInfoOk := d.GetOk("config_context_auth_info") - cluster, clusterOk := d.GetOk("config_context_cluster") - if ctxOk || authInfoOk || clusterOk { - ctxSuffix = "; overriden context" - if ctxOk { - overrides.CurrentContext = ctx.(string) - ctxSuffix += fmt.Sprintf("; config ctx: %s", overrides.CurrentContext) - log.Printf("[DEBUG] Using custom current context: %q", overrides.CurrentContext) - } - - overrides.Context = clientcmdapi.Context{} - if authInfoOk { - overrides.Context.AuthInfo = authInfo.(string) - ctxSuffix += fmt.Sprintf("; auth_info: %s", overrides.Context.AuthInfo) - } - if clusterOk { - overrides.Context.Cluster = cluster.(string) - ctxSuffix += fmt.Sprintf("; cluster: %s", overrides.Context.Cluster) - } - log.Printf("[DEBUG] Using overidden context: %#v", overrides.Context) - } - } - } - - // Overriding with static configuration - if v, ok := d.GetOk("insecure"); ok { - overrides.ClusterInfo.InsecureSkipTLSVerify = v.(bool) - } - if v, ok := d.GetOk("cluster_ca_certificate"); ok { - overrides.ClusterInfo.CertificateAuthorityData = bytes.NewBufferString(v.(string)).Bytes() - } - if v, ok := d.GetOk("client_certificate"); ok { - overrides.AuthInfo.ClientCertificateData = bytes.NewBufferString(v.(string)).Bytes() - } - if v, ok := d.GetOk("host"); ok { - // Server has to be the complete address of the kubernetes cluster (scheme://hostname:port), not just the hostname, - // because `overrides` are processed too late to be taken into account by `defaultServerUrlFor()`. - // This basically replicates what defaultServerUrlFor() does with config but for overrides, - // see https://github.com/kubernetes/client-go/blob/v12.0.0/rest/url_utils.go#L85-L87 - hasCA := len(overrides.ClusterInfo.CertificateAuthorityData) != 0 - hasCert := len(overrides.AuthInfo.ClientCertificateData) != 0 - defaultTLS := hasCA || hasCert || overrides.ClusterInfo.InsecureSkipTLSVerify - host, _, err := restclient.DefaultServerURL(v.(string), "", apimachineryschema.GroupVersion{}, defaultTLS) - if err != nil { - return nil, fmt.Errorf("Failed to parse host: %s", err) - } - - overrides.ClusterInfo.Server = host.String() - } - if v, ok := d.GetOk("username"); ok { - overrides.AuthInfo.Username = v.(string) - } - if v, ok := d.GetOk("password"); ok { - overrides.AuthInfo.Password = v.(string) - } - if v, ok := d.GetOk("client_key"); ok { - overrides.AuthInfo.ClientKeyData = bytes.NewBufferString(v.(string)).Bytes() - } - if v, ok := d.GetOk("token"); ok { - overrides.AuthInfo.Token = v.(string) - } - - if v, ok := d.GetOk("exec"); ok { - exec := &clientcmdapi.ExecConfig{} - if spec, ok := v.([]interface{})[0].(map[string]interface{}); ok { - exec.APIVersion = spec["api_version"].(string) - exec.Command = spec["command"].(string) - exec.Args = expandStringSlice(spec["args"].([]interface{})) - for kk, vv := range spec["env"].(map[string]interface{}) { - exec.Env = append(exec.Env, clientcmdapi.ExecEnvVar{Name: kk, Value: vv.(string)}) - } - } else { - return nil, fmt.Errorf("Failed to parse exec") - } - overrides.AuthInfo.Exec = exec - } - - cc := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loader, overrides) - cfg, err := cc.ClientConfig() - if err != nil { - log.Printf("[WARN] Invalid provider configuration was supplied. Provider operations likely to fail: %v", err) - return nil, nil - } - - log.Printf("[INFO] Successfully initialized config") - return cfg, nil -} - -var useadmissionregistrationv1beta1 *bool - -func useAdmissionregistrationV1beta1(conn *kubernetes.Clientset) (bool, error) { - if useadmissionregistrationv1beta1 != nil { - return *useadmissionregistrationv1beta1, nil - } - - d := conn.Discovery() - - group := "admissionregistration.k8s.io" - - v1, err := apimachineryschema.ParseGroupVersion(fmt.Sprintf("%s/v1", group)) - if err != nil { - return false, err - } - - err = discovery.ServerSupportsVersion(d, v1) - if err == nil { - log.Printf("[INFO] Using %s/v1", group) - useadmissionregistrationv1beta1 = ptrToBool(false) - return false, nil - } - - v1beta1, err := apimachineryschema.ParseGroupVersion(fmt.Sprintf("%s/v1beta1", group)) - if err != nil { - return false, err - } - - err = discovery.ServerSupportsVersion(d, v1beta1) - if err != nil { - return false, err - } - - log.Printf("[INFO] Using %s/v1beta1", group) - useadmissionregistrationv1beta1 = ptrToBool(true) - return true, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_api_service.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_api_service.go deleted file mode 100644 index 7ee5070680d..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_api_service.go +++ /dev/null @@ -1,228 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "k8s.io/apimachinery/pkg/api/errors" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" - v1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" -) - -func resourceKubernetesAPIService() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesAPIServiceCreate, - Read: resourceKubernetesAPIServiceRead, - Exists: resourceKubernetesAPIServiceExists, - Update: resourceKubernetesAPIServiceUpdate, - Delete: resourceKubernetesAPIServiceDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("api_service", true), - "spec": { - Type: schema.TypeList, - Description: "Spec contains information for locating and communicating with a server. https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ca_bundle": { - Type: schema.TypeString, - Description: "CABundle is a PEM encoded CA bundle which will be used to validate an API server's serving certificate. If unspecified, system trust roots on the apiserver are used.", - Optional: true, - }, - "group": { - Type: schema.TypeString, - Description: "Group is the API group name this server hosts.", - Required: true, - }, - "group_priority_minimum": { - Type: schema.TypeInt, - Description: "GroupPriorityMinimum is the priority this group should have at least. Higher priority means that the group is preferred by clients over lower priority ones. Note that other versions of this group might specify even higher GroupPriorityMininum values such that the whole group gets a higher priority. The primary sort is based on GroupPriorityMinimum, ordered highest number to lowest (20 before 10). The secondary sort is based on the alphabetical comparison of the name of the object. (v1.bar before v1.foo) We'd recommend something like: *.k8s.io (except extensions) at 18000 and PaaSes (OpenShift, Deis) are recommended to be in the 2000s.", - Required: true, - ValidateFunc: validation.IntBetween(0, 20000), - }, - "insecure_skip_tls_verify": { - Type: schema.TypeBool, - Description: "InsecureSkipTLSVerify disables TLS certificate verification when communicating with this server. This is strongly discouraged. You should use the CABundle instead.", - Optional: true, - Default: false, - }, - "service": { - Type: schema.TypeList, - Description: "Service is a reference to the service for this API server. It must communicate on port 443. If the Service is nil, that means the handling for the API groupversion is handled locally on this server. The call will simply delegate to the normal handler chain to be fulfilled.", - Optional: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "Name is the name of the service.", - Required: true, - }, - "namespace": { - Type: schema.TypeString, - Description: "Namespace is the namespace of the service.", - Required: true, - }, - "port": { - Type: schema.TypeInt, - Description: "If specified, the port on the service that is hosting the service. Defaults to 443 for backward compatibility. Should be a valid port number (1-65535, inclusive).", - Optional: true, - Default: 443, - ValidateFunc: validatePortNum, - }, - }, - }, - }, - "version": { - Type: schema.TypeString, - Description: "Version is the API version this server hosts. For example, `v1`.", - Required: true, - }, - "version_priority": { - Type: schema.TypeInt, - Description: "VersionPriority controls the ordering of this API version inside of its group. Must be greater than zero. The primary sort is based on VersionPriority, ordered highest to lowest (20 before 10). Since it's inside of a group, the number can be small, probably in the 10s. In case of equal version priorities, the version string will be used to compute the order inside a group. If the version string is `kube-like`, it will sort above non `kube-like` version strings, which are ordered lexicographically. `Kube-like` versions start with a `v`, then are followed by a number (the major version), then optionally the string `alpha` or `beta` and another number (the minor version). These are sorted first by GA > `beta` > `alpha` (where GA is a version with no suffix such as `beta` or `alpha`), and then by comparing major version, then minor version. An example sorted list of versions: `v10`, `v2`, `v1`, `v11beta2`, `v10beta3`, `v3beta1`, `v12alpha1`, `v11alpha2`, `foo1`, `foo10`.", - Required: true, - ValidateFunc: validation.IntBetween(0, 1000), - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesAPIServiceCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).AggregatorClientset() - if err != nil { - return err - } - - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - svc := v1.APIService{ - ObjectMeta: metadata, - Spec: expandAPIServiceSpec(d.Get("spec").([]interface{})), - } - - log.Printf("[INFO] Creating new API service: %#v", svc) - out, err := conn.ApiregistrationV1().APIServices().Create(ctx, &svc, meta_v1.CreateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted new API service: %#v", out) - d.SetId(out.ObjectMeta.Name) - - return resourceKubernetesAPIServiceRead(d, meta) -} - -func resourceKubernetesAPIServiceRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).AggregatorClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Reading service %s", name) - svc, err := conn.ApiregistrationV1().APIServices().Get(ctx, name, meta_v1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received API service: %#v", svc) - err = d.Set("metadata", flattenMetadata(svc.ObjectMeta, d)) - if err != nil { - return err - } - - flattened := flattenAPIServiceSpec(svc.Spec) - log.Printf("[DEBUG] Flattened API service spec: %#v", flattened) - err = d.Set("spec", flattened) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesAPIServiceUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).AggregatorClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("spec") { - ops = append(ops, &ReplaceOperation{ - Path: "/spec", - Value: expandAPIServiceSpec(d.Get("spec").([]interface{})), - }) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating service %q: %v", name, string(data)) - out, err := conn.ApiregistrationV1().APIServices().Patch(ctx, name, pkgApi.JSONPatchType, data, meta_v1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update API service: %s", err) - } - log.Printf("[INFO] Submitted updated API service: %#v", out) - d.SetId(out.ObjectMeta.Name) - - return resourceKubernetesAPIServiceRead(d, meta) -} - -func resourceKubernetesAPIServiceDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).AggregatorClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Deleting API service: %#v", name) - err = conn.ApiregistrationV1().APIServices().Delete(ctx, name, meta_v1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] API service %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesAPIServiceExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).AggregatorClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Checking API service %s", name) - _, err = conn.ApiregistrationV1().APIServices().Get(ctx, name, meta_v1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_certificate_signing_request.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_certificate_signing_request.go deleted file mode 100644 index 06570cf1aaf..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_certificate_signing_request.go +++ /dev/null @@ -1,202 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "k8s.io/api/certificates/v1beta1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/util/retry" - "log" - "reflect" - "time" -) - -func resourceKubernetesCertificateSigningRequest() *schema.Resource { - apiDoc := v1beta1.CertificateSigningRequest{}.SwaggerDoc() - apiDocSpec := v1beta1.CertificateSigningRequestSpec{}.SwaggerDoc() - apiDocStatus := v1beta1.CertificateSigningRequestStatus{}.SwaggerDoc() - - return &schema.Resource{ - Create: resourceKubernetesCertificateSigningRequestCreate, - Read: resourceKubernetesCertificateSigningRequestRead, - Delete: resourceKubernetesCertificateSigningRequestDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(5 * time.Minute), - }, - Schema: map[string]*schema.Schema{ - "auto_approve": { - Type: schema.TypeBool, - Description: "Automatically approve the CertificateSigningRequest", - Optional: true, - ForceNew: true, - Default: true, - }, - "certificate": { - Type: schema.TypeString, - Description: apiDocStatus["certificate"], - Computed: true, - }, - "metadata": metadataSchemaForceNew(metadataSchema("certificate signing request", true)), - "spec": { - ForceNew: true, - Type: schema.TypeList, - Description: apiDoc[""], - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "request": { - Type: schema.TypeString, - Description: apiDocSpec["request"], - Required: true, - ForceNew: true, - }, - "signer_name": { - Type: schema.TypeString, - // no swagger doc available for signerName - Description: "Requested signer for the request. It is a qualified name in the form: `scope-hostname.io/name`." + - "If empty, it will be defaulted: 1. If it's a kubelet client certificate, it is assigned `kubernetes.io/kube-apiserver-client-kubelet`." + - "2. If it's a kubelet serving certificate, it is assigned `kubernetes.io/kubelet-serving`." + - "3. Otherwise, it is assigned `kubernetes.io/legacy-unknown`. Distribution of trust for signers happens out of band." + - "You can select on this field using `spec.signerName`.", - Optional: true, - ForceNew: true, - }, - "usages": { - Type: schema.TypeSet, - Description: apiDocSpec["usages"], - Set: schema.HashString, - Elem: &schema.Schema{Type: schema.TypeString}, - Optional: true, - ForceNew: true, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesCertificateSigningRequestCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandCertificateSigningRequestSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - - csr := v1beta1.CertificateSigningRequest{ - ObjectMeta: metadata, - Spec: *spec, - } - log.Printf("[INFO] Creating new certificate signing request: %#v", csr) - newCSR, createErr := conn.CertificatesV1beta1().CertificateSigningRequests().Create(ctx, &csr, metav1.CreateOptions{}) - if createErr != nil { - return fmt.Errorf("Failed to create certificate signing request: %s", err) - } - - // Get the name, since it might have been randomly generated during create. - csrName := newCSR.ObjectMeta.Name - - // Delete the remote CSR resource when this function exits, or when errors are encountered. - defer conn.CertificatesV1beta1().CertificateSigningRequests().Delete(ctx, csrName, metav1.DeleteOptions{}) - - if d.Get("auto_approve").(bool) { - retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error { - pendingCSR, getErr := conn.CertificatesV1beta1().CertificateSigningRequests().Get(ctx, csrName, metav1.GetOptions{}) - if getErr != nil { - return getErr - } - approval := v1beta1.CertificateSigningRequestCondition{ - Type: "Approved", - Reason: "TerraformAutoApprove", - Message: "This CSR was approved by Terraform auto_approve.", - } - pendingCSR.Status.Certificate = []byte{} - pendingCSR.Status.Conditions = append(pendingCSR.Status.Conditions, approval) - _, updateErr := conn.CertificatesV1beta1().CertificateSigningRequests().UpdateApproval(ctx, pendingCSR, metav1.UpdateOptions{}) - return updateErr - }) - if retryErr != nil { - panic(fmt.Errorf("CSR auto-approve update failed: %v", retryErr)) - } - fmt.Println("CSR auto-approve update succeeded") - } - - log.Printf("[DEBUG] Waiting for certificate to be issued") - stateConf := &resource.StateChangeConf{ - Target: []string{"Issued"}, - Pending: []string{"", "Approved"}, - Timeout: d.Timeout(schema.TimeoutCreate), - Refresh: func() (interface{}, string, error) { - out, refreshErr := conn.CertificatesV1beta1().CertificateSigningRequests().Get(ctx, csrName, metav1.GetOptions{}) - if refreshErr != nil { - log.Printf("[ERROR] Received error: %v", refreshErr) - return out, "Error", refreshErr - } - var csrStatus string - emptyStatus := v1beta1.CertificateSigningRequestStatus{} - emptyCSR := v1beta1.CertificateSigningRequest{} - - // If the CSR is empty, check again later. - if reflect.DeepEqual(emptyCSR, out) { - return out, csrStatus, nil - } - - // If the status is empty, check again later. - if reflect.DeepEqual(emptyStatus, out.Status) { - return out, csrStatus, nil - } - - // Check to see if a certificate has been issued, and update status accordingly, - // since 'Issued' is not a state ever populated in the Status Conditions. - for _, condition := range out.Status.Conditions { - log.Printf("[DEBUG] Found Status.Condition.Type: %v", condition.Type) - if string(condition.Type) == "Approved" { - if string(out.Status.Certificate) != "" { - log.Printf("[DEBUG] Found non-empty Certificate field in Status") - csrStatus = "Issued" - } - } - } - log.Printf("[DEBUG] CertificateSigningRequest %s status received: %#v", csrName, csrStatus) - return out, csrStatus, nil - }, - } - _, err = stateConf.WaitForState() - if err != nil { - return err - } - log.Printf("[INFO] Certificate issued for request: %s", csrName) - - issued, err := conn.CertificatesV1beta1().CertificateSigningRequests().Get(ctx, csrName, metav1.GetOptions{}) - if err != nil { - return err - } - - d.SetId(csrName) - d.Set("certificate", string(issued.Status.Certificate)) - - return resourceKubernetesCertificateSigningRequestRead(d, meta) -} - -// resourceKubernetesCertificateSigningRequestRead does not return any data, because Read functions exist to -// sync the local state with the remote state. Since this data is local-only, there is nothing to read. -func resourceKubernetesCertificateSigningRequestRead(_ *schema.ResourceData, _ interface{}) error { - return nil -} - -func resourceKubernetesCertificateSigningRequestDelete(d *schema.ResourceData, _ interface{}) error { - d.SetId("") - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_cluster_role.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_cluster_role.go deleted file mode 100644 index b61887fe32d..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_cluster_role.go +++ /dev/null @@ -1,192 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesClusterRole() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesClusterRoleCreate, - Read: resourceKubernetesClusterRoleRead, - Exists: resourceKubernetesClusterRoleExists, - Update: resourceKubernetesClusterRoleUpdate, - Delete: resourceKubernetesClusterRoleDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchemaRBAC("clusterRole", false, false), - "rule": { - Type: schema.TypeList, - Description: "List of PolicyRules for this ClusterRole", - Optional: true, - Computed: true, - MinItems: 1, - Elem: &schema.Resource{ - Schema: policyRuleSchema(), - }, - }, - "aggregation_rule": { - Type: schema.TypeList, - Description: "Describes how to build the Rules for this ClusterRole.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cluster_role_selectors": { - Type: schema.TypeList, - Description: "A list of selectors which will be used to find ClusterRoles and create the rules.", - Optional: true, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesClusterRoleCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - cRole := api.ClusterRole{ - ObjectMeta: metadata, - Rules: expandClusterRoleRules(d.Get("rule").([]interface{})), - } - - if v, ok := d.GetOk("aggregation_rule"); ok { - cRole.AggregationRule = expandClusterRoleAggregationRule(v.([]interface{})) - } - - log.Printf("[INFO] Creating new cluster role: %#v", cRole) - out, err := conn.RbacV1().ClusterRoles().Create(ctx, &cRole, metav1.CreateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted new cluster role: %#v", out) - d.SetId(out.Name) - - return resourceKubernetesClusterRoleRead(d, meta) -} - -func resourceKubernetesClusterRoleUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("rule") { - diffOps := patchRbacRule(d) - ops = append(ops, diffOps...) - } - if d.HasChange("aggregation_rule") { - diffOps := patchRbacAggregationRule(d) - ops = append(ops, diffOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating ClusterRole %q: %v", name, string(data)) - out, err := conn.RbacV1().ClusterRoles().Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update ClusterRole: %s", err) - } - log.Printf("[INFO] Submitted updated ClusterRole: %#v", out) - d.SetId(out.ObjectMeta.Name) - - return resourceKubernetesClusterRoleRead(d, meta) -} - -func resourceKubernetesClusterRoleRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Reading cluster role %s", name) - cRole, err := conn.RbacV1().ClusterRoles().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if errors.IsNotFound(err) { - d.SetId("") - return nil - } - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received cluster role: %#v", cRole) - err = d.Set("metadata", flattenMetadata(cRole.ObjectMeta, d)) - if err != nil { - return err - } - err = d.Set("rule", flattenClusterRoleRules(cRole.Rules)) - if err != nil { - return err - } - if cRole.AggregationRule != nil { - err = d.Set("aggregation_rule", flattenClusterRoleAggregationRule(cRole.AggregationRule)) - if err != nil { - return err - } - } - return nil -} - -func resourceKubernetesClusterRoleDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Deleting cluster role: %#v", name) - err = conn.RbacV1().ClusterRoles().Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] cluster role %s deleted", name) - - return nil -} - -func resourceKubernetesClusterRoleExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Checking cluster role %s", name) - _, err = conn.RbacV1().ClusterRoles().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if errors.IsNotFound(err) { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_cluster_role_binding.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_cluster_role_binding.go deleted file mode 100644 index b7552a16caf..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_cluster_role_binding.go +++ /dev/null @@ -1,179 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesClusterRoleBinding() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesClusterRoleBindingCreate, - Read: resourceKubernetesClusterRoleBindingRead, - Exists: resourceKubernetesClusterRoleBindingExists, - Update: resourceKubernetesClusterRoleBindingUpdate, - Delete: resourceKubernetesClusterRoleBindingDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchemaRBAC("clusterRoleBinding", false, false), - "role_ref": { - Type: schema.TypeList, - Description: "RoleRef references the Cluster Role for this binding", - Required: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: rbacRoleRefSchema(), - }, - }, - "subject": { - Type: schema.TypeList, - Description: "Subjects defines the entities to bind a ClusterRole to.", - Required: true, - MinItems: 1, - Elem: &schema.Resource{ - Schema: rbacSubjectSchema(), - }, - }, - }, - } -} - -func resourceKubernetesClusterRoleBindingCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - binding := &api.ClusterRoleBinding{ - ObjectMeta: metadata, - RoleRef: expandRBACRoleRef(d.Get("role_ref").([]interface{})), - Subjects: expandRBACSubjects(d.Get("subject").([]interface{})), - } - log.Printf("[INFO] Creating new ClusterRoleBinding: %#v", binding) - binding, err = conn.RbacV1().ClusterRoleBindings().Create(ctx, binding, metav1.CreateOptions{}) - - if err != nil { - return err - } - log.Printf("[INFO] Submitted new ClusterRoleBinding: %#v", binding) - d.SetId(metadata.Name) - - return resourceKubernetesClusterRoleBindingRead(d, meta) -} - -func resourceKubernetesClusterRoleBindingRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Reading ClusterRoleBinding %s", name) - binding, err := conn.RbacV1().ClusterRoleBindings().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - - log.Printf("[INFO] Received ClusterRoleBinding: %#v", binding) - err = d.Set("metadata", flattenMetadata(binding.ObjectMeta, d)) - if err != nil { - return err - } - - flattenedRef := flattenRBACRoleRef(binding.RoleRef) - log.Printf("[DEBUG] Flattened ClusterRoleBinding roleRef: %#v", flattenedRef) - err = d.Set("role_ref", flattenedRef) - if err != nil { - return err - } - - flattenedSubjects := flattenRBACSubjects(binding.Subjects) - log.Printf("[DEBUG] Flattened ClusterRoleBinding subjects: %#v", flattenedSubjects) - err = d.Set("subject", flattenedSubjects) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesClusterRoleBindingUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("subject") { - diffOps := patchRbacSubject(d) - ops = append(ops, diffOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating ClusterRoleBinding %q: %v", name, string(data)) - out, err := conn.RbacV1().ClusterRoleBindings().Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update ClusterRoleBinding: %s", err) - } - log.Printf("[INFO] Submitted updated ClusterRoleBinding: %#v", out) - d.SetId(out.ObjectMeta.Name) - - return resourceKubernetesClusterRoleBindingRead(d, meta) -} - -func resourceKubernetesClusterRoleBindingDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Deleting ClusterRoleBinding: %#v", name) - err = conn.RbacV1().ClusterRoleBindings().Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] ClusterRoleBinding %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesClusterRoleBindingExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Checking ClusterRoleBinding %s", name) - _, err = conn.RbacV1().ClusterRoleBindings().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_config_map.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_config_map.go deleted file mode 100644 index c819ec72a48..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_config_map.go +++ /dev/null @@ -1,181 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesConfigMap() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesConfigMapCreate, - Read: resourceKubernetesConfigMapRead, - Exists: resourceKubernetesConfigMapExists, - Update: resourceKubernetesConfigMapUpdate, - Delete: resourceKubernetesConfigMapDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("config map", true), - "binary_data": { - Type: schema.TypeMap, - Description: "BinaryData contains the binary data. Each key must consist of alphanumeric characters, '-', '_' or '.'. BinaryData can contain byte sequences that are not in the UTF-8 range. The keys stored in BinaryData must not overlap with the ones in the Data field, this is enforced during validation process. Using this field will require 1.10+ apiserver and kubelet. This field only accepts base64-encoded payloads that will be decoded/encoded before being sent/received to/from the apiserver.", - Optional: true, - ValidateFunc: validateBase64EncodedMap, - }, - "data": { - Type: schema.TypeMap, - Description: "Data contains the configuration data. Each key must consist of alphanumeric characters, '-', '_' or '.'. Values with non-UTF-8 byte sequences must use the BinaryData field. The keys stored in Data must not overlap with the keys in the BinaryData field, this is enforced during validation process.", - Optional: true, - }, - }, - } -} - -func resourceKubernetesConfigMapCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - cfgMap := api.ConfigMap{ - ObjectMeta: metadata, - BinaryData: expandBase64MapToByteMap(d.Get("binary_data").(map[string]interface{})), - Data: expandStringMap(d.Get("data").(map[string]interface{})), - } - log.Printf("[INFO] Creating new config map: %#v", cfgMap) - out, err := conn.CoreV1().ConfigMaps(metadata.Namespace).Create(ctx, &cfgMap, metav1.CreateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted new config map: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesConfigMapRead(d, meta) -} - -func resourceKubernetesConfigMapRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - log.Printf("[INFO] Reading config map %s", name) - cfgMap, err := conn.CoreV1().ConfigMaps(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received config map: %#v", cfgMap) - err = d.Set("metadata", flattenMetadata(cfgMap.ObjectMeta, d)) - if err != nil { - return err - } - - d.Set("binary_data", flattenByteMapToBase64Map(cfgMap.BinaryData)) - d.Set("data", cfgMap.Data) - - return nil -} - -func resourceKubernetesConfigMapUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("binary_data") { - oldV, newV := d.GetChange("binary_data") - diffOps := diffStringMap("/binaryData/", oldV.(map[string]interface{}), newV.(map[string]interface{})) - ops = append(ops, diffOps...) - } - - if d.HasChange("data") { - oldV, newV := d.GetChange("data") - diffOps := diffStringMap("/data/", oldV.(map[string]interface{}), newV.(map[string]interface{})) - ops = append(ops, diffOps...) - } - - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - - log.Printf("[INFO] Updating config map %q: %v", name, string(data)) - out, err := conn.CoreV1().ConfigMaps(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update Config Map: %s", err) - } - log.Printf("[INFO] Submitted updated config map: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesConfigMapRead(d, meta) -} - -func resourceKubernetesConfigMapDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - log.Printf("[INFO] Deleting config map: %#v", name) - err = conn.CoreV1().ConfigMaps(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Config map %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesConfigMapExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking config map %s", name) - _, err = conn.CoreV1().ConfigMaps(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_cron_job.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_cron_job.go deleted file mode 100644 index 685ec30640b..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_cron_job.go +++ /dev/null @@ -1,234 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "k8s.io/api/batch/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func resourceKubernetesCronJob() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesCronJobCreate, - Read: resourceKubernetesCronJobRead, - Update: resourceKubernetesCronJobUpdate, - Delete: resourceKubernetesCronJobDelete, - Exists: resourceKubernetesCronJobExists, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Delete: schema.DefaultTimeout(1 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("cronjob", true), - "spec": { - Type: schema.TypeList, - Description: "Spec of the cron job owned by the cluster", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: cronJobSpecFields(), - }, - }, - }, - } -} - -func resourceKubernetesCronJobCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandCronJobSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - - job := v1beta1.CronJob{ - ObjectMeta: metadata, - Spec: spec, - } - - log.Printf("[INFO] Creating new cron job: %#v", job) - - out, err := conn.BatchV1beta1().CronJobs(metadata.Namespace).Create(ctx, &job, metav1.CreateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted new cron job: %#v", out) - - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesCronJobRead(d, meta) -} - -func resourceKubernetesCronJobUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, _, err := idParts(d.Id()) - if err != nil { - return err - } - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandCronJobSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - spec.JobTemplate.ObjectMeta.Annotations = metadata.Annotations - - cronjob := &v1beta1.CronJob{ - ObjectMeta: metadata, - Spec: spec, - } - - log.Printf("[INFO] Updating cron job %s: %s", d.Id(), cronjob) - - out, err := conn.BatchV1beta1().CronJobs(namespace).Update(ctx, cronjob, metav1.UpdateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted updated cron job: %#v", out) - - d.SetId(buildId(out.ObjectMeta)) - return resourceKubernetesCronJobRead(d, meta) -} - -func resourceKubernetesCronJobRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading cron job %s", name) - job, err := conn.BatchV1beta1().CronJobs(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received cron job: %#v", job) - - // Remove server-generated labels unless using manual selector - if _, ok := d.GetOk("spec.0.manual_selector"); !ok { - labels := job.ObjectMeta.Labels - - if _, ok := labels["controller-uid"]; ok { - delete(labels, "controller-uid") - } - - if _, ok := labels["cron-job-name"]; ok { - delete(labels, "cron-job-name") - } - - if job.Spec.JobTemplate.Spec.Selector != nil && - job.Spec.JobTemplate.Spec.Selector.MatchLabels != nil { - labels = job.Spec.JobTemplate.Spec.Selector.MatchLabels - } - - if _, ok := labels["controller-uid"]; ok { - delete(labels, "controller-uid") - } - } - - err = d.Set("metadata", flattenMetadata(job.ObjectMeta, d)) - if err != nil { - return err - } - - jobSpec, err := flattenCronJobSpec(job.Spec, d) - if err != nil { - return err - } - - err = d.Set("spec", jobSpec) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesCronJobDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting cron job: %#v", name) - err = conn.BatchV1beta1().CronJobs(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - _, err := conn.BatchV1beta1().CronJobs(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return nil - } - return resource.NonRetryableError(err) - } - - e := fmt.Errorf("Cron Job %s still exists", name) - return resource.RetryableError(e) - }) - if err != nil { - return err - } - - log.Printf("[INFO] Cron Job %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesCronJobExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking cron job %s", name) - _, err = conn.BatchV1beta1().CronJobs(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_csi_driver.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_csi_driver.go deleted file mode 100644 index 6b270b5d38d..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_csi_driver.go +++ /dev/null @@ -1,206 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - storage "k8s.io/api/storage/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesCSIDriver() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesCSIDriverCreate, - Read: resourceKubernetesCSIDriverRead, - Exists: resourceKubernetesCSIDriverExists, - Update: resourceKubernetesCSIDriverUpdate, - Delete: resourceKubernetesCSIDriverDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("csi driver", true), - "spec": { - Type: schema.TypeList, - Description: fmt.Sprintf("Spec of the CSIDriver"), - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "attach_required": { - Type: schema.TypeBool, - Description: "Indicates if the CSI volume driver requires an attach operation", - Required: true, - ForceNew: true, - }, - "pod_info_on_mount": { - Type: schema.TypeBool, - Description: "Indicates that the CSI volume driver requires additional pod information (like podName, podUID, etc.) during mount operations", - Optional: true, - }, - "volume_lifecycle_modes": { - Type: schema.TypeList, - Description: "Defines what kind of volumes this CSI volume driver supports", - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: validation.StringInSlice([]string{ - "Persistent", - "Ephemeral", - }, false), - }, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesCSIDriverCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - CSIDriver := storage.CSIDriver{ - ObjectMeta: expandMetadata(d.Get("metadata").([]interface{})), - Spec: expandCSIDriverSpec(d.Get("spec").([]interface{})), - } - - log.Printf("[INFO] Creating new CSIDriver: %#v", CSIDriver) - out, err := conn.StorageV1beta1().CSIDrivers().Create(ctx, &CSIDriver, metav1.CreateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted new CSIDriver: %#v", out) - d.SetId(out.Name) - - return resourceKubernetesCSIDriverRead(d, meta) -} - -func resourceKubernetesCSIDriverRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Reading CSIDriver %s", name) - CSIDriver, err := conn.StorageV1beta1().CSIDrivers().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received CSIDriver: %#v", CSIDriver) - err = d.Set("metadata", flattenMetadata(CSIDriver.ObjectMeta, d)) - if err != nil { - return err - } - - spec, err := flattenCSIDriverSpec(CSIDriver.Spec) - if err != nil { - return err - } - - err = d.Set("spec", spec) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesCSIDriverUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("spec") { - diffOps, err := patchCSIDriverSpec("spec.0.", "/spec", d) - if err != nil { - return err - } - ops = append(ops, *diffOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating CSIDriver %q: %v", name, string(data)) - out, err := conn.StorageV1beta1().CSIDrivers().Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update CSIDriver: %s", err) - } - log.Printf("[INFO] Submitted updated CSIDriver: %#v", out) - d.SetId(out.ObjectMeta.Name) - - return resourceKubernetesCSIDriverRead(d, meta) -} - -func resourceKubernetesCSIDriverDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - log.Printf("[INFO] Deleting CSIDriver: %s", d.Id()) - err = conn.StorageV1beta1().CSIDrivers().Delete(ctx, d.Id(), metav1.DeleteOptions{}) - if err != nil { - return err - } - - err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - _, err := conn.StorageV1beta1().CSIDrivers().Get(ctx, d.Id(), metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return nil - } - return resource.NonRetryableError(err) - } - - e := fmt.Errorf("CSIDriver (%s) still exists", d.Id()) - return resource.RetryableError(e) - }) - if err != nil { - return err - } - - log.Printf("[INFO] CSIDriver %s deleted", d.Id()) - - d.SetId("") - return nil -} - -func resourceKubernetesCSIDriverExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Checking CSIDriver %s", name) - _, err = conn.StorageV1beta1().CSIDrivers().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_daemonset.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_daemonset.go deleted file mode 100644 index bd94bbbcbac..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_daemonset.go +++ /dev/null @@ -1,305 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "regexp" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - appsv1 "k8s.io/api/apps/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" -) - -func resourceKubernetesDaemonSet() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesDaemonSetCreate, - Read: resourceKubernetesDaemonSetRead, - Exists: resourceKubernetesDaemonSetExists, - Update: resourceKubernetesDaemonSetUpdate, - Delete: resourceKubernetesDaemonSetDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(10 * time.Minute), - Update: schema.DefaultTimeout(10 * time.Minute), - Delete: schema.DefaultTimeout(10 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("daemonset", true), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the specification of the desired behavior of the daemonset. More info: https://v1-9.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.9/#daemonset-v1-apps", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "min_ready_seconds": { - Type: schema.TypeInt, - Description: "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - Optional: true, - Default: 0, - }, - "revision_history_limit": { - Type: schema.TypeInt, - Description: "The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.", - Optional: true, - Default: 10, - }, - "selector": { - Type: schema.TypeList, - Description: "A label query over pods that are managed by the DaemonSet.", - Optional: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - "strategy": { - Type: schema.TypeList, - Optional: true, - Computed: true, - Description: "The deployment strategy used to replace existing pods with new ones.", - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "type": { - Type: schema.TypeString, - Description: "Type of deployment. Can be 'RollingUpdate' or 'OnDelete'. Default is RollingUpdate.", - Optional: true, - Default: "RollingUpdate", - ValidateFunc: validation.StringInSlice([]string{"RollingUpdate", "OnDelete"}, false), - }, - "rolling_update": { - Type: schema.TypeList, - Description: "Rolling update config params. Present only if type = 'RollingUpdate'.", - Optional: true, - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "max_unavailable": { - Type: schema.TypeString, - Description: "The maximum number of DaemonSet pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of total number of DaemonSet pods at the start of the update (ex: 10%). Absolute number is calculated from percentage by rounding up. This cannot be 0. Default value is 1. Example: when this is set to 30%, at most 30% of the total number of nodes that should be running the daemon pod (i.e. status.desiredNumberScheduled) can have their pods stopped for an update at any given time. The update starts by stopping at most 30% of those DaemonSet pods and then brings up new DaemonSet pods in their place. Once the new pods are available, it then proceeds onto other DaemonSet pods, thus ensuring that at least 70% of original number of DaemonSet pods are available at all times during the update.", - Optional: true, - Default: 1, - ValidateFunc: validation.StringMatch(regexp.MustCompile(`^([1-9][0-9]*|[1-9][0-9]%|[1-9]%|100%)$`), ""), - }, - }, - }, - }, - }, - }, - }, - "template": { - Type: schema.TypeList, - Description: "An object that describes the pod that will be created. The DaemonSet will create exactly one copy of this pod on every node that matches the template's node selector (or on every node if no node selector is specified). More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/#pod-template", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: podTemplateFields("daemon set"), - }, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesDaemonSetCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandDaemonSetSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - - daemonset := appsv1.DaemonSet{ - ObjectMeta: metadata, - Spec: spec, - } - - log.Printf("[INFO] Creating new daemonset: %#v", daemonset) - - out, err := conn.AppsV1().DaemonSets(metadata.Namespace).Create(ctx, &daemonset, metav1.CreateOptions{}) - if err != nil { - return fmt.Errorf("Failed to create daemonset: %s", err) - } - - d.SetId(buildId(out.ObjectMeta)) - - log.Printf("[INFO] Submitted new daemonset: %#v", out) - - return resourceKubernetesDaemonSetRead(d, meta) -} - -func resourceKubernetesDaemonSetUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - - if d.HasChange("spec") { - spec, err := expandDaemonSetSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - - ops = append(ops, &ReplaceOperation{ - Path: "/spec", - Value: spec, - }) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating daemonset: %q", name) - - out, err := conn.AppsV1().DaemonSets(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update daemonset: %s", err) - } - log.Printf("[INFO] Submitted updated daemonset: %#v", out) - - err = resource.Retry(d.Timeout(schema.TimeoutUpdate), - waitForDaemonSetReplicasFunc(ctx, conn, namespace, name)) - if err != nil { - return err - } - - return resourceKubernetesDaemonSetRead(d, meta) -} - -func resourceKubernetesDaemonSetRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading daemonset %s", name) - daemonset, err := conn.AppsV1().DaemonSets(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if errors.IsNotFound(err) { - d.SetId("") - return nil - } - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received daemonset: %#v", daemonset) - - err = d.Set("metadata", flattenMetadata(daemonset.ObjectMeta, d)) - if err != nil { - return err - } - - spec, err := flattenDaemonSetSpec(daemonset.Spec, d) - if err != nil { - return err - } - - err = d.Set("spec", spec) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesDaemonSetDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting daemonset: %#v", name) - - err = conn.AppsV1().DaemonSets(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] DaemonSet %s deleted", name) - - return nil -} - -func resourceKubernetesDaemonSetExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking daemonset %s", name) - _, err = conn.AppsV1().DaemonSets(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if errors.IsNotFound(err) { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} - -func waitForDaemonSetReplicasFunc(ctx context.Context, conn *kubernetes.Clientset, ns, name string) resource.RetryFunc { - return func() *resource.RetryError { - daemonSet, err := conn.AppsV1().DaemonSets(ns).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return resource.NonRetryableError(err) - } - - desiredReplicas := daemonSet.Status.DesiredNumberScheduled - log.Printf("[DEBUG] Current number of labelled replicas of %q: %d (of %d)\n", - daemonSet.GetName(), daemonSet.Status.CurrentNumberScheduled, desiredReplicas) - - if daemonSet.Status.CurrentNumberScheduled == desiredReplicas { - return nil - } - - return resource.RetryableError(fmt.Errorf("Waiting for %d replicas of %q to be scheduled (%d)", - desiredReplicas, daemonSet.GetName(), daemonSet.Status.CurrentNumberScheduled)) - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_default_service_account.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_default_service_account.go deleted file mode 100644 index 889c8815939..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_default_service_account.go +++ /dev/null @@ -1,71 +0,0 @@ -package kubernetes - -import ( - "context" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func resourceKubernetesDefaultServiceAccount() *schema.Resource { - serviceAccountResource := resourceKubernetesServiceAccount() - - metaSchema := namespacedMetadataSchema("service account", false) - - nameField := metaSchema.Elem.(*schema.Resource).Schema["name"] - nameField.Computed = false - nameField.Default = "default" - nameField.ValidateFunc = validation.StringInSlice([]string{"default"}, false) - - serviceAccountResource.Schema["metadata"] = metaSchema - - serviceAccountResource.Create = resourceKubernetesDefaultServiceAccountCreate - - return serviceAccountResource -} - -func resourceKubernetesDefaultServiceAccountCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - svcAcc := api.ServiceAccount{ObjectMeta: metadata} - - log.Printf("[INFO] Checking for default service account existence: %s", metadata.Namespace) - err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { - _, err := conn.CoreV1().ServiceAccounts(metadata.Namespace).Get(ctx, metadata.Name, metav1.GetOptions{}) - if err != nil { - if errors.IsNotFound(err) { - log.Printf("[INFO] Default service account does not exist, will retry: %s", metadata.Namespace) - return resource.RetryableError(err) - } - - return resource.NonRetryableError(err) - } - - log.Printf("[INFO] Default service account exists: %s", metadata.Namespace) - return nil - }) - - if err != nil { - return err - } - - d.SetId(buildId(metadata)) - - secret, err := getServiceAccountDefaultSecret(ctx, "default", svcAcc, d.Timeout(schema.TimeoutCreate), conn) - if err != nil { - return err - } - d.Set("default_secret_name", secret.Name) - - return resourceKubernetesServiceAccountUpdate(d, meta) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_deployment.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_deployment.go deleted file mode 100644 index 7c1834316d2..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_deployment.go +++ /dev/null @@ -1,445 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "regexp" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - - appsv1 "k8s.io/api/apps/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" -) - -const ( - // https://github.com/kubernetes/kubernetes/blob/master/pkg/controller/deployment/util/deployment_util.go#L93 - TimedOutReason = "ProgressDeadlineExceeded" -) - -func resourceKubernetesDeployment() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesDeploymentCreate, - Read: resourceKubernetesDeploymentRead, - Exists: resourceKubernetesDeploymentExists, - Update: resourceKubernetesDeploymentUpdate, - Delete: resourceKubernetesDeploymentDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(10 * time.Minute), - Update: schema.DefaultTimeout(10 * time.Minute), - Delete: schema.DefaultTimeout(10 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("deployment", true), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the specification of the desired behavior of the deployment. More info: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.9/#deployment-v1-apps", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "min_ready_seconds": { - Type: schema.TypeInt, - Description: "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - Optional: true, - Default: 0, - }, - "paused": { - Type: schema.TypeBool, - Description: "Indicates that the deployment is paused.", - Optional: true, - Default: false, - }, - "progress_deadline_seconds": { - Type: schema.TypeInt, - Description: "The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress will not be estimated during the time a deployment is paused. Defaults to 600s.", - Optional: true, - Default: 600, - }, - "replicas": { - Type: schema.TypeInt, - Description: "The number of desired replicas. Defaults to 1. More info: http://kubernetes.io/docs/user-guide/replication-controller#what-is-a-replication-controller", - Optional: true, - Default: 1, - }, - "revision_history_limit": { - Type: schema.TypeInt, - Description: "The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.", - Optional: true, - Default: 10, - }, - "selector": { - Type: schema.TypeList, - Description: "A label query over pods that should match the Replicas count.", - Optional: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "match_expressions": { - Type: schema.TypeList, - Description: "A list of label selector requirements. The requirements are ANDed.", - Optional: true, - ForceNew: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, - Description: "The label key that the selector applies to.", - Optional: true, - ForceNew: true, - }, - "operator": { - Type: schema.TypeString, - Description: "A key's relationship to a set of values. Valid operators ard `In`, `NotIn`, `Exists` and `DoesNotExist`.", - Optional: true, - ForceNew: true, - }, - "values": { - Type: schema.TypeSet, - Description: "An array of string values. If the operator is `In` or `NotIn`, the values array must be non-empty. If the operator is `Exists` or `DoesNotExist`, the values array must be empty. This array is replaced during a strategic merge patch.", - Optional: true, - ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - }, - }, - }, - "match_labels": { - Type: schema.TypeMap, - Description: "A map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of `match_expressions`, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.", - Optional: true, - ForceNew: true, - }, - }, - }, - }, - "strategy": { - Type: schema.TypeList, - Description: "The deployment strategy to use to replace existing pods with new ones.", - Optional: true, - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "type": { - Type: schema.TypeString, - Description: "Type of deployment. Can be 'Recreate' or 'RollingUpdate'. Default is RollingUpdate.", - Optional: true, - Default: "RollingUpdate", - ValidateFunc: validation.StringInSlice([]string{"RollingUpdate", "Recreate"}, false), - }, - "rolling_update": { - Type: schema.TypeList, - Description: "Rolling update config params. Present only if DeploymentStrategyType = RollingUpdate.", - Optional: true, - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "max_surge": { - Type: schema.TypeString, - Description: "The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 25%. Example: when this is set to 30%, the new RC can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new RC can be scaled up further, ensuring that total number of pods running at any time during the update is atmost 130% of desired pods.", - Optional: true, - Default: "25%", - ValidateFunc: validation.StringMatch(regexp.MustCompile(`^([0-9]+|[0-9]+%|)$`), ""), - }, - "max_unavailable": { - Type: schema.TypeString, - Description: "The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 25%. Example: when this is set to 30%, the old RC can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old RC can be scaled down further, followed by scaling up the new RC, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods.", - Optional: true, - Default: "25%", - ValidateFunc: validation.StringMatch(regexp.MustCompile(`^([0-9]+|[0-9]+%|)$`), ""), - }, - }, - }, - }, - }, - }, - }, - "template": { - Type: schema.TypeList, - Description: "Template describes the pods that will be created.", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchemaIsTemplate("pod", true, true), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the specification of the desired behavior of the deployment. More info: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.9/#deployment-v1-apps", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: podSpecFields(true, false, false), - }, - }, - }, - }, - }, - }, - }, - }, - "wait_for_rollout": { - Type: schema.TypeBool, - Description: "Wait for the rollout of the deployment to complete. Defaults to true.", - Default: true, - Optional: true, - }, - }, - } -} - -func resourceKubernetesDeploymentCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandDeploymentSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - - deployment := appsv1.Deployment{ - ObjectMeta: metadata, - Spec: *spec, - } - - log.Printf("[INFO] Creating new deployment: %#v", deployment) - out, err := conn.AppsV1().Deployments(metadata.Namespace).Create(ctx, &deployment, metav1.CreateOptions{}) - if err != nil { - return fmt.Errorf("Failed to create deployment: %s", err) - } - - d.SetId(buildId(out.ObjectMeta)) - - log.Printf("[DEBUG] Waiting for deployment %s to schedule %d replicas", d.Id(), *out.Spec.Replicas) - - if d.Get("wait_for_rollout").(bool) { - log.Printf("[INFO] Waiting for deployment %s/%s to rollout", out.ObjectMeta.Namespace, out.ObjectMeta.Name) - err := resource.Retry(d.Timeout(schema.TimeoutCreate), - waitForDeploymentReplicasFunc(ctx, conn, out.GetNamespace(), out.GetName())) - if err != nil { - return err - } - } - - log.Printf("[INFO] Submitted new deployment: %#v", out) - - return resourceKubernetesDeploymentRead(d, meta) -} - -func resourceKubernetesDeploymentUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - - if d.HasChange("spec") { - spec, err := expandDeploymentSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - - ops = append(ops, &ReplaceOperation{ - Path: "/spec", - Value: spec, - }) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating deployment %q: %v", name, string(data)) - out, err := conn.AppsV1().Deployments(namespace).Patch(ctx, name, types.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update deployment: %s", err) - } - log.Printf("[INFO] Submitted updated deployment: %#v", out) - - if d.Get("wait_for_rollout").(bool) { - log.Printf("[INFO] Waiting for deployment %s/%s to rollout", out.ObjectMeta.Namespace, out.ObjectMeta.Name) - err := resource.Retry(d.Timeout(schema.TimeoutCreate), - waitForDeploymentReplicasFunc(ctx, conn, out.GetNamespace(), out.GetName())) - if err != nil { - return err - } - } - - return resourceKubernetesDeploymentRead(d, meta) -} - -func resourceKubernetesDeploymentRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading deployment %s", name) - deployment, err := conn.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received deployment: %#v", deployment) - - err = d.Set("metadata", flattenMetadata(deployment.ObjectMeta, d)) - if err != nil { - return err - } - - spec, err := flattenDeploymentSpec(deployment.Spec, d) - if err != nil { - return err - } - - err = d.Set("spec", spec) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesDeploymentDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting deployment: %#v", name) - - err = conn.AppsV1().Deployments(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - _, err := conn.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return nil - } - return resource.NonRetryableError(err) - } - - e := fmt.Errorf("Deployment (%s) still exists", d.Id()) - return resource.RetryableError(e) - }) - if err != nil { - return err - } - - log.Printf("[INFO] Deployment %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesDeploymentExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking deployment %s", name) - _, err = conn.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} - -// GetDeploymentConditionInternal returns the condition with the provided type. -// Borrowed from: https://github.com/kubernetes/kubernetes/blob/master/pkg/controller/deployment/util/deployment_util.go#L135 -func GetDeploymentCondition(status appsv1.DeploymentStatus, condType appsv1.DeploymentConditionType) *appsv1.DeploymentCondition { - for i := range status.Conditions { - c := status.Conditions[i] - if c.Type == condType { - return &c - } - } - return nil -} - -func waitForDeploymentReplicasFunc(ctx context.Context, conn *kubernetes.Clientset, ns, name string) resource.RetryFunc { - return func() *resource.RetryError { - // Query the deployment to get a status update. - dply, err := conn.AppsV1().Deployments(ns).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return resource.NonRetryableError(err) - } - - var specReplicas int32 = 1 // default, acording to API docs - if dply.Spec.Replicas != nil { - specReplicas = *dply.Spec.Replicas - } - - if dply.Generation <= dply.Status.ObservedGeneration { - cond := GetDeploymentCondition(dply.Status, appsv1.DeploymentProgressing) - if cond != nil && cond.Reason == TimedOutReason { - err := fmt.Errorf("Deployment exceeded its progress deadline") - return resource.NonRetryableError(err) - } - - if dply.Status.UpdatedReplicas < specReplicas { - return resource.RetryableError(fmt.Errorf("Waiting for rollout to finish: %d out of %d new replicas have been updated...", dply.Status.UpdatedReplicas, specReplicas)) - } - - if dply.Status.Replicas > dply.Status.UpdatedReplicas { - return resource.RetryableError(fmt.Errorf("Waiting for rollout to finish: %d old replicas are pending termination...", dply.Status.Replicas-dply.Status.UpdatedReplicas)) - } - - if dply.Status.AvailableReplicas < dply.Status.UpdatedReplicas { - return resource.RetryableError(fmt.Errorf("Waiting for rollout to finish: %d of %d updated replicas are available...", dply.Status.AvailableReplicas, dply.Status.UpdatedReplicas)) - } - } else if dply.Status.ObservedGeneration == 0 { - return resource.RetryableError(fmt.Errorf("Waiting for rollout to start")) - } - return nil - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_endpoints.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_endpoints.go deleted file mode 100644 index e8190635252..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_endpoints.go +++ /dev/null @@ -1,174 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesEndpoints() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesEndpointsCreate, - Read: resourceKubernetesEndpointsRead, - Exists: resourceKubernetesEndpointsExists, - Update: resourceKubernetesEndpointsUpdate, - Delete: resourceKubernetesEndpointsDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("endpoints", true), - "subset": { - Type: schema.TypeSet, - Description: "Set of addresses and ports that comprise a service. More info: https://kubernetes.io/docs/concepts/services-networking/service/#services-without-selectors", - Optional: true, - Elem: schemaEndpointsSubset(), - Set: hashEndpointsSubset(), - }, - }, - } -} - -func resourceKubernetesEndpointsCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - ep := api.Endpoints{ - ObjectMeta: metadata, - Subsets: expandEndpointsSubsets(d.Get("subset").(*schema.Set)), - } - log.Printf("[INFO] Creating new endpoints: %#v", ep) - out, err := conn.CoreV1().Endpoints(metadata.Namespace).Create(ctx, &ep, metav1.CreateOptions{}) - if err != nil { - return fmt.Errorf("Failed to create endpoints because: %s", err) - } - log.Printf("[INFO] Submitted new endpoints: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesEndpointsRead(d, meta) -} - -func resourceKubernetesEndpointsRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return fmt.Errorf("Failed to read endpoints because: %s", err) - } - - log.Printf("[INFO] Reading endpoints %s", name) - ep, err := conn.CoreV1().Endpoints(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return fmt.Errorf("Failed to read endpoint because: %s", err) - } - log.Printf("[INFO] Received endpoints: %#v", ep) - err = d.Set("metadata", flattenMetadata(ep.ObjectMeta, d)) - if err != nil { - return fmt.Errorf("Failed to read endpoints because: %s", err) - } - - flattened := flattenEndpointsSubsets(ep.Subsets) - log.Printf("[DEBUG] Flattened endpoints subset: %#v", flattened) - err = d.Set("subset", flattened) - if err != nil { - return fmt.Errorf("Failed to read endpoints because: %s", err) - } - - return nil -} - -func resourceKubernetesEndpointsUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return fmt.Errorf("Failed to update endpoints because: %s", err) - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("subset") { - subsets := expandEndpointsSubsets(d.Get("subset").(*schema.Set)) - ops = append(ops, &ReplaceOperation{ - Path: "/subsets", - Value: subsets, - }) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating endpoints %q: %v", name, string(data)) - out, err := conn.CoreV1().Endpoints(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update endpoints: %s", err) - } - log.Printf("[INFO] Submitted updated endpoints: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesEndpointsRead(d, meta) -} - -func resourceKubernetesEndpointsDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return fmt.Errorf("Failed to delete endpoints because: %s", err) - } - log.Printf("[INFO] Deleting endpoints: %#v", name) - err = conn.CoreV1().Endpoints(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return fmt.Errorf("Failed to delete endpoints because: %s", err) - } - log.Printf("[INFO] Endpoints %s deleted", name) - d.SetId("") - - return nil -} - -func resourceKubernetesEndpointsExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking endpoints %s", name) - _, err = conn.CoreV1().Endpoints(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_horizontal_pod_autoscaler.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_horizontal_pod_autoscaler.go deleted file mode 100644 index 5b371551252..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_horizontal_pod_autoscaler.go +++ /dev/null @@ -1,261 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/autoscaling/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesHorizontalPodAutoscaler() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesHorizontalPodAutoscalerCreate, - Read: resourceKubernetesHorizontalPodAutoscalerRead, - Exists: resourceKubernetesHorizontalPodAutoscalerExists, - Update: resourceKubernetesHorizontalPodAutoscalerUpdate, - Delete: resourceKubernetesHorizontalPodAutoscalerDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("horizontal pod autoscaler", true), - "spec": { - Type: schema.TypeList, - Description: "Behaviour of the autoscaler. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "max_replicas": { - Type: schema.TypeInt, - Description: "Upper limit for the number of pods that can be set by the autoscaler.", - Required: true, - }, - "metric": { - Type: schema.TypeList, - Optional: true, - Description: "The specifications for which to use to calculate the desired replica count (the maximum replica count across all metrics will be used). The desired replica count is calculated multiplying the ratio between the target value and the current value by the current number of pods. Ergo, metrics used must decrease as the pod count is increased, and vice-versa. See the individual metric source types for more information about how each type of metric must respond. If not set, the default metric will be set to 80% average CPU utilization.", - Elem: metricSpecFields(), - }, - "min_replicas": { - Type: schema.TypeInt, - Description: "Lower limit for the number of pods that can be set by the autoscaler, defaults to `1`.", - Optional: true, - Default: 1, - }, - "scale_target_ref": { - Type: schema.TypeList, - Description: "Reference to scaled resource. e.g. Replication Controller", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "api_version": { - Type: schema.TypeString, - Description: "API version of the referent", - Optional: true, - }, - "kind": { - Type: schema.TypeString, - Description: "Kind of the referent. e.g. `ReplicationController`. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", - Required: true, - }, - "name": { - Type: schema.TypeString, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - Required: true, - }, - }, - }, - }, - "target_cpu_utilization_percentage": { - Type: schema.TypeInt, - Description: "Target average CPU utilization (represented as a percentage of requested CPU) over all the pods. If not specified the default autoscaling policy will be used.", - Optional: true, - Computed: true, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesHorizontalPodAutoscalerCreate(d *schema.ResourceData, meta interface{}) error { - if useV2(d) { - return resourceKubernetesHorizontalPodAutoscalerV2Create(d, meta) - } - - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandHorizontalPodAutoscalerSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - - svc := api.HorizontalPodAutoscaler{ - ObjectMeta: metadata, - Spec: *spec, - } - log.Printf("[INFO] Creating new horizontal pod autoscaler: %#v", svc) - out, err := conn.AutoscalingV1().HorizontalPodAutoscalers(metadata.Namespace).Create(ctx, &svc, metav1.CreateOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Submitted new horizontal pod autoscaler: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesHorizontalPodAutoscalerRead(d, meta) -} - -func resourceKubernetesHorizontalPodAutoscalerRead(d *schema.ResourceData, meta interface{}) error { - if useV2(d) { - return resourceKubernetesHorizontalPodAutoscalerV2Read(d, meta) - } - - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - log.Printf("[INFO] Reading horizontal pod autoscaler %s", name) - hpa, err := conn.AutoscalingV1().HorizontalPodAutoscalers(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - - // NOTE: this is needed for import - if _, exists := hpa.ObjectMeta.GetAnnotations()["autoscaling.alpha.kubernetes.io/metrics"]; exists { - return resourceKubernetesHorizontalPodAutoscalerV2Read(d, meta) - } - - log.Printf("[INFO] Received horizontal pod autoscaler: %#v", hpa) - err = d.Set("metadata", flattenMetadata(hpa.ObjectMeta, d)) - if err != nil { - return err - } - - flattened := flattenHorizontalPodAutoscalerSpec(hpa.Spec) - log.Printf("[DEBUG] Flattened horizontal pod autoscaler spec: %#v", flattened) - err = d.Set("spec", flattened) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesHorizontalPodAutoscalerUpdate(d *schema.ResourceData, meta interface{}) error { - if useV2(d) { - return resourceKubernetesHorizontalPodAutoscalerV2Update(d, meta) - } - - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("spec") { - diffOps := patchHorizontalPodAutoscalerSpec("spec.0.", "/spec", d) - ops = append(ops, diffOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating horizontal pod autoscaler %q: %v", name, string(data)) - out, err := conn.AutoscalingV1().HorizontalPodAutoscalers(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update horizontal pod autoscaler: %s", err) - } - log.Printf("[INFO] Submitted updated horizontal pod autoscaler: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesHorizontalPodAutoscalerRead(d, meta) -} - -func resourceKubernetesHorizontalPodAutoscalerDelete(d *schema.ResourceData, meta interface{}) error { - if useV2(d) { - return resourceKubernetesHorizontalPodAutoscalerV2Delete(d, meta) - } - - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - log.Printf("[INFO] Deleting horizontal pod autoscaler: %#v", name) - err = conn.AutoscalingV1().HorizontalPodAutoscalers(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Horizontal Pod Autoscaler %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesHorizontalPodAutoscalerExists(d *schema.ResourceData, meta interface{}) (bool, error) { - if useV2(d) { - return resourceKubernetesHorizontalPodAutoscalerV2Exists(d, meta) - } - - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking horizontal pod autoscaler %s", name) - _, err = conn.AutoscalingV1().HorizontalPodAutoscalers(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} - -func useV2(d *schema.ResourceData) bool { - if len(d.Get("spec.0.metric").([]interface{})) > 0 { - log.Printf("[INFO] Using autoscaling/v2beta2 because this resource has a metric field") - return true - } - return false -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_horizontal_pod_autoscaler_v2.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_horizontal_pod_autoscaler_v2.go deleted file mode 100644 index 026efe0459d..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_horizontal_pod_autoscaler_v2.go +++ /dev/null @@ -1,153 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - autoscalingv2beta2 "k8s.io/api/autoscaling/v2beta2" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesHorizontalPodAutoscalerV2Create(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandHorizontalPodAutoscalerV2Spec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - - hpa := autoscalingv2beta2.HorizontalPodAutoscaler{ - ObjectMeta: metadata, - Spec: *spec, - } - log.Printf("[INFO] Creating new horizontal pod autoscaler: %#v", hpa) - out, err := conn.AutoscalingV2beta2().HorizontalPodAutoscalers(metadata.Namespace).Create(ctx, &hpa, metav1.CreateOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Submitted new horizontal pod autoscaler: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesHorizontalPodAutoscalerV2Read(d, meta) -} - -func resourceKubernetesHorizontalPodAutoscalerV2Read(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - log.Printf("[INFO] Reading horizontal pod autoscaler %s", name) - hpa, err := conn.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received horizontal pod autoscaler: %#v", hpa) - err = d.Set("metadata", flattenMetadata(hpa.ObjectMeta, d)) - if err != nil { - return err - } - - flattened := flattenHorizontalPodAutoscalerV2Spec(hpa.Spec) - log.Printf("[DEBUG] Flattened horizontal pod autoscaler spec: %#v", flattened) - err = d.Set("spec", flattened) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesHorizontalPodAutoscalerV2Update(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("spec") { - diffOps := patchHorizontalPodAutoscalerV2Spec("spec.0.", "/spec", d) - ops = append(ops, diffOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating horizontal pod autoscaler %q: %v", name, string(data)) - out, err := conn.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).Patch(ctx, name, types.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update horizontal pod autoscaler: %s", err) - } - log.Printf("[INFO] Submitted updated horizontal pod autoscaler: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesHorizontalPodAutoscalerV2Read(d, meta) -} - -func resourceKubernetesHorizontalPodAutoscalerV2Delete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - log.Printf("[INFO] Deleting horizontal pod autoscaler: %#v", name) - err = conn.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Horizontal Pod Autoscaler %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesHorizontalPodAutoscalerV2Exists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking horizontal pod autoscaler %s", name) - _, err = conn.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_ingress.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_ingress.go deleted file mode 100644 index 2974820a79a..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_ingress.go +++ /dev/null @@ -1,295 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - networking "k8s.io/api/networking/v1beta1" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "k8s.io/api/extensions/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func resourceKubernetesIngress() *schema.Resource { - docHTTPIngressPath := networking.HTTPIngressPath{}.SwaggerDoc() - docHTTPIngressRuleValue := networking.HTTPIngressPath{}.SwaggerDoc() - docIngress := networking.Ingress{}.SwaggerDoc() - docIngressTLS := networking.IngressTLS{}.SwaggerDoc() - docIngressRule := networking.IngressRule{}.SwaggerDoc() - docIngressSpec := networking.IngressSpec{}.SwaggerDoc() - return &schema.Resource{ - Create: resourceKubernetesIngressCreate, - Read: resourceKubernetesIngressRead, - Exists: resourceKubernetesIngressExists, - Update: resourceKubernetesIngressUpdate, - Delete: resourceKubernetesIngressDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("ingress", true), - "spec": { - Type: schema.TypeList, - Description: docIngress["spec"], - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "backend": backendSpecFields(defaultBackendDescription), - // FIXME: this field is inconsistent with the k8s API 'rules' - "rule": { - Type: schema.TypeList, - Description: docIngress["rules"], - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "host": { - Type: schema.TypeString, - Description: docIngressRule["host"], - Optional: true, - }, - "http": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Description: "http is a list of http selectors pointing to backends. In the example: http:///? -> backend where where parts of the url correspond to RFC 3986, this resource will be used to match against everything after the last '/' and before the first '?' or '#'.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - // FIXME: this field is inconsistent with the k8s API 'paths' - "path": { - Type: schema.TypeList, - Required: true, - Description: docHTTPIngressRuleValue["paths"], - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "path": { - Type: schema.TypeString, - Description: docHTTPIngressPath["path"], - Optional: true, - }, - "backend": backendSpecFields(ruleBackedDescription), - }, - }, - }, - }, - }, - }, - }, - }, - }, - "tls": { - Type: schema.TypeList, - Description: docIngressSpec["tls"], - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "hosts": { - Type: schema.TypeList, - Description: docIngressTLS["hosts"], - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "secret_name": { - Type: schema.TypeString, - Description: docIngressTLS["secretName"], - Optional: true, - }, - }, - }, - }, - }, - }, - }, - "load_balancer_ingress": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ip": { - Type: schema.TypeString, - Computed: true, - }, - "hostname": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "wait_for_load_balancer": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "Terraform will wait for the load balancer to have at least 1 endpoint before considering the resource created.", - }, - }, - } -} - -func resourceKubernetesIngressCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - ing := &v1beta1.Ingress{ - Spec: expandIngressSpec(d.Get("spec").([]interface{})), - } - ing.ObjectMeta = metadata - log.Printf("[INFO] Creating new ingress: %#v", ing) - out, err := conn.ExtensionsV1beta1().Ingresses(metadata.Namespace).Create(ctx, ing, metav1.CreateOptions{}) - if err != nil { - return fmt.Errorf("Failed to create Ingress '%s' because: %s", buildId(ing.ObjectMeta), err) - } - log.Printf("[INFO] Submitted new ingress: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - if !d.Get("wait_for_load_balancer").(bool) { - return resourceKubernetesIngressRead(d, meta) - } - - log.Printf("[INFO] Waiting for load balancer to become ready: %#v", out) - return resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { - res, err := conn.ExtensionsV1beta1().Ingresses(metadata.Namespace).Get(ctx, metadata.Name, metav1.GetOptions{}) - if err != nil { - // NOTE it is possible in some HA apiserver setups that are eventually consistent - // that we could get a 404 when doing a Get immediately after a Create - if errors.IsNotFound(err) { - return resource.RetryableError(err) - } - return resource.NonRetryableError(err) - } - - if len(res.Status.LoadBalancer.Ingress) > 0 { - return resource.NonRetryableError(resourceKubernetesIngressRead(d, meta)) - } - - log.Printf("[INFO] Load Balancer not ready yet...") - return resource.RetryableError(fmt.Errorf("Load Balancer is not ready yet")) - }) -} - -func resourceKubernetesIngressRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading ingress %s", name) - ing, err := conn.ExtensionsV1beta1().Ingresses(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return fmt.Errorf("Failed to read Ingress '%s' because: %s", buildId(ing.ObjectMeta), err) - } - log.Printf("[INFO] Received ingress: %#v", ing) - err = d.Set("metadata", flattenMetadata(ing.ObjectMeta, d)) - if err != nil { - return err - } - - flattened := flattenIngressSpec(ing.Spec) - log.Printf("[DEBUG] Flattened ingress spec: %#v", flattened) - err = d.Set("spec", flattened) - if err != nil { - return err - } - - err = d.Set("load_balancer_ingress", flattenLoadBalancerIngress(ing.Status.LoadBalancer.Ingress)) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesIngressUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, _, err := idParts(d.Id()) - if err != nil { - return err - } - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec := expandIngressSpec(d.Get("spec").([]interface{})) - - if metadata.Namespace == "" { - metadata.Namespace = "default" - } - - ingress := &v1beta1.Ingress{ - ObjectMeta: metadata, - Spec: spec, - } - - out, err := conn.ExtensionsV1beta1().Ingresses(namespace).Update(ctx, ingress, metav1.UpdateOptions{}) - if err != nil { - return fmt.Errorf("Failed to update Ingress %s because: %s", buildId(ingress.ObjectMeta), err) - } - log.Printf("[INFO] Submitted updated ingress: %#v", out) - - return resourceKubernetesIngressRead(d, meta) -} - -func resourceKubernetesIngressDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting ingress: %#v", name) - err = conn.ExtensionsV1beta1().Ingresses(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return fmt.Errorf("Failed to delete Ingress %s because: %s", d.Id(), err) - } - - log.Printf("[INFO] Ingress %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesIngressExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking ingress %s", name) - _, err = conn.ExtensionsV1beta1().Ingresses(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_job.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_job.go deleted file mode 100644 index 28db978b1ca..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_job.go +++ /dev/null @@ -1,269 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - batchv1 "k8s.io/api/batch/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" -) - -func resourceKubernetesJob() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesJobCreate, - Read: resourceKubernetesJobRead, - Update: resourceKubernetesJobUpdate, - Delete: resourceKubernetesJobDelete, - Exists: resourceKubernetesJobExists, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(1 * time.Minute), - Update: schema.DefaultTimeout(1 * time.Minute), - Delete: schema.DefaultTimeout(1 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "metadata": jobMetadataSchema(), - "spec": { - Type: schema.TypeList, - Description: "Spec of the job owned by the cluster", - Required: true, - MaxItems: 1, - ForceNew: true, - Elem: &schema.Resource{ - Schema: jobSpecFields(), - }, - }, - "wait_for_completion": { - Type: schema.TypeBool, - Optional: true, - }, - }, - } -} - -func resourceKubernetesJobCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandJobSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - - job := batchv1.Job{ - ObjectMeta: metadata, - Spec: spec, - } - - log.Printf("[INFO] Creating new Job: %#v", job) - - out, err := conn.BatchV1().Jobs(metadata.Namespace).Create(ctx, &job, metav1.CreateOptions{}) - if err != nil { - return fmt.Errorf("Failed to create Job! API error: %s", err) - } - log.Printf("[INFO] Submitted new job: %#v", out) - - d.SetId(buildId(out.ObjectMeta)) - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - if d.Get("wait_for_completion").(bool) { - return resource.Retry(d.Timeout(schema.TimeoutCreate), - retryUntilJobIsFinished(ctx, conn, namespace, name)) - } - - return resourceKubernetesJobRead(d, meta) -} - -func resourceKubernetesJobUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - - log.Printf("[INFO] Updating job %s: %#v", d.Id(), ops) - - out, err := conn.BatchV1().Jobs(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update Job! API error: %s", err) - } - log.Printf("[INFO] Submitted updated job: %#v", out) - - d.SetId(buildId(out.ObjectMeta)) - - if d.Get("wait_for_completion").(bool) { - return resource.Retry(d.Timeout(schema.TimeoutUpdate), - retryUntilJobIsFinished(ctx, conn, namespace, name)) - } - return resourceKubernetesJobRead(d, meta) -} - -func resourceKubernetesJobRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading job %s", name) - job, err := conn.BatchV1().Jobs(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return fmt.Errorf("Failed to read Job! API error: %s", err) - } - log.Printf("[INFO] Received job: %#v", job) - - // Remove server-generated labels unless using manual selector - if _, ok := d.GetOk("spec.0.manual_selector"); !ok { - labels := job.ObjectMeta.Labels - - if _, ok := labels["controller-uid"]; ok { - delete(labels, "controller-uid") - } - - if _, ok := labels["job-name"]; ok { - delete(labels, "job-name") - } - - labels = job.Spec.Selector.MatchLabels - - if _, ok := labels["controller-uid"]; ok { - delete(labels, "controller-uid") - } - } - - err = d.Set("metadata", flattenMetadata(job.ObjectMeta, d)) - if err != nil { - return err - } - - jobSpec, err := flattenJobSpec(job.Spec, d) - if err != nil { - return err - } - - return d.Set("spec", jobSpec) -} - -func resourceKubernetesJobDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting job: %#v", name) - err = conn.BatchV1().Jobs(namespace).Delete(ctx, name, deleteOptions) - if err != nil { - return fmt.Errorf("Failed to delete Job! API error: %s", err) - } - - err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - _, err := conn.BatchV1().Jobs(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return nil - } - return resource.NonRetryableError(err) - } - - e := fmt.Errorf("Job %s still exists", name) - return resource.RetryableError(e) - }) - if err != nil { - return err - } - - log.Printf("[INFO] Job %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesJobExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking job %s", name) - _, err = conn.BatchV1().Jobs(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} - -// retryUntilJobIsFinished checks if a give job finished its execution and either in Complete or Failed state -func retryUntilJobIsFinished(ctx context.Context, conn *kubernetes.Clientset, ns, name string) resource.RetryFunc { - return func() *resource.RetryError { - job, err := conn.BatchV1().Jobs(ns).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return resource.NonRetryableError(err) - } - - for _, c := range job.Status.Conditions { - if c.Status == corev1.ConditionTrue { - log.Printf("[DEBUG] Current condition of job: %s/%s: %s\n", ns, name, c.Type) - switch c.Type { - case batchv1.JobComplete: - return nil - case batchv1.JobFailed: - return resource.NonRetryableError(fmt.Errorf("job: %s/%s is in failed sate", ns, name)) - } - } - } - - return resource.RetryableError(fmt.Errorf("job: %s/%s is not in complete state", ns, name)) - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_limit_range.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_limit_range.go deleted file mode 100644 index 2f90ffe4436..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_limit_range.go +++ /dev/null @@ -1,223 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesLimitRange() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesLimitRangeCreate, - Read: resourceKubernetesLimitRangeRead, - Exists: resourceKubernetesLimitRangeExists, - Update: resourceKubernetesLimitRangeUpdate, - Delete: resourceKubernetesLimitRangeDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("limit range", true), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the limits enforced. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "limit": { - Type: schema.TypeList, - Description: "Limits is the list of objects that are enforced.", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "default": { - Type: schema.TypeMap, - Description: "Default resource requirement limit value by resource name if resource limit is omitted.", - Optional: true, - }, - "default_request": { - Type: schema.TypeMap, - Description: "The default resource requirement request value by resource name if resource request is omitted.", - Optional: true, - Computed: true, - }, - "max": { - Type: schema.TypeMap, - Description: "Max usage constraints on this kind by resource name.", - Optional: true, - }, - "max_limit_request_ratio": { - Type: schema.TypeMap, - Description: "The named resource must have a request and limit that are both non-zero where limit divided by request is less than or equal to the enumerated value; this represents the max burst for the named resource.", - Optional: true, - }, - "min": { - Type: schema.TypeMap, - Description: "Min usage constraints on this kind by resource name.", - Optional: true, - }, - "type": { - Type: schema.TypeString, - Description: "Type of resource that this limit applies to.", - Optional: true, - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesLimitRangeCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandLimitRangeSpec(d.Get("spec").([]interface{}), d.IsNewResource()) - if err != nil { - return err - } - limitRange := api.LimitRange{ - ObjectMeta: metadata, - Spec: *spec, - } - log.Printf("[INFO] Creating new limit range: %#v", limitRange) - out, err := conn.CoreV1().LimitRanges(metadata.Namespace).Create(ctx, &limitRange, metav1.CreateOptions{}) - if err != nil { - return fmt.Errorf("Failed to create limit range: %s", err) - } - log.Printf("[INFO] Submitted new limit range: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesLimitRangeRead(d, meta) -} - -func resourceKubernetesLimitRangeRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - log.Printf("[INFO] Reading limit range %s", name) - limitRange, err := conn.CoreV1().LimitRanges(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received limit range: %#v", limitRange) - - err = d.Set("metadata", flattenMetadata(limitRange.ObjectMeta, d)) - if err != nil { - return err - } - err = d.Set("spec", flattenLimitRangeSpec(limitRange.Spec)) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesLimitRangeUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("spec") { - spec, err := expandLimitRangeSpec(d.Get("spec").([]interface{}), d.IsNewResource()) - if err != nil { - return err - } - ops = append(ops, &ReplaceOperation{ - Path: "/spec", - Value: spec, - }) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating limit range %q: %v", name, string(data)) - out, err := conn.CoreV1().LimitRanges(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update limit range: %s", err) - } - log.Printf("[INFO] Submitted updated limit range: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesLimitRangeRead(d, meta) -} - -func resourceKubernetesLimitRangeDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting limit range: %#v", name) - err = conn.CoreV1().LimitRanges(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Limit range %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesLimitRangeExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking limit range %s", name) - _, err = conn.CoreV1().LimitRanges(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_mutating_webhook_configuration.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_mutating_webhook_configuration.go deleted file mode 100644 index bc84669f6fa..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_mutating_webhook_configuration.go +++ /dev/null @@ -1,325 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - - copier "github.com/jinzhu/copier" -) - -func resourceKubernetesMutatingWebhookConfiguration() *schema.Resource { - apiDoc := admissionregistrationv1.MutatingWebhookConfiguration{}.SwaggerDoc() - webhookDoc := admissionregistrationv1.MutatingWebhook{}.SwaggerDoc() - return &schema.Resource{ - Create: resourceKubernetesMutatingWebhookConfigurationCreate, - Read: resourceKubernetesMutatingWebhookConfigurationRead, - Exists: resourceKubernetesMutatingWebhookConfigurationExists, - Update: resourceKubernetesMutatingWebhookConfigurationUpdate, - Delete: resourceKubernetesMutatingWebhookConfigurationDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("mutating webhook configuration", true), - "webhook": { - Type: schema.TypeList, - Description: apiDoc["webhooks"], - Required: true, - MinItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "admission_review_versions": { - Type: schema.TypeList, - Description: webhookDoc["admissionReviewVersions"], - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "client_config": { - Type: schema.TypeList, - Description: webhookDoc["clientConfig"], - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: webhookClientConfigFields(), - }, - }, - "failure_policy": { - Type: schema.TypeString, - Description: webhookDoc["failurePolicy"], - Optional: true, - Default: "Fail", - }, - "match_policy": { - Type: schema.TypeString, - Description: webhookDoc["matchPolicy"], - Optional: true, - Default: "Equivalent", - }, - "name": { - Type: schema.TypeString, - Description: webhookDoc["name"], - Required: true, - }, - "namespace_selector": { - Type: schema.TypeList, - Description: webhookDoc["namespaceSelector"], - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - "object_selector": { - Type: schema.TypeList, - Description: webhookDoc["objectSelector"], - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - "reinvocation_policy": { - Type: schema.TypeString, - Description: webhookDoc["reinvocationPolicy"], - Optional: true, - Default: "Never", - }, - "rule": { - Type: schema.TypeList, - Description: webhookDoc["rules"], - Required: true, - MinItems: 1, - Elem: &schema.Resource{ - Schema: ruleWithOperationsFields(), - }, - }, - "side_effects": { - Type: schema.TypeString, - Description: webhookDoc["sideEffects"], - Optional: true, - }, - "timeout_seconds": { - Type: schema.TypeInt, - Description: webhookDoc["timeoutSeconds"], - Default: 10, - Optional: true, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesMutatingWebhookConfigurationCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - cfg := admissionregistrationv1.MutatingWebhookConfiguration{ - ObjectMeta: expandMetadata(d.Get("metadata").([]interface{})), - Webhooks: expandMutatingWebhooks(d.Get("webhook").([]interface{})), - } - - log.Printf("[INFO] Creating new MutatingWebhookConfiguration: %#v", cfg) - - res := &admissionregistrationv1.MutatingWebhookConfiguration{} - - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return err - } - if useadmissionregistrationv1beta1 { - requestv1beta1 := &admissionregistrationv1beta1.MutatingWebhookConfiguration{} - responsev1beta1 := &admissionregistrationv1beta1.MutatingWebhookConfiguration{} - copier.Copy(requestv1beta1, cfg) - responsev1beta1, err = conn.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Create(ctx, requestv1beta1, metav1.CreateOptions{}) - copier.Copy(res, responsev1beta1) - } else { - res, err = conn.AdmissionregistrationV1().MutatingWebhookConfigurations().Create(ctx, &cfg, metav1.CreateOptions{}) - } - - if err != nil { - return err - } - - log.Printf("[INFO] Submitted new MutatingWebhookConfiguration: %#v", res) - - d.SetId(res.Name) - - return resourceKubernetesMutatingWebhookConfigurationRead(d, meta) -} - -func resourceKubernetesMutatingWebhookConfigurationRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - cfg := &admissionregistrationv1.MutatingWebhookConfiguration{} - - log.Printf("[INFO] Reading MutatingWebhookConfiguration %s", name) - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return err - } - if useadmissionregistrationv1beta1 { - cfgv1beta1 := &admissionregistrationv1beta1.MutatingWebhookConfiguration{} - cfgv1beta1, err = conn.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Get(ctx, name, metav1.GetOptions{}) - copier.Copy(cfg, cfgv1beta1) - } else { - cfg, err = conn.AdmissionregistrationV1().MutatingWebhookConfigurations().Get(ctx, name, metav1.GetOptions{}) - } - if err != nil { - return err - } - - err = d.Set("metadata", flattenMetadata(cfg.ObjectMeta, d)) - if err != nil { - return nil - } - - log.Printf("[DEBUG] Setting webhook to: %#v", cfg.Webhooks) - - err = d.Set("webhook", flattenMutatingWebhooks(cfg.Webhooks)) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesMutatingWebhookConfigurationUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - ops := patchMetadata("metadata.0.", "/metadata/", d) - - if d.HasChange("webhook") { - op := &ReplaceOperation{ - Path: "/webhooks", - } - - patch := expandMutatingWebhooks(d.Get("webhook").([]interface{})) - - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return err - } - if useadmissionregistrationv1beta1 { - patchv1beta1 := []admissionregistrationv1beta1.MutatingWebhook{} - copier.Copy(&patchv1beta1, &patch) - op.Value = patchv1beta1 - } else { - op.Value = patch - } - - ops = append(ops, op) - } - - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - - name := d.Id() - log.Printf("[INFO] Updating MutatingWebhookConfiguration %q: %v", name, string(data)) - - res := &admissionregistrationv1.MutatingWebhookConfiguration{} - - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return err - } - if useadmissionregistrationv1beta1 { - responsev1beta1 := &admissionregistrationv1beta1.MutatingWebhookConfiguration{} - responsev1beta1, err = conn.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Patch(ctx, name, types.JSONPatchType, data, metav1.PatchOptions{}) - copier.Copy(res, responsev1beta1) - } else { - res, err = conn.AdmissionregistrationV1().MutatingWebhookConfigurations().Patch(ctx, name, types.JSONPatchType, data, metav1.PatchOptions{}) - } - if err != nil { - return fmt.Errorf("Failed to update MutatingWebhookConfiguration: %s", err) - } - - log.Printf("[INFO] Submitted updated MutatingWebhookConfiguration: %#v", res) - - return resourceKubernetesMutatingWebhookConfigurationRead(d, meta) -} - -func resourceKubernetesMutatingWebhookConfigurationDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Deleting MutatingWebhookConfiguration: %#v", name) - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return err - } - if useadmissionregistrationv1beta1 { - err = conn.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Delete(ctx, name, metav1.DeleteOptions{}) - } else { - err = conn.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(ctx, name, metav1.DeleteOptions{}) - } - if err != nil { - return err - } - - log.Printf("[INFO] MutatingWebhookConfiguration %#v is deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesMutatingWebhookConfigurationExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Checking MutatingWebhookConfiguration %s", name) - - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return false, err - } - if useadmissionregistrationv1beta1 { - _, err = conn.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Get(ctx, name, metav1.GetOptions{}) - } else { - _, err = conn.AdmissionregistrationV1().MutatingWebhookConfigurations().Get(ctx, name, metav1.GetOptions{}) - } - - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - return false, err - } - - return true, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_namespace.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_namespace.go deleted file mode 100644 index 2902c93937e..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_namespace.go +++ /dev/null @@ -1,167 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesNamespace() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesNamespaceCreate, - Read: resourceKubernetesNamespaceRead, - Exists: resourceKubernetesNamespaceExists, - Update: resourceKubernetesNamespaceUpdate, - Delete: resourceKubernetesNamespaceDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("namespace", true), - }, - Timeouts: &schema.ResourceTimeout{ - Delete: schema.DefaultTimeout(5 * time.Minute), - }, - } -} - -func resourceKubernetesNamespaceCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - namespace := api.Namespace{ - ObjectMeta: metadata, - } - log.Printf("[INFO] Creating new namespace: %#v", namespace) - out, err := conn.CoreV1().Namespaces().Create(ctx, &namespace, metav1.CreateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted new namespace: %#v", out) - d.SetId(out.Name) - - return resourceKubernetesNamespaceRead(d, meta) -} - -func resourceKubernetesNamespaceRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Reading namespace %s", name) - namespace, err := conn.CoreV1().Namespaces().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received namespace: %#v", namespace) - err = d.Set("metadata", flattenMetadata(namespace.ObjectMeta, d)) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesNamespaceUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - ops := patchMetadata("metadata.0.", "/metadata/", d) - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - - log.Printf("[INFO] Updating namespace: %s", ops) - out, err := conn.CoreV1().Namespaces().Patch(ctx, d.Id(), pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted updated namespace: %#v", out) - d.SetId(out.Name) - - return resourceKubernetesNamespaceRead(d, meta) -} - -func resourceKubernetesNamespaceDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Deleting namespace: %#v", name) - err = conn.CoreV1().Namespaces().Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - stateConf := &resource.StateChangeConf{ - Target: []string{}, - Pending: []string{"Terminating"}, - Timeout: d.Timeout(schema.TimeoutDelete), - Refresh: func() (interface{}, string, error) { - out, err := conn.CoreV1().Namespaces().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return nil, "", nil - } - log.Printf("[ERROR] Received error: %#v", err) - return out, "Error", err - } - - statusPhase := fmt.Sprintf("%v", out.Status.Phase) - log.Printf("[DEBUG] Namespace %s status received: %#v", out.Name, statusPhase) - return out, statusPhase, nil - }, - } - _, err = stateConf.WaitForState() - if err != nil { - return err - } - log.Printf("[INFO] Namespace %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesNamespaceExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Checking namespace %s", name) - _, err = conn.CoreV1().Namespaces().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - log.Printf("[INFO] Namespace %s exists", name) - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_network_policy.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_network_policy.go deleted file mode 100644 index 6cabc965a3f..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_network_policy.go +++ /dev/null @@ -1,378 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/networking/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -// Use generated swagger docs from kubernetes' client-go to avoid copy/pasting them here -var ( - networkPolicySpecDoc = api.NetworkPolicy{}.SwaggerDoc()["spec"] - networkPolicySpecIngressDoc = api.NetworkPolicySpec{}.SwaggerDoc()["ingress"] - networkPolicyIngressRulePortsDoc = api.NetworkPolicyIngressRule{}.SwaggerDoc()["ports"] - networkPolicyIngressRuleFromDoc = api.NetworkPolicyIngressRule{}.SwaggerDoc()["from"] - networkPolicySpecEgressDoc = api.NetworkPolicySpec{}.SwaggerDoc()["egress"] - networkPolicyEgressRulePortsDoc = api.NetworkPolicyEgressRule{}.SwaggerDoc()["ports"] - networkPolicyEgressRuleToDoc = api.NetworkPolicyEgressRule{}.SwaggerDoc()["to"] - networkPolicyPortPortDoc = api.NetworkPolicyPort{}.SwaggerDoc()["port"] - networkPolicyPortProtocolDoc = api.NetworkPolicyPort{}.SwaggerDoc()["protocol"] - networkPolicyPeerIpBlockDoc = api.NetworkPolicyPeer{}.SwaggerDoc()["ipBlock"] - ipBlockCidrDoc = api.IPBlock{}.SwaggerDoc()["cidr"] - ipBlockExceptDoc = api.IPBlock{}.SwaggerDoc()["except"] - networkPolicyPeerNamespaceSelectorDoc = api.NetworkPolicyPeer{}.SwaggerDoc()["namespaceSelector"] - networkPolicyPeerPodSelectorDoc = api.NetworkPolicyPeer{}.SwaggerDoc()["podSelector"] - networkPolicySpecPodSelectorDoc = api.NetworkPolicySpec{}.SwaggerDoc()["podSelector"] - networkPolicySpecPolicyTypesDoc = api.NetworkPolicySpec{}.SwaggerDoc()["policyTypes"] -) - -func resourceKubernetesNetworkPolicy() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesNetworkPolicyCreate, - Read: resourceKubernetesNetworkPolicyRead, - Exists: resourceKubernetesNetworkPolicyExists, - Update: resourceKubernetesNetworkPolicyUpdate, - Delete: resourceKubernetesNetworkPolicyDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("network policy", true), - "spec": { - Type: schema.TypeList, - Description: networkPolicySpecDoc, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ingress": { - Type: schema.TypeList, - Description: networkPolicySpecIngressDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ports": { - Type: schema.TypeList, - Description: networkPolicyIngressRulePortsDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "port": { - Type: schema.TypeString, - Description: networkPolicyPortPortDoc, - Optional: true, - }, - "protocol": { - Type: schema.TypeString, - Description: networkPolicyPortProtocolDoc, - Optional: true, - Default: "TCP", - }, - }, - }, - }, - "from": { - Type: schema.TypeList, - Description: networkPolicyIngressRuleFromDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ip_block": { - Type: schema.TypeList, - Description: networkPolicyPeerIpBlockDoc, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cidr": { - Type: schema.TypeString, - Description: ipBlockCidrDoc, - Optional: true, - }, - "except": { - Type: schema.TypeList, - Description: ipBlockExceptDoc, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }, - }, - }, - "namespace_selector": { - Type: schema.TypeList, - Description: networkPolicyPeerNamespaceSelectorDoc, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - "pod_selector": { - Type: schema.TypeList, - Description: networkPolicyPeerPodSelectorDoc, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - }, - }, - }, - }, - }, - }, - "egress": { - Type: schema.TypeList, - Description: networkPolicySpecEgressDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ports": { - Type: schema.TypeList, - Description: networkPolicyEgressRulePortsDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "port": { - Type: schema.TypeString, - Description: networkPolicyPortPortDoc, - Optional: true, - }, - "protocol": { - Type: schema.TypeString, - Description: networkPolicyPortProtocolDoc, - Optional: true, - Default: "TCP", - }, - }, - }, - }, - "to": { - Type: schema.TypeList, - Description: networkPolicyEgressRuleToDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ip_block": { - Type: schema.TypeList, - Description: networkPolicyPeerIpBlockDoc, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cidr": { - Type: schema.TypeString, - Description: ipBlockCidrDoc, - Optional: true, - }, - "except": { - Type: schema.TypeList, - Description: ipBlockExceptDoc, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }, - }, - }, - "namespace_selector": { - Type: schema.TypeList, - Description: networkPolicyPeerNamespaceSelectorDoc, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - "pod_selector": { - Type: schema.TypeList, - Description: networkPolicyPeerPodSelectorDoc, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - }, - }, - }, - }, - }, - }, - "pod_selector": { - Type: schema.TypeList, - Description: networkPolicySpecPodSelectorDoc, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - // The policy_types property is made required because the default value is only evaluated server side on resource creation. - // During the initial creation, a default value is determined and stored, then PolicyTypes is no longer considered unset, - // it will stick to that value on further updates unless explicitly overridden. - // Leaving the policy_types property optional here would prevent further updates adding egress rules after the initial resource creation - // without egress rules nor policy types from working as expected as PolicyTypes will stick to Ingress server side. - "policy_types": { - Type: schema.TypeList, - Description: networkPolicySpecPolicyTypesDoc, - Required: true, - MinItems: 1, - MaxItems: 2, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesNetworkPolicyCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandNetworkPolicySpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - - svc := api.NetworkPolicy{ - ObjectMeta: metadata, - Spec: *spec, - } - log.Printf("[INFO] Creating new network policy: %#v", svc) - out, err := conn.NetworkingV1().NetworkPolicies(metadata.Namespace).Create(ctx, &svc, metav1.CreateOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Submitted new network policy: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesNetworkPolicyRead(d, meta) -} - -func resourceKubernetesNetworkPolicyRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - log.Printf("[INFO] Reading network policy %s", name) - svc, err := conn.NetworkingV1().NetworkPolicies(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received network policy: %#v", svc) - err = d.Set("metadata", flattenMetadata(svc.ObjectMeta, d)) - if err != nil { - return err - } - - flattened := flattenNetworkPolicySpec(svc.Spec) - log.Printf("[DEBUG] Flattened network policy spec: %#v", flattened) - err = d.Set("spec", flattened) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesNetworkPolicyUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("spec") { - diffOps, err := patchNetworkPolicySpec("spec.0.", "/spec", d) - if err != nil { - return err - } - ops = append(ops, *diffOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating network policy %q: %v", name, string(data)) - out, err := conn.NetworkingV1().NetworkPolicies(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update network policy: %s", err) - } - log.Printf("[INFO] Submitted updated network policy: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesNetworkPolicyRead(d, meta) -} - -func resourceKubernetesNetworkPolicyDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - log.Printf("[INFO] Deleting network policy: %#v", name) - err = conn.NetworkingV1().NetworkPolicies(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Network Policy %s deleted", name) - - return nil -} - -func resourceKubernetesNetworkPolicyExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking network policy %s", name) - _, err = conn.NetworkingV1().NetworkPolicies(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_persistent_volume.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_persistent_volume.go deleted file mode 100644 index 5ebdecc3d19..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_persistent_volume.go +++ /dev/null @@ -1,342 +0,0 @@ -package kubernetes - -import ( - "context" - "errors" - "fmt" - "log" - "strings" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - api "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -const ( - persistentVolumeAzureManagedError = `Unable to apply Azure Disk configuration. Managed disks require configuration: kind = "Managed"` - persistentVolumeAzureBlobError = `Unable to apply Azure Disk configuration. Blob storage disks require configuration: kind = "Shared" or kind = "Dedicated"` -) - -func resourceKubernetesPersistentVolume() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesPersistentVolumeCreate, - Read: resourceKubernetesPersistentVolumeRead, - Exists: resourceKubernetesPersistentVolumeExists, - Update: resourceKubernetesPersistentVolumeUpdate, - Delete: resourceKubernetesPersistentVolumeDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(5 * time.Minute), - }, - - CustomizeDiff: func(diff *schema.ResourceDiff, meta interface{}) error { - // The field `data_disk_uri` expects a different value depending on the value of `kind`. - // If `kind` is omitted, "Shared", or "Dedicated", then data_disk_uri expects a blob storage disk. - // If `kind` is "Managed", then `data_disk_uri` expects a Managed Disk. - kind := "spec.0.persistent_volume_source.0.azure_disk.0.kind" - diskURI := "spec.0.persistent_volume_source.0.azure_disk.0.data_disk_uri" - kindValue, _ := diff.GetOk(kind) - diskURIValue, diskURIExists := diff.GetOk(diskURI) - if diskURIExists && strings.Contains(diskURIValue.(string), "blob.core.windows.net") && kindValue == "Managed" { - log.Printf("Configuration error:") - log.Printf("Mismatch between Disk URI: %v = %v and Disk Kind: %v = %v", diskURI, diskURIValue, kind, kindValue) - return errors.New(persistentVolumeAzureBlobError) - } - if diskURIExists && strings.Contains(diskURIValue.(string), "/providers/Microsoft.Compute/disks/") && kindValue != "Managed" { - log.Printf("Configuration error:") - log.Printf("Mismatch between Disk URI: %v = %v and disk Kind: %v = %v", diskURI, diskURIValue, kind, kindValue) - return errors.New(persistentVolumeAzureManagedError) - } - // The following applies to Updates only. - if diff.Id() == "" { - return nil - } - // Any change to Persistent Volume Source requires a new resource. - keys := diff.GetChangedKeysPrefix("spec.0.persistent_volume_source") - for _, key := range keys { - log.Printf("[DEBUG] CustomizeDiff GetChangedKeysPrefix key: %v", key) - log.Printf("[DEBUG] CustomizeDiff key: %v", key) - err := diff.ForceNew(key) - if err != nil { - return err - } - } - return nil - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("persistent volume", false), - "spec": { - Type: schema.TypeList, - Description: "Spec of the persistent volume owned by the cluster", - Required: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "access_modes": { - Type: schema.TypeSet, - Description: "Contains all ways the volume can be mounted. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#access-modes", - Required: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: validation.StringInSlice([]string{ - "ReadWriteOnce", - "ReadOnlyMany", - "ReadWriteMany", - }, false), - }, - Set: schema.HashString, - }, - "capacity": { - Type: schema.TypeMap, - Description: "A description of the persistent volume's resources and capacity. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#capacity", - Required: true, - Elem: schema.TypeString, - ValidateFunc: validateResourceList, - }, - "persistent_volume_reclaim_policy": { - Type: schema.TypeString, - Description: "What happens to a persistent volume when released from its claim. Valid options are Retain (default) and Recycle. Recycling must be supported by the volume plugin underlying this persistent volume. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#recycling-policy", - Optional: true, - Default: "Retain", - ValidateFunc: validation.StringInSlice([]string{ - "Recycle", - "Delete", - "Retain", - }, false), - }, - "persistent_volume_source": { - Type: schema.TypeList, - Description: "The specification of a persistent volume.", - Required: true, - MaxItems: 1, - Elem: persistentVolumeSourceSchema(), - }, - "storage_class_name": { - Type: schema.TypeString, - Description: "A description of the persistent volume's class. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes/#class", - Optional: true, - }, - "node_affinity": { - Type: schema.TypeList, - Description: "A description of the persistent volume's node affinity. More info: https://kubernetes.io/docs/concepts/storage/volumes/#local", - Optional: true, - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "required": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "node_selector_term": { - Type: schema.TypeList, - Required: true, - Elem: &schema.Resource{ - Schema: nodeSelectorTermFields(), - }, - }, - }, - }, - }, - }, - }, - }, - "mount_options": { - Type: schema.TypeSet, - Description: "A list of mount options, e.g. [\"ro\", \"soft\"]. Not validated - mount will simply fail if one is invalid.", - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "volume_mode": { - Type: schema.TypeString, - Description: "Defines if a volume is intended to be used with a formatted filesystem. or to remain in raw block state.", - Optional: true, - ForceNew: true, - Default: "Filesystem", - ValidateFunc: validation.StringInSlice([]string{ - "Block", - "Filesystem", - }, false), - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesPersistentVolumeCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandPersistentVolumeSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - volume := api.PersistentVolume{ - ObjectMeta: metadata, - Spec: *spec, - } - - log.Printf("[INFO] Creating new persistent volume: %#v", volume) - out, err := conn.CoreV1().PersistentVolumes().Create(ctx, &volume, metav1.CreateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted new persistent volume: %#v", out) - - stateConf := &resource.StateChangeConf{ - Target: []string{"Available", "Bound"}, - Pending: []string{"Pending"}, - Timeout: d.Timeout(schema.TimeoutCreate), - Refresh: func() (interface{}, string, error) { - out, err := conn.CoreV1().PersistentVolumes().Get(ctx, metadata.Name, metav1.GetOptions{}) - if err != nil { - log.Printf("[ERROR] Received error: %#v", err) - return out, "Error", err - } - - statusPhase := fmt.Sprintf("%v", out.Status.Phase) - log.Printf("[DEBUG] Persistent volume %s status received: %#v", out.Name, statusPhase) - return out, statusPhase, nil - }, - } - _, err = stateConf.WaitForState() - if err != nil { - return err - } - log.Printf("[INFO] Persistent volume %s created", out.Name) - - d.SetId(out.Name) - - return resourceKubernetesPersistentVolumeRead(d, meta) -} - -func resourceKubernetesPersistentVolumeRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Reading persistent volume %s", name) - volume, err := conn.CoreV1().PersistentVolumes().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received persistent volume: %#v", volume) - err = d.Set("metadata", flattenMetadata(volume.ObjectMeta, d)) - if err != nil { - return err - } - err = d.Set("spec", flattenPersistentVolumeSpec(volume.Spec)) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesPersistentVolumeUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("spec") { - specOps, err := patchPersistentVolumeSpec("/spec", "spec", d) - if err != nil { - return err - } - ops = append(ops, specOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - - log.Printf("[INFO] Updating persistent volume %s: %s", d.Id(), ops) - out, err := conn.CoreV1().PersistentVolumes().Patch(ctx, d.Id(), pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted updated persistent volume: %#v", out) - d.SetId(out.Name) - - return resourceKubernetesPersistentVolumeRead(d, meta) -} - -func resourceKubernetesPersistentVolumeDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Deleting persistent volume: %#v", name) - err = conn.CoreV1().PersistentVolumes().Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - out, err := conn.CoreV1().PersistentVolumes().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - return nil - } - return resource.NonRetryableError(err) - } - - log.Printf("[DEBUG] Current state of persistent volume: %#v", out.Status.Phase) - e := fmt.Errorf("Persistent volume %s still exists (%s)", name, out.Status.Phase) - return resource.RetryableError(e) - }) - if err != nil { - return err - } - - log.Printf("[INFO] Persistent volume %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesPersistentVolumeExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Checking persistent volume %s", name) - _, err = conn.CoreV1().PersistentVolumes().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if k8serrors.IsNotFound(err) { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_persistent_volume_claim.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_persistent_volume_claim.go deleted file mode 100644 index 8ce4028b2c7..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_persistent_volume_claim.go +++ /dev/null @@ -1,289 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - k8sresource "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesPersistentVolumeClaim() *schema.Resource { - fields := persistentVolumeClaimFields() - // The 'wait_until_bound' control attribute only makes sense in stand-alone PVCs, - // so adding it on top of the standard PVC fields which are re-usable for other resources. - fields["wait_until_bound"] = &schema.Schema{ - Type: schema.TypeBool, - Description: "Whether to wait for the claim to reach `Bound` state (to find volume in which to claim the space)", - Optional: true, - Default: true, - } - return &schema.Resource{ - Create: resourceKubernetesPersistentVolumeClaimCreate, - Read: resourceKubernetesPersistentVolumeClaimRead, - Exists: resourceKubernetesPersistentVolumeClaimExists, - Update: resourceKubernetesPersistentVolumeClaimUpdate, - Delete: resourceKubernetesPersistentVolumeClaimDelete, - Importer: &schema.ResourceImporter{ - State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - d.Set("wait_until_bound", true) - return []*schema.ResourceData{d}, nil - }, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(5 * time.Minute), - }, - - Schema: fields, - - // All fields of Spec are immutable after creation, except for resources.requests.storage. - // Storage can only be increased in place. A new object will be created when the storage is decreased. - CustomizeDiff: func(diff *schema.ResourceDiff, meta interface{}) error { - // Skip custom logic for resource creation. - if diff.Id() == "" { - return nil - } - key := "spec.0.resources.0.requests" - subKeyStorage := "spec.0.resources.0.requests.storage" - subKeyLimits := "spec.0.resources.0.limits" - if diff.HasChange(subKeyLimits) { - err := diff.ForceNew(subKeyLimits) - if err != nil { - return err - } - return nil - } - if diff.HasChange(key) { - old, new := diff.GetChange(subKeyStorage) - oldStorageQuantity, err := k8sresource.ParseQuantity(old.(string)) - if err != nil { - return err - } - newStorageQuantity, err := k8sresource.ParseQuantity(new.(string)) - if err != nil { - return err - } - if newStorageQuantity.Cmp(oldStorageQuantity) == -1 { - log.Printf("[DEBUG] CustomizeDiff spec.resources.requests.storage: field can not be less than previous value") - log.Printf("[DEBUG] CustomizeDiff creating new PVC with size: %v", new) - err := diff.ForceNew(key) - if err != nil { - return err - } - } - } - return nil - }, - } -} - -func resourceKubernetesPersistentVolumeClaimCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - claim, err := expandPersistentVolumeClaim(map[string]interface{}{ - "metadata": d.Get("metadata"), - "spec": d.Get("spec"), - }) - if err != nil { - return err - } - log.Printf("[INFO] Creating new persistent volume claim: %#v", claim) - out, err := conn.CoreV1().PersistentVolumeClaims(claim.Namespace).Create(ctx, claim, metav1.CreateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted new persistent volume claim: %#v", out) - - d.SetId(buildId(out.ObjectMeta)) - name := out.ObjectMeta.Name - - if d.Get("wait_until_bound").(bool) { - stateConf := &resource.StateChangeConf{ - Target: []string{"Bound"}, - Pending: []string{"Pending"}, - Timeout: d.Timeout(schema.TimeoutCreate), - Refresh: func() (interface{}, string, error) { - out, err := conn.CoreV1().PersistentVolumeClaims(claim.Namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[ERROR] Received error: %#v", err) - return out, "", err - } - - statusPhase := fmt.Sprintf("%v", out.Status.Phase) - log.Printf("[DEBUG] Persistent volume claim %s status received: %#v", out.Name, statusPhase) - return out, statusPhase, nil - }, - } - _, err = stateConf.WaitForState() - if err != nil { - var lastWarnings []api.Event - var wErr error - - lastWarnings, wErr = getLastWarningsForObject(ctx, conn, out.ObjectMeta, "PersistentVolumeClaim", 3) - if wErr != nil { - return wErr - } - - if len(lastWarnings) == 0 { - lastWarnings, wErr = getLastWarningsForObject(ctx, conn, metav1.ObjectMeta{ - Name: out.Spec.VolumeName, - }, "PersistentVolume", 3) - if wErr != nil { - return wErr - } - } - - return fmt.Errorf("%s%s", err, stringifyEvents(lastWarnings)) - } - } - log.Printf("[INFO] Persistent volume claim %s created", out.Name) - - return resourceKubernetesPersistentVolumeClaimRead(d, meta) -} - -func resourceKubernetesPersistentVolumeClaimRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading persistent volume claim %s", name) - claim, err := conn.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received persistent volume claim: %#v", claim) - err = d.Set("metadata", flattenMetadata(claim.ObjectMeta, d)) - if err != nil { - return err - } - err = d.Set("spec", flattenPersistentVolumeClaimSpec(claim.Spec)) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesPersistentVolumeClaimUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - // spec.resources.requests is the only editable field in Spec. - if d.HasChange("spec.0.resources.0.requests") { - r := d.Get("spec.0.resources.0.requests").(map[string]interface{}) - requests, err := expandMapToResourceList(r) - if err != nil { - return err - } - ops = append(ops, &ReplaceOperation{ - Path: "/spec/resources/requests", - Value: requests, - }) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - - log.Printf("[INFO] Updating persistent volume claim: %s", ops) - out, err := conn.CoreV1().PersistentVolumeClaims(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted updated persistent volume claim: %#v", out) - - return resourceKubernetesPersistentVolumeClaimRead(d, meta) -} - -func resourceKubernetesPersistentVolumeClaimDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting persistent volume claim: %#v", name) - err = conn.CoreV1().PersistentVolumeClaims(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - out, err := conn.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if errors.IsNotFound(err) { - return nil - } - return resource.NonRetryableError(err) - } - - log.Printf("[DEBUG] Current state of persistent volume claim finalizers: %#v", out.Finalizers) - e := fmt.Errorf("Persistent volume claim %s still exists with finalizers: %v", name, out.Finalizers) - return resource.RetryableError(e) - }) - if err != nil { - return err - } - - log.Printf("[INFO] Persistent volume claim %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesPersistentVolumeClaimExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking persistent volume claim %s", name) - _, err = conn.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_pod.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_pod.go deleted file mode 100644 index 36a5589d490..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_pod.go +++ /dev/null @@ -1,246 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesPod() *schema.Resource { - podSpecFields := podSpecFields(false, false, false) - // Setting this default to false prevents a perpetual diff caused by volume_mounts - // being mutated on the server side as Kubernetes automatically adds a mount - // for the service account token - podSpecFields["automount_service_account_token"].Default = false - return &schema.Resource{ - Create: resourceKubernetesPodCreate, - Read: resourceKubernetesPodRead, - Update: resourceKubernetesPodUpdate, - Delete: resourceKubernetesPodDelete, - Exists: resourceKubernetesPodExists, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(5 * time.Minute), - Delete: schema.DefaultTimeout(5 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("pod", true), - "spec": { - Type: schema.TypeList, - Description: "Specification of the desired behavior of the pod.", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: podSpecFields, - }, - }, - }, - } -} -func resourceKubernetesPodCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandPodSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - - pod := api.Pod{ - ObjectMeta: metadata, - Spec: *spec, - } - - log.Printf("[INFO] Creating new pod: %#v", pod) - out, err := conn.CoreV1().Pods(metadata.Namespace).Create(ctx, &pod, metav1.CreateOptions{}) - - if err != nil { - return err - } - log.Printf("[INFO] Submitted new pod: %#v", out) - - d.SetId(buildId(out.ObjectMeta)) - - stateConf := &resource.StateChangeConf{ - Target: []string{"Running"}, - Pending: []string{"Pending"}, - Timeout: d.Timeout(schema.TimeoutCreate), - Refresh: func() (interface{}, string, error) { - out, err := conn.CoreV1().Pods(metadata.Namespace).Get(ctx, metadata.Name, metav1.GetOptions{}) - if err != nil { - log.Printf("[ERROR] Received error: %#v", err) - return out, "Error", err - } - - statusPhase := fmt.Sprintf("%v", out.Status.Phase) - log.Printf("[DEBUG] Pods %s status received: %#v", out.Name, statusPhase) - return out, statusPhase, nil - }, - } - _, err = stateConf.WaitForState() - if err != nil { - lastWarnings, wErr := getLastWarningsForObject(ctx, conn, out.ObjectMeta, "Pod", 3) - if wErr != nil { - return wErr - } - return fmt.Errorf("%s%s", err, stringifyEvents(lastWarnings)) - } - log.Printf("[INFO] Pod %s created", out.Name) - - return resourceKubernetesPodRead(d, meta) -} - -func resourceKubernetesPodUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("spec") { - specOps, err := patchPodSpec("/spec", "spec.0.", d) - if err != nil { - return err - } - ops = append(ops, specOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - - log.Printf("[INFO] Updating pod %s: %s", d.Id(), ops) - - out, err := conn.CoreV1().Pods(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted updated pod: %#v", out) - - d.SetId(buildId(out.ObjectMeta)) - return resourceKubernetesPodRead(d, meta) -} - -func resourceKubernetesPodRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading pod %s", name) - pod, err := conn.CoreV1().Pods(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received pod: %#v", pod) - - err = d.Set("metadata", flattenMetadata(pod.ObjectMeta, d)) - if err != nil { - return err - } - - podSpec, err := flattenPodSpec(pod.Spec) - if err != nil { - return err - } - - err = d.Set("spec", podSpec) - if err != nil { - return err - } - return nil - -} - -func resourceKubernetesPodDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting pod: %#v", name) - err = conn.CoreV1().Pods(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - out, err := conn.CoreV1().Pods(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return nil - } - return resource.NonRetryableError(err) - } - - log.Printf("[DEBUG] Current state of pod: %#v", out.Status.Phase) - e := fmt.Errorf("Pod %s still exists (%s)", name, out.Status.Phase) - return resource.RetryableError(e) - }) - if err != nil { - return err - } - - log.Printf("[INFO] Pod %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesPodExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking pod %s", name) - _, err = conn.CoreV1().Pods(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_pod_disruption_budget.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_pod_disruption_budget.go deleted file mode 100644 index 25c0944c636..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_pod_disruption_budget.go +++ /dev/null @@ -1,216 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/policy/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -// Use generated swagger docs from kubernetes' client-go to avoid copy/pasting them here -var ( - podDisruptionBudgetSpecDoc = api.PodDisruptionBudget{}.SwaggerDoc()["spec"] - podDisruptionBudgetSpecMaxUnavailableDoc = api.PodDisruptionBudget{}.SwaggerDoc()["maxUnavailable"] - podDisruptionBudgetSpecMinAvailableDoc = api.PodDisruptionBudget{}.SwaggerDoc()["minAvailable"] - podDisruptionBudgetSpecSelectorDoc = api.PodDisruptionBudget{}.SwaggerDoc()["selector"] -) - -func resourceKubernetesPodDisruptionBudget() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesPodDisruptionBudgetCreate, - Read: resourceKubernetesPodDisruptionBudgetRead, - Update: resourceKubernetesPodDisruptionBudgetUpdate, - Delete: resourceKubernetesPodDisruptionBudgetDelete, - Exists: resourceKubernetesPodDisruptionBudgetExists, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("pod disruption budget", true), - // Updates to spec not allowed until Kubernetes dependencies are updated to - // 1.13; have to delete and recreate until then - // https://github.com/kubernetes/kubernetes/issues/45398 - "spec": { - Type: schema.TypeList, - Description: podDisruptionBudgetSpecDoc, - Required: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "max_unavailable": { - Type: schema.TypeString, - Description: podDisruptionBudgetSpecMaxUnavailableDoc, - Optional: true, - ForceNew: true, - ValidateFunc: validateTypeStringNullableIntOrPercent, - }, - "min_available": { - Type: schema.TypeString, - Description: podDisruptionBudgetSpecMinAvailableDoc, - Optional: true, - ForceNew: true, - ValidateFunc: validateTypeStringNullableIntOrPercent, - }, - "selector": { - Type: schema.TypeList, - Description: podDisruptionBudgetSpecSelectorDoc, - Required: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(false), - }, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesPodDisruptionBudgetUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - - log.Printf("[INFO] Updating pod disruption budget %s: %s", d.Id(), ops) - out, err := conn.PolicyV1beta1().PodDisruptionBudgets(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Submitted updated pod disruption budget: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesPodDisruptionBudgetRead(d, meta) -} - -func resourceKubernetesPodDisruptionBudgetCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandPodDisruptionBudgetSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - pdb := api.PodDisruptionBudget{ - ObjectMeta: metadata, - Spec: *spec, - } - - log.Printf("[INFO] Creating new pod disruption budget: %#v", pdb) - out, err := conn.PolicyV1beta1().PodDisruptionBudgets(metadata.Namespace).Create(ctx, &pdb, metav1.CreateOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Submitted new pod disruption budget: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesPodDisruptionBudgetRead(d, meta) -} - -func resourceKubernetesPodDisruptionBudgetRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading pod disruption budget %s", name) - pdb, err := conn.PolicyV1beta1().PodDisruptionBudgets(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - - log.Printf("[INFO] Received pod disruption budget: %#v", pdb) - err = d.Set("metadata", flattenMetadata(pdb.ObjectMeta, d)) - if err != nil { - return err - } - - err = d.Set("spec", flattenPodDisruptionBudgetSpec(pdb.Spec)) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesPodDisruptionBudgetDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting pod disruption budget %#v", name) - err = conn.PolicyV1beta1().PodDisruptionBudgets(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - - log.Printf("[INFO] Pod disruption budget %#v deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesPodDisruptionBudgetExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking pod disruption budget %s", name) - _, err = conn.PolicyV1beta1().PodDisruptionBudgets(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_pod_security_policy.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_pod_security_policy.go deleted file mode 100644 index 1e9badbbe25..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_pod_security_policy.go +++ /dev/null @@ -1,515 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - policy "k8s.io/api/policy/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -// Use generated swagger docs from kubernetes' client-go to avoid copy/pasting them here -var ( - pspSpecDoc = policy.PodSecurityPolicy{}.SwaggerDoc()["spec"] - pspSpecAllowPrivilegeEscalationDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowPrivilegeEscalation"] - pspSpecAllowedCapabilitiesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowedCapabilities"] - pspSpecAllowedFlexVolumesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowedFlexVolumes"] - pspAllowedFlexVolumesDriverDoc = policy.AllowedFlexVolume{}.SwaggerDoc()["driver"] - pspSpecAllowedHostPathsDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowedHostPaths"] - pspAllowedHostPathsPathPrefixDoc = policy.AllowedHostPath{}.SwaggerDoc()["pathPrefix"] - pspAllowedHostPathsReadOnlyDoc = policy.AllowedHostPath{}.SwaggerDoc()["readOnly"] - pspSpecAllowedProcMountTypesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowedProcMountTypes"] - pspSpecAllowedUnsafeSysctlsDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowedUnsafeSysctls"] - pspSpecDefaultAddCapabilitiesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["defaultAddCapabilities"] - pspSpecDefaultAllowPrivilegeEscalationDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["defaultAllowPrivilegeEscalation"] - pspSpecForbiddenSysctlsDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["forbiddenSysctls"] - pspSpecFSGroupDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["fsGroup"] - pspFSGroupIDRangeDoc = policy.FSGroupStrategyOptions{}.SwaggerDoc()["ranges"] - pspIDRangeMinDoc = policy.IDRange{}.SwaggerDoc()["min"] - pspIDRangeMaxDoc = policy.IDRange{}.SwaggerDoc()["max"] - pspFSGroupRuleDoc = policy.FSGroupStrategyOptions{}.SwaggerDoc()["rule"] - pspSpecHostIPCDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["hostIPC"] - pspSpecHostNetworkDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["hostNetwork"] - pspSpecHostPIDDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["hostPID"] - pspSpecHostPortsDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["hostPorts"] - pspHostPortRangeMinDoc = policy.HostPortRange{}.SwaggerDoc()["min"] - pspHostPortRangeMaxDoc = policy.HostPortRange{}.SwaggerDoc()["max"] - pspSpecPrivilegedDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["privileged"] - pspSpecReadOnlyRootFilesystemDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["readOnlyRootFilesystem"] - pspSpecRequiredDropCapabilitiesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["requiredDropCapabilities"] - pspSpecRunAsUserDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["runAsUser"] - pspRunAsUserIDRangeDoc = policy.RunAsUserStrategyOptions{}.SwaggerDoc()["ranges"] - pspRunAsUserRuleDoc = policy.RunAsUserStrategyOptions{}.SwaggerDoc()["rule"] - pspSpecSELinuxDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["seLinux"] - pspSELinuxOptionsDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["seLinuxOptions"] - pspSELinuxOptionsLevelDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["level"] - pspSELinuxOptionsRoleDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["role"] - pspSELinuxOptionsTypeDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["type"] - pspSELinuxOptionsUserDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["user"] - pspSELinuxOptionsRuleDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["rule"] - pspSpecSupplementalGroupsDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["supplementalGroups"] - pspSupplementalGroupsRangesDoc = policy.SupplementalGroupsStrategyOptions{}.SwaggerDoc()["ranges"] - pspSupplementalGroupsRuleDoc = policy.SupplementalGroupsStrategyOptions{}.SwaggerDoc()["rule"] - pspSpecVolumesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["volumes"] - pspSpecRunAsGroupDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["runAsGroup"] - pspRunAsGroupIDRangeDoc = policy.RunAsGroupStrategyOptions{}.SwaggerDoc()["ranges"] - pspRunAsGroupRuleDoc = policy.RunAsGroupStrategyOptions{}.SwaggerDoc()["rule"] -) - -func resourceKubernetesPodSecurityPolicy() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesPodSecurityPolicyCreate, - Read: resourceKubernetesPodSecurityPolicyRead, - Exists: resourceKubernetesPodSecurityPolicyExists, - Update: resourceKubernetesPodSecurityPolicyUpdate, - Delete: resourceKubernetesPodSecurityPolicyDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("podsecuritypolicy", false), - "spec": { - Type: schema.TypeList, - Description: pspSpecDoc, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "allow_privilege_escalation": { - Type: schema.TypeBool, - Description: pspSpecAllowPrivilegeEscalationDoc, - Optional: true, - Computed: true, - }, - "allowed_capabilities": { - Type: schema.TypeList, - Description: pspSpecAllowedCapabilitiesDoc, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "allowed_flex_volumes": { - Type: schema.TypeList, - Description: pspSpecAllowedFlexVolumesDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "driver": { - Type: schema.TypeString, - Description: pspAllowedFlexVolumesDriverDoc, - Required: true, - }, - }, - }, - }, - "allowed_host_paths": { - Type: schema.TypeList, - Description: pspSpecAllowedHostPathsDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "path_prefix": { - Type: schema.TypeString, - Description: pspAllowedHostPathsPathPrefixDoc, - Required: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: pspAllowedHostPathsReadOnlyDoc, - Optional: true, - }, - }, - }, - }, - "allowed_proc_mount_types": { - Type: schema.TypeList, - Description: pspSpecAllowedProcMountTypesDoc, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "allowed_unsafe_sysctls": { - Type: schema.TypeList, - Description: pspSpecAllowedUnsafeSysctlsDoc, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "default_add_capabilities": { - Type: schema.TypeList, - Description: pspSpecDefaultAddCapabilitiesDoc, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "default_allow_privilege_escalation": { - Type: schema.TypeBool, - Description: pspSpecDefaultAllowPrivilegeEscalationDoc, - Optional: true, - Computed: true, - }, - "forbidden_sysctls": { - Type: schema.TypeList, - Description: pspSpecForbiddenSysctlsDoc, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "fs_group": { - Type: schema.TypeList, - Description: pspSpecFSGroupDoc, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "range": { - Type: schema.TypeList, - Description: pspFSGroupIDRangeDoc, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: idRangeSchema(), - }, - }, - "rule": { - Type: schema.TypeString, - Description: pspFSGroupRuleDoc, - Required: true, - }, - }, - }, - }, - "host_ipc": { - Type: schema.TypeBool, - Description: pspSpecHostIPCDoc, - Optional: true, - Computed: true, - }, - "host_network": { - Type: schema.TypeBool, - Description: pspSpecHostNetworkDoc, - Optional: true, - Computed: true, - }, - "host_pid": { - Type: schema.TypeBool, - Description: pspSpecHostPIDDoc, - Optional: true, - Computed: true, - }, - "host_ports": { - Type: schema.TypeList, - Description: pspSpecHostPortsDoc, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "min": { - Type: schema.TypeInt, - Description: pspHostPortRangeMinDoc, - Required: true, - }, - "max": { - Type: schema.TypeInt, - Description: pspHostPortRangeMaxDoc, - Required: true, - }, - }, - }, - }, - "privileged": { - Type: schema.TypeBool, - Description: pspSpecPrivilegedDoc, - Optional: true, - Computed: true, - }, - "read_only_root_filesystem": { - Type: schema.TypeBool, - Description: pspSpecReadOnlyRootFilesystemDoc, - Optional: true, - Computed: true, - }, - "required_drop_capabilities": { - Type: schema.TypeList, - Description: pspSpecRequiredDropCapabilitiesDoc, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "run_as_user": { - Type: schema.TypeList, - Description: pspSpecRunAsUserDoc, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "range": { - Type: schema.TypeList, - Description: pspRunAsUserIDRangeDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: idRangeSchema(), - }, - }, - "rule": { - Type: schema.TypeString, - Description: pspRunAsUserRuleDoc, - Required: true, - }, - }, - }, - }, - "run_as_group": { - Type: schema.TypeList, - Description: pspSpecRunAsGroupDoc, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "range": { - Type: schema.TypeList, - Description: pspRunAsGroupIDRangeDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: idRangeSchema(), - }, - }, - "rule": { - Type: schema.TypeString, - Description: pspRunAsGroupRuleDoc, - Required: true, - }, - }, - }, - }, - "se_linux": { - Type: schema.TypeList, - Description: pspSpecSELinuxDoc, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "se_linux_options": { - Type: schema.TypeList, - Description: pspSELinuxOptionsDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "level": { - Type: schema.TypeString, - Description: pspSELinuxOptionsLevelDoc, - Required: true, - }, - "role": { - Type: schema.TypeString, - Description: pspSELinuxOptionsRoleDoc, - Required: true, - }, - "type": { - Type: schema.TypeString, - Description: pspSELinuxOptionsTypeDoc, - Required: true, - }, - "user": { - Type: schema.TypeString, - Description: pspSELinuxOptionsUserDoc, - Required: true, - }, - }, - }, - }, - "rule": { - Type: schema.TypeString, - Description: pspSELinuxOptionsRuleDoc, - Required: true, - }, - }, - }, - }, - "supplemental_groups": { - Type: schema.TypeList, - Description: pspSpecSupplementalGroupsDoc, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "range": { - Type: schema.TypeList, - Description: pspSupplementalGroupsRangesDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: idRangeSchema(), - }, - }, - "rule": { - Type: schema.TypeString, - Description: pspSupplementalGroupsRuleDoc, - Required: true, - }, - }, - }, - }, - "volumes": { - Type: schema.TypeList, - Description: pspSpecVolumesDoc, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesPodSecurityPolicyCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandPodSecurityPolicySpec(d.Get("spec").([]interface{})) - - if err != nil { - return err - } - - psp := &policy.PodSecurityPolicy{ - ObjectMeta: metadata, - Spec: spec, - } - - log.Printf("[INFO] Creating new PodSecurityPolicy: %#v", psp) - out, err := conn.PolicyV1beta1().PodSecurityPolicies().Create(ctx, psp, metav1.CreateOptions{}) - - if err != nil { - return err - } - log.Printf("[INFO] Submitted new PodSecurityPolicy: %#v", out) - d.SetId(out.Name) - - return resourceKubernetesPodSecurityPolicyRead(d, meta) -} - -func resourceKubernetesPodSecurityPolicyRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Reading PodSecurityPolicy %s", name) - psp, err := conn.PolicyV1beta1().PodSecurityPolicies().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - - log.Printf("[INFO] Received PodSecurityPolicy: %#v", psp) - err = d.Set("metadata", flattenMetadata(psp.ObjectMeta, d)) - if err != nil { - return err - } - - flattenedSpec := flattenPodSecurityPolicySpec(psp.Spec) - log.Printf("[DEBUG] Flattened PodSecurityPolicy roleRef: %#v", flattenedSpec) - err = d.Set("spec", flattenedSpec) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesPodSecurityPolicyUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - ops := patchMetadata("metadata.0.", "/metadata/", d) - - if d.HasChange("spec") { - diffOps, err := patchPodSecurityPolicySpec("spec.0.", "/spec", d) - if err != nil { - return err - } - ops = append(ops, *diffOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating PodSecurityPolicy %q: %v", name, string(data)) - out, err := conn.PolicyV1beta1().PodSecurityPolicies().Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update PodSecurityPolicy: %s", err) - } - log.Printf("[INFO] Submitted updated PodSecurityPolicy: %#v", out) - d.SetId(out.Name) - - return resourceKubernetesPodSecurityPolicyRead(d, meta) -} - -func resourceKubernetesPodSecurityPolicyDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Deleting PodSecurityPolicy: %#v", name) - err = conn.PolicyV1beta1().PodSecurityPolicies().Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] PodSecurityPolicy %s deleted", name) - - return nil -} - -func resourceKubernetesPodSecurityPolicyExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Checking PodSecurityPolicy %s", name) - _, err = conn.PolicyV1beta1().PodSecurityPolicies().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} - -func idRangeSchema() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "min": { - Type: schema.TypeInt, - Description: pspIDRangeMinDoc, - Required: true, - }, - "max": { - Type: schema.TypeInt, - Description: pspIDRangeMaxDoc, - Required: true, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_priority_class.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_priority_class.go deleted file mode 100644 index d5c2bddcde2..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_priority_class.go +++ /dev/null @@ -1,201 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/scheduling/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesPriorityClass() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesPriorityClassCreate, - Read: resourceKubernetesPriorityClassRead, - Exists: resourceKubernetesPriorityClassExists, - Update: resourceKubernetesPriorityClassUpdate, - Delete: resourceKubernetesPriorityClassDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("priority class", true), - "description": { - Type: schema.TypeString, - Description: "An arbitrary string that usually provides guidelines on when this priority class should be used.", - Optional: true, - Default: "", - }, - "global_default": { - Type: schema.TypeBool, - Description: "Specifies whether this PriorityClass should be considered as the default priority for pods that do not have any priority class. Only one PriorityClass can be marked as `globalDefault`. However, if more than one PriorityClasses exists with their `globalDefault` field set to true, the smallest value of such global default PriorityClasses will be used as the default priority.", - Optional: true, - Default: false, - }, - "value": { - Type: schema.TypeInt, - Description: "The value of this priority class. This is the actual priority that pods receive when they have the name of this class in their pod spec.", - Required: true, - ForceNew: true, - }, - }, - } -} - -func resourceKubernetesPriorityClassCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - value := d.Get("value").(int) - description := d.Get("description").(string) - globalDefault := d.Get("global_default").(bool) - - priorityClass := api.PriorityClass{ - ObjectMeta: metadata, - Description: description, - GlobalDefault: globalDefault, - Value: int32(value), - } - - log.Printf("[INFO] Creating new priority class: %#v", priorityClass) - out, err := conn.SchedulingV1().PriorityClasses().Create(ctx, &priorityClass, metav1.CreateOptions{}) - if err != nil { - return fmt.Errorf("Failed to create priority class: %s", err) - } - log.Printf("[INFO] Submitted new priority class: %#v", out) - d.SetId(out.ObjectMeta.Name) - - return resourceKubernetesPriorityClassRead(d, meta) -} - -func resourceKubernetesPriorityClassRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Reading priority class %s", name) - priorityClass, err := conn.SchedulingV1().PriorityClasses().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received priority class: %#v", priorityClass) - - err = d.Set("metadata", flattenMetadata(priorityClass.ObjectMeta, d)) - if err != nil { - return err - } - - err = d.Set("value", priorityClass.Value) - if err != nil { - return err - } - - err = d.Set("description", priorityClass.Description) - if err != nil { - return err - } - - err = d.Set("global_default", priorityClass.GlobalDefault) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesPriorityClassUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - ops := patchMetadata("metadata.0.", "/metadata/", d) - - if d.HasChange("description") { - description := d.Get("description").(string) - ops = append(ops, &ReplaceOperation{ - Path: "/description", - Value: description, - }) - } - - if d.HasChange("global_default") { - globalDefault := d.Get("global_default").(bool) - ops = append(ops, &ReplaceOperation{ - Path: "/globalDefault", - Value: globalDefault, - }) - } - - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating priority class %q: %v", name, string(data)) - out, err := conn.SchedulingV1().PriorityClasses().Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update priority class: %s", err) - } - log.Printf("[INFO] Submitted updated priority class: %#v", out) - d.SetId(out.ObjectMeta.Name) - - return resourceKubernetesPriorityClassRead(d, meta) -} - -func resourceKubernetesPriorityClassDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Deleting priority class: %#v", name) - err = conn.SchedulingV1().PriorityClasses().Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] priority class %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesPriorityClassExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Checking priority class %s", name) - _, err = conn.SchedulingV1().PriorityClasses().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_replication_controller.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_replication_controller.go deleted file mode 100644 index 2e107177d5a..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_replication_controller.go +++ /dev/null @@ -1,328 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" -) - -func resourceKubernetesReplicationController() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesReplicationControllerCreate, - Read: resourceKubernetesReplicationControllerRead, - Exists: resourceKubernetesReplicationControllerExists, - Update: resourceKubernetesReplicationControllerUpdate, - Delete: resourceKubernetesReplicationControllerDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(10 * time.Minute), - Update: schema.DefaultTimeout(10 * time.Minute), - Delete: schema.DefaultTimeout(10 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("replication controller", true), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the specification of the desired behavior of the replication controller. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "min_ready_seconds": { - Type: schema.TypeInt, - Description: "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - Optional: true, - Default: 0, - }, - "replicas": { - Type: schema.TypeInt, - Description: "The number of desired replicas. Defaults to 1. More info: http://kubernetes.io/docs/user-guide/replication-controller#what-is-a-replication-controller", - Optional: true, - Default: 1, - }, - "selector": { - Type: schema.TypeMap, - Description: "A label query over pods that should match the Replicas count. If Selector is empty, it is defaulted to the labels present on the Pod template. Label keys and values that must match in order to be controlled by this replication controller, if empty defaulted to labels on Pod template. More info: http://kubernetes.io/docs/user-guide/labels#label-selectors", - Required: true, - }, - "template": { - Type: schema.TypeList, - Description: "Describes the pod that will be created if insufficient replicas are detected. This takes precedence over a TemplateRef. More info: http://kubernetes.io/docs/user-guide/replication-controller#pod-template", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: replicationControllerTemplateFieldSpec(), - }, - }, - }, - }, - }, - }, - } -} - -func replicationControllerTemplateFieldSpec() map[string]*schema.Schema { - metadata := namespacedMetadataSchemaIsTemplate("replication controller's template", true, true) - // TODO: make this required once the legacy fields are removed - metadata.Computed = true - metadata.Required = false - metadata.Optional = true - - templateFields := map[string]*schema.Schema{ - "metadata": metadata, - "spec": { - Type: schema.TypeList, - Description: "Spec of the pods managed by the replication controller", - Optional: true, // TODO: make this required once the legacy fields are removed - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: podSpecFields(false, false, true), - }, - }, - } - - // Merge deprecated fields and mark them conflicting with the ones to avoid complex mixed use-cases - for k, v := range podSpecFields(true, true, true) { - v.ConflictsWith = []string{"spec.0.template.0.spec", "spec.0.template.0.metadata"} - templateFields[k] = v - } - - return templateFields -} - -func useDeprecatedSpecFields(d *schema.ResourceData) (deprecatedSpecFieldsExist bool) { - // Check which replication controller template spec fields are used - _, deprecatedSpecFieldsExist = d.GetOkExists("spec.0.template.0.container.0.name") - return -} - -func resourceKubernetesReplicationControllerCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - - spec, err := expandReplicationControllerSpec(d.Get("spec").([]interface{}), useDeprecatedSpecFields(d)) - if err != nil { - return err - } - - rc := api.ReplicationController{ - ObjectMeta: metadata, - Spec: *spec, - } - - log.Printf("[INFO] Creating new replication controller: %#v", rc) - out, err := conn.CoreV1().ReplicationControllers(metadata.Namespace).Create(ctx, &rc, metav1.CreateOptions{}) - if err != nil { - return fmt.Errorf("Failed to create replication controller: %s", err) - } - - d.SetId(buildId(out.ObjectMeta)) - - log.Printf("[DEBUG] Waiting for replication controller %s to schedule %d replicas", - d.Id(), *out.Spec.Replicas) - // 10 mins should be sufficient for scheduling ~10k replicas - err = resource.Retry(d.Timeout(schema.TimeoutCreate), - waitForDesiredReplicasFunc(ctx, conn, out.GetNamespace(), out.GetName())) - if err != nil { - return err - } - // We could wait for all pods to actually reach Ready state - // but that means checking each pod status separately (which can be expensive at scale) - // as there's no aggregate data available from the API - - log.Printf("[INFO] Submitted new replication controller: %#v", out) - - return resourceKubernetesReplicationControllerRead(d, meta) -} - -func resourceKubernetesReplicationControllerRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading replication controller %s", name) - rc, err := conn.CoreV1().ReplicationControllers(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received replication controller: %#v", rc) - - err = d.Set("metadata", flattenMetadata(rc.ObjectMeta, d)) - if err != nil { - return err - } - - spec, err := flattenReplicationControllerSpec(rc.Spec, d, useDeprecatedSpecFields(d)) - if err != nil { - return err - } - - err = d.Set("spec", spec) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesReplicationControllerUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - - if d.HasChange("spec") { - spec, err := expandReplicationControllerSpec(d.Get("spec").([]interface{}), useDeprecatedSpecFields(d)) - if err != nil { - return err - } - - ops = append(ops, &ReplaceOperation{ - Path: "/spec", - Value: spec, - }) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating replication controller %q: %v", name, string(data)) - out, err := conn.CoreV1().ReplicationControllers(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update replication controller: %s", err) - } - log.Printf("[INFO] Submitted updated replication controller: %#v", out) - - err = resource.Retry(d.Timeout(schema.TimeoutUpdate), - waitForDesiredReplicasFunc(ctx, conn, namespace, name)) - if err != nil { - return err - } - - return resourceKubernetesReplicationControllerRead(d, meta) -} - -func resourceKubernetesReplicationControllerDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting replication controller: %#v", name) - - // Drain all replicas before deleting - var ops PatchOperations - ops = append(ops, &ReplaceOperation{ - Path: "/spec/replicas", - Value: 0, - }) - data, err := ops.MarshalJSON() - if err != nil { - return err - } - _, err = conn.CoreV1().ReplicationControllers(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return err - } - - // Wait until all replicas are gone - err = resource.Retry(d.Timeout(schema.TimeoutDelete), - waitForDesiredReplicasFunc(ctx, conn, namespace, name)) - if err != nil { - return err - } - - err = conn.CoreV1().ReplicationControllers(namespace).Delete(ctx, name, deleteOptions) - if err != nil { - return err - } - - log.Printf("[INFO] Replication controller %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesReplicationControllerExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking replication controller %s", name) - _, err = conn.CoreV1().ReplicationControllers(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} - -func waitForDesiredReplicasFunc(ctx context.Context, conn *kubernetes.Clientset, ns, name string) resource.RetryFunc { - return func() *resource.RetryError { - rc, err := conn.CoreV1().ReplicationControllers(ns).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return resource.NonRetryableError(err) - } - - desiredReplicas := *rc.Spec.Replicas - log.Printf("[DEBUG] Current number of labelled replicas of %q: %d (of %d)\n", - rc.GetName(), rc.Status.FullyLabeledReplicas, desiredReplicas) - - if rc.Status.FullyLabeledReplicas == desiredReplicas { - return nil - } - - return resource.RetryableError(fmt.Errorf("Waiting for %d replicas of %q to be scheduled (%d)", - desiredReplicas, rc.GetName(), rc.Status.FullyLabeledReplicas)) - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_resource_quota.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_resource_quota.go deleted file mode 100644 index 8f976edceb3..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_resource_quota.go +++ /dev/null @@ -1,251 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesResourceQuota() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesResourceQuotaCreate, - Read: resourceKubernetesResourceQuotaRead, - Exists: resourceKubernetesResourceQuotaExists, - Update: resourceKubernetesResourceQuotaUpdate, - Delete: resourceKubernetesResourceQuotaDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(1 * time.Minute), - Update: schema.DefaultTimeout(1 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("resource quota", true), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the desired quota. https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "hard": { - Type: schema.TypeMap, - Description: "The set of desired hard limits for each named resource. More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota", - Optional: true, - Elem: schema.TypeString, - ValidateFunc: validateResourceList, - }, - "scopes": { - Type: schema.TypeSet, - Description: "A collection of filters that must match each object tracked by a quota. If not specified, the quota matches all objects.", - Optional: true, - ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesResourceQuotaCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandResourceQuotaSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - resQuota := api.ResourceQuota{ - ObjectMeta: metadata, - Spec: *spec, - } - log.Printf("[INFO] Creating new resource quota: %#v", resQuota) - out, err := conn.CoreV1().ResourceQuotas(metadata.Namespace).Create(ctx, &resQuota, metav1.CreateOptions{}) - if err != nil { - return fmt.Errorf("Failed to create resource quota: %s", err) - } - log.Printf("[INFO] Submitted new resource quota: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { - quota, err := conn.CoreV1().ResourceQuotas(out.Namespace).Get(ctx, out.Name, metav1.GetOptions{}) - if err != nil { - return resource.NonRetryableError(err) - } - if resourceListEquals(spec.Hard, quota.Status.Hard) { - return nil - } - err = fmt.Errorf("Quotas don't match after creation.\nExpected: %#v\nGiven: %#v", - spec.Hard, quota.Status.Hard) - return resource.RetryableError(err) - }) - if err != nil { - return err - } - - return resourceKubernetesResourceQuotaRead(d, meta) -} - -func resourceKubernetesResourceQuotaRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading resource quota %s", name) - resQuota, err := conn.CoreV1().ResourceQuotas(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received resource quota: %#v", resQuota) - - // This is to work around K8S bug - // See https://github.com/kubernetes/kubernetes/issues/44539 - if resQuota.ObjectMeta.GenerateName == "" { - if v, ok := d.GetOk("metadata.0.generate_name"); ok { - resQuota.ObjectMeta.GenerateName = v.(string) - } - } - - err = d.Set("metadata", flattenMetadata(resQuota.ObjectMeta, d)) - if err != nil { - return err - } - err = d.Set("spec", flattenResourceQuotaSpec(resQuota.Spec)) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesResourceQuotaUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - var spec *api.ResourceQuotaSpec - waitForChangedSpec := false - if d.HasChange("spec") { - spec, err = expandResourceQuotaSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - ops = append(ops, &ReplaceOperation{ - Path: "/spec", - Value: *spec, - }) - waitForChangedSpec = true - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating resource quota %q: %v", name, string(data)) - out, err := conn.CoreV1().ResourceQuotas(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update resource quota: %s", err) - } - log.Printf("[INFO] Submitted updated resource quota: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - if waitForChangedSpec { - err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { - quota, err := conn.CoreV1().ResourceQuotas(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return resource.NonRetryableError(err) - } - if resourceListEquals(spec.Hard, quota.Status.Hard) { - return nil - } - err = fmt.Errorf("Quotas don't match after update.\nExpected: %#v\nGiven: %#v", - spec.Hard, quota.Status.Hard) - return resource.RetryableError(err) - }) - if err != nil { - return err - } - } - - return resourceKubernetesResourceQuotaRead(d, meta) -} - -func resourceKubernetesResourceQuotaDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting resource quota: %#v", name) - err = conn.CoreV1().ResourceQuotas(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Resource quota %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesResourceQuotaExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking resource quota %s", name) - _, err = conn.CoreV1().ResourceQuotas(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_role.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_role.go deleted file mode 100644 index ed7f92d93eb..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_role.go +++ /dev/null @@ -1,255 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - v1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesRole() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesRoleCreate, - Read: resourceKubernetesRoleRead, - Exists: resourceKubernetesRoleExists, - Update: resourceKubernetesRoleUpdate, - Delete: resourceKubernetesRoleDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchemaRBAC("role", true, true), - "rule": { - Type: schema.TypeList, - Description: "Rule defining a set of permissions for the role", - Required: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "api_groups": { - Type: schema.TypeSet, - Description: "Name of the APIGroup that contains the resources", - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "resources": { - Type: schema.TypeSet, - Description: "List of resources that the rule applies to", - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "resource_names": { - Type: schema.TypeSet, - Description: "White list of names that the rule applies to", - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "verbs": { - Type: schema.TypeSet, - Description: "List of Verbs that apply to ALL the ResourceKinds and AttributeRestrictions contained in this rule", - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesRoleCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - rules := expandRules(d.Get("rule").([]interface{})) - - role := v1.Role{ - ObjectMeta: metadata, - Rules: *rules, - } - log.Printf("[INFO] Creating new role: %#v", role) - out, err := conn.RbacV1().Roles(metadata.Namespace).Create(ctx, &role, metav1.CreateOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Submitted new role: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesRoleRead(d, meta) -} - -func resourceKubernetesRoleRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading role %s", name) - role, err := conn.RbacV1().Roles(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - - log.Printf("[INFO] Received role: %#v", role) - err = d.Set("metadata", flattenMetadata(role.ObjectMeta, d)) - if err != nil { - return err - } - - err = d.Set("rule", flattenRules(&role.Rules)) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesRoleUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("rule") { - rules := expandRules(d.Get("rule").([]interface{})) - - ops = append(ops, &ReplaceOperation{ - Path: "/rules", - Value: rules, - }) - } - - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating role %q: %v", name, string(data)) - out, err := conn.RbacV1().Roles(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update role: %s", err) - } - log.Printf("[INFO] Submitted updated role: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesRoleRead(d, meta) -} - -func resourceKubernetesRoleDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting role: %#v", name) - err = conn.RbacV1().Roles(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Role %s deleted", name) - - return nil -} - -func resourceKubernetesRoleExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking role %s", name) - _, err = conn.RbacV1().Roles(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if errors.IsNotFound(err) { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} - -func expandRules(rules []interface{}) *[]v1.PolicyRule { - var objects []v1.PolicyRule - - for _, rule := range rules { - in := rule.(map[string]interface{}) - obj := v1.PolicyRule{} - if v, ok := in["api_groups"].(*schema.Set); ok && v.Len() > 0 { - obj.APIGroups = sliceOfString(v.List()) - } - if v, ok := in["resources"].(*schema.Set); ok && v.Len() > 0 { - obj.Resources = sliceOfString(v.List()) - } - if v, ok := in["resource_names"].(*schema.Set); ok && v.Len() > 0 { - obj.ResourceNames = sliceOfString(v.List()) - } - if v, ok := in["verbs"].(*schema.Set); ok && v.Len() > 0 { - obj.Verbs = sliceOfString(v.List()) - } - objects = append(objects, obj) - } - - return &objects -} - -func flattenRules(in *[]v1.PolicyRule) []interface{} { - var flattened []interface{} - for _, rule := range *in { - att := make(map[string]interface{}) - if len(rule.APIGroups) > 0 { - att["api_groups"] = newStringSet(schema.HashString, rule.APIGroups) - } - if len(rule.Resources) > 0 { - att["resources"] = newStringSet(schema.HashString, rule.Resources) - } - if len(rule.ResourceNames) > 0 { - att["resource_names"] = newStringSet(schema.HashString, rule.ResourceNames) - } - if len(rule.Verbs) > 0 { - att["verbs"] = newStringSet(schema.HashString, rule.Verbs) - } - flattened = append(flattened, att) - } - - return flattened -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_role_binding.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_role_binding.go deleted file mode 100644 index 73217f20025..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_role_binding.go +++ /dev/null @@ -1,193 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesRoleBinding() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesRoleBindingCreate, - Read: resourceKubernetesRoleBindingRead, - Exists: resourceKubernetesRoleBindingExists, - Update: resourceKubernetesRoleBindingUpdate, - Delete: resourceKubernetesRoleBindingDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchemaRBAC("roleBinding", false, true), - "role_ref": { - Type: schema.TypeList, - Description: "RoleRef references the Role for this binding", - Required: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: rbacRoleRefSchema(), - }, - }, - "subject": { - Type: schema.TypeList, - Description: "Subjects defines the entities to bind a Role to.", - Required: true, - MinItems: 1, - Elem: &schema.Resource{ - Schema: rbacSubjectSchema(), - }, - }, - }, - } -} - -func resourceKubernetesRoleBindingCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - binding := &api.RoleBinding{ - ObjectMeta: metadata, - RoleRef: expandRBACRoleRef(d.Get("role_ref").([]interface{})), - Subjects: expandRBACSubjects(d.Get("subject").([]interface{})), - } - log.Printf("[INFO] Creating new RoleBinding: %#v", binding) - out, err := conn.RbacV1().RoleBindings(metadata.Namespace).Create(ctx, binding, metav1.CreateOptions{}) - - if err != nil { - return err - } - log.Printf("[INFO] Submitted new RoleBinding: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesRoleBindingRead(d, meta) -} - -func resourceKubernetesRoleBindingRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading RoleBinding %s", name) - binding, err := conn.RbacV1().RoleBindings(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - - log.Printf("[INFO] Received RoleBinding: %#v", binding) - err = d.Set("metadata", flattenMetadata(binding.ObjectMeta, d)) - if err != nil { - return err - } - - flattenedRef := flattenRBACRoleRef(binding.RoleRef) - log.Printf("[DEBUG] Flattened RoleBinding roleRef: %#v", flattenedRef) - err = d.Set("role_ref", flattenedRef) - if err != nil { - return err - } - - flattenedSubjects := flattenRBACSubjects(binding.Subjects) - log.Printf("[DEBUG] Flattened RoleBinding subjects: %#v", flattenedSubjects) - err = d.Set("subject", flattenedSubjects) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesRoleBindingUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("subject") { - diffOps := patchRbacSubject(d) - ops = append(ops, diffOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating RoleBinding %q: %v", name, string(data)) - out, err := conn.RbacV1().RoleBindings(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update RoleBinding: %s", err) - } - log.Printf("[INFO] Submitted updated RoleBinding: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesRoleBindingRead(d, meta) -} - -func resourceKubernetesRoleBindingDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting RoleBinding: %#v", name) - err = conn.RbacV1().RoleBindings(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] RoleBinding %s deleted", name) - - return nil -} - -func resourceKubernetesRoleBindingExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking RoleBinding %s", name) - _, err = conn.RbacV1().RoleBindings(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_secret.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_secret.go deleted file mode 100644 index 6c834784e78..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_secret.go +++ /dev/null @@ -1,192 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesSecret() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesSecretCreate, - Read: resourceKubernetesSecretRead, - Exists: resourceKubernetesSecretExists, - Update: resourceKubernetesSecretUpdate, - Delete: resourceKubernetesSecretDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("secret", true), - "data": { - Type: schema.TypeMap, - Description: "A map of the secret data.", - Optional: true, - Sensitive: true, - }, - "type": { - Type: schema.TypeString, - Description: "Type of secret", - Default: "Opaque", - Optional: true, - ForceNew: true, - }, - }, - } -} - -func resourceKubernetesSecretCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - secret := api.Secret{ - ObjectMeta: metadata, - Data: expandStringMapToByteMap(d.Get("data").(map[string]interface{})), - } - - if v, ok := d.GetOk("type"); ok { - secret.Type = api.SecretType(v.(string)) - } - - log.Printf("[INFO] Creating new secret: %#v", secret) - out, err := conn.CoreV1().Secrets(metadata.Namespace).Create(ctx, &secret, metav1.CreateOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Submitting new secret: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesSecretRead(d, meta) -} - -func resourceKubernetesSecretRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading secret %s", name) - secret, err := conn.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Received secret: %#v", secret) - err = d.Set("metadata", flattenMetadata(secret.ObjectMeta, d)) - if err != nil { - return err - } - - d.Set("data", flattenByteMapToStringMap(secret.Data)) - d.Set("type", secret.Type) - - return nil -} - -func resourceKubernetesSecretUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("data") { - oldV, newV := d.GetChange("data") - - oldV = base64EncodeStringMap(oldV.(map[string]interface{})) - newV = base64EncodeStringMap(newV.(map[string]interface{})) - - diffOps := diffStringMap("/data/", oldV.(map[string]interface{}), newV.(map[string]interface{})) - - ops = append(ops, diffOps...) - } - - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - - log.Printf("[INFO] Updating secret %q: %v", name, data) - out, err := conn.CoreV1().Secrets(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update secret: %s", err) - } - - log.Printf("[INFO] Submitting updated secret: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesSecretRead(d, meta) -} - -func resourceKubernetesSecretDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting secret: %q", name) - err = conn.CoreV1().Secrets(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Secret %s deleted", name) - - d.SetId("") - - return nil -} - -func resourceKubernetesSecretExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking secret %s", name) - _, err = conn.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_service.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_service.go deleted file mode 100644 index e544fd8ba14..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_service.go +++ /dev/null @@ -1,377 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesService() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesServiceCreate, - Read: resourceKubernetesServiceRead, - Exists: resourceKubernetesServiceExists, - Update: resourceKubernetesServiceUpdate, - Delete: resourceKubernetesServiceDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(10 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("service", true), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the behavior of a service. https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cluster_ip": { - Type: schema.TypeString, - Description: "The IP address of the service. It is usually assigned randomly by the master. If an address is specified manually and is not in use by others, it will be allocated to the service; otherwise, creation of the service will fail. `None` can be specified for headless services when proxying is not required. Ignored if type is `ExternalName`. More info: http://kubernetes.io/docs/user-guide/services#virtual-ips-and-service-proxies", - Optional: true, - ForceNew: true, - Computed: true, - }, - "external_ips": { - Type: schema.TypeSet, - Description: "A list of IP addresses for which nodes in the cluster will also accept traffic for this service. These IPs are not managed by Kubernetes. The user is responsible for ensuring that traffic arrives at a node with this IP. A common example is external load-balancers that are not part of the Kubernetes system.", - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "external_name": { - Type: schema.TypeString, - Description: "The external reference that kubedns or equivalent will return as a CNAME record for this service. No proxying will be involved. Must be a valid DNS name and requires `type` to be `ExternalName`.", - Optional: true, - }, - "external_traffic_policy": { - Type: schema.TypeString, - Description: "Denotes if this Service desires to route external traffic to node-local or cluster-wide endpoints. `Local` preserves the client source IP and avoids a second hop for LoadBalancer and Nodeport type services, but risks potentially imbalanced traffic spreading. `Cluster` obscures the client source IP and may cause a second hop to another node, but should have good overall load-spreading. More info: https://kubernetes.io/docs/tutorials/services/source-ip/", - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice([]string{"Local", "Cluster"}, false), - }, - "load_balancer_ip": { - Type: schema.TypeString, - Description: "Only applies to `type = LoadBalancer`. LoadBalancer will get created with the IP specified in this field. This feature depends on whether the underlying cloud-provider supports specifying this field when a load balancer is created. This field will be ignored if the cloud-provider does not support the feature.", - Optional: true, - }, - "load_balancer_source_ranges": { - Type: schema.TypeSet, - Description: "If specified and supported by the platform, this will restrict traffic through the cloud-provider load-balancer will be restricted to the specified client IPs. This field will be ignored if the cloud-provider does not support the feature. More info: http://kubernetes.io/docs/user-guide/services-firewalls", - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "port": { - Type: schema.TypeList, - Description: "The list of ports that are exposed by this service. More info: http://kubernetes.io/docs/user-guide/services#virtual-ips-and-service-proxies", - Optional: true, - MinItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "The name of this port within the service. All ports within the service must have unique names. Optional if only one ServicePort is defined on this service.", - Optional: true, - }, - "node_port": { - Type: schema.TypeInt, - Description: "The port on each node on which this service is exposed when `type` is `NodePort` or `LoadBalancer`. Usually assigned by the system. If specified, it will be allocated to the service if unused or else creation of the service will fail. Default is to auto-allocate a port if the `type` of this service requires one. More info: http://kubernetes.io/docs/user-guide/services#type--nodeport", - Computed: true, - Optional: true, - }, - "port": { - Type: schema.TypeInt, - Description: "The port that will be exposed by this service.", - Required: true, - }, - "protocol": { - Type: schema.TypeString, - Description: "The IP protocol for this port. Supports `TCP` and `UDP`. Default is `TCP`.", - Optional: true, - Default: "TCP", - ValidateFunc: validation.StringInSlice([]string{ - "TCP", - "UDP", - "SCTP", - }, false), - }, - "target_port": { - Type: schema.TypeString, - Description: "Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. This field is ignored for services with `cluster_ip = \"None\"`. More info: http://kubernetes.io/docs/user-guide/services#defining-a-service", - Optional: true, - Computed: true, - }, - }, - }, - }, - "publish_not_ready_addresses": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "When set to true, indicates that DNS implementations must publish the `notReadyAddresses` of subsets for the Endpoints associated with the Service. The default value is `false`. The primary use case for setting this field is to use a StatefulSet's Headless Service to propagate `SRV` records for its Pods without respect to their readiness for purpose of peer discovery.", - }, - "selector": { - Type: schema.TypeMap, - Description: "Route service traffic to pods with label keys and values matching this selector. Only applies to types `ClusterIP`, `NodePort`, and `LoadBalancer`. More info: http://kubernetes.io/docs/user-guide/services#overview", - Optional: true, - }, - "session_affinity": { - Type: schema.TypeString, - Description: "Used to maintain session affinity. Supports `ClientIP` and `None`. Defaults to `None`. More info: http://kubernetes.io/docs/user-guide/services#virtual-ips-and-service-proxies", - Optional: true, - Default: "None", - ValidateFunc: validation.StringInSlice([]string{ - "ClientIP", - "None", - }, false), - }, - "type": { - Type: schema.TypeString, - Description: "Determines how the service is exposed. Defaults to `ClusterIP`. Valid options are `ExternalName`, `ClusterIP`, `NodePort`, and `LoadBalancer`. `ExternalName` maps to the specified `external_name`. More info: http://kubernetes.io/docs/user-guide/services#overview", - Optional: true, - Default: "ClusterIP", - ValidateFunc: validation.StringInSlice([]string{ - "ClusterIP", - "ExternalName", - "NodePort", - "LoadBalancer", - }, false), - }, - "health_check_node_port": { - Type: schema.TypeInt, - Description: "Specifies the Healthcheck NodePort for the service. Only effects when type is set to `LoadBalancer` and external_traffic_policy is set to `Local`.", - Optional: true, - Computed: true, - ForceNew: true, - }, - }, - }, - }, - "load_balancer_ingress": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ip": { - Type: schema.TypeString, - Computed: true, - }, - "hostname": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesServiceCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - svc := api.Service{ - ObjectMeta: metadata, - Spec: expandServiceSpec(d.Get("spec").([]interface{})), - } - log.Printf("[INFO] Creating new service: %#v", svc) - out, err := conn.CoreV1().Services(metadata.Namespace).Create(ctx, &svc, metav1.CreateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted new service: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - if out.Spec.Type == api.ServiceTypeLoadBalancer { - log.Printf("[DEBUG] Waiting for load balancer to assign IP/hostname") - - err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { - svc, err := conn.CoreV1().Services(out.Namespace).Get(ctx, out.Name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return resource.NonRetryableError(err) - } - - lbIngress := svc.Status.LoadBalancer.Ingress - - log.Printf("[INFO] Received service status: %#v", svc.Status) - if len(lbIngress) > 0 { - return nil - } - - return resource.RetryableError(fmt.Errorf( - "Waiting for service %q to assign IP/hostname for a load balancer", d.Id())) - }) - if err != nil { - lastWarnings, wErr := getLastWarningsForObject(ctx, conn, out.ObjectMeta, "Service", 3) - if wErr != nil { - return wErr - } - return fmt.Errorf("%s%s", err, stringifyEvents(lastWarnings)) - } - } - - return resourceKubernetesServiceRead(d, meta) -} - -func resourceKubernetesServiceRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading service %s", name) - svc, err := conn.CoreV1().Services(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received service: %#v", svc) - err = d.Set("metadata", flattenMetadata(svc.ObjectMeta, d)) - if err != nil { - return err - } - - err = d.Set("load_balancer_ingress", flattenLoadBalancerIngress(svc.Status.LoadBalancer.Ingress)) - if err != nil { - return err - } - - flattened := flattenServiceSpec(svc.Spec) - log.Printf("[DEBUG] Flattened service spec: %#v", flattened) - err = d.Set("spec", flattened) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesServiceUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("spec") { - serverVersion, err := conn.ServerVersion() - if err != nil { - return err - } - diffOps, err := patchServiceSpec("spec.0.", "/spec/", d, serverVersion) - if err != nil { - return err - } - ops = append(ops, diffOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating service %q: %v", name, string(data)) - out, err := conn.CoreV1().Services(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update service: %s", err) - } - log.Printf("[INFO] Submitted updated service: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesServiceRead(d, meta) -} - -func resourceKubernetesServiceDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting service: %#v", name) - err = conn.CoreV1().Services(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - _, err := conn.CoreV1().Services(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return nil - } - return resource.NonRetryableError(err) - } - - e := fmt.Errorf("Service (%s) still exists", d.Id()) - return resource.RetryableError(e) - }) - if err != nil { - return err - } - - log.Printf("[INFO] Service %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesServiceExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking service %s", name) - _, err = conn.CoreV1().Services(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_service_account.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_service_account.go deleted file mode 100644 index ec269368fe3..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_service_account.go +++ /dev/null @@ -1,379 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - "strings" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" -) - -func resourceKubernetesServiceAccount() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesServiceAccountCreate, - Read: resourceKubernetesServiceAccountRead, - Exists: resourceKubernetesServiceAccountExists, - Update: resourceKubernetesServiceAccountUpdate, - Delete: resourceKubernetesServiceAccountDelete, - Importer: &schema.ResourceImporter{ - State: resourceKubernetesServiceAccountImportState, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Second), - }, - - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("service account", true), - "image_pull_secret": { - Type: schema.TypeSet, - Description: "A list of references to secrets in the same namespace to use for pulling any images in pods that reference this Service Account. More info: http://kubernetes.io/docs/user-guide/secrets#manually-specifying-an-imagepullsecret", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - Optional: true, - }, - }, - }, - }, - "secret": { - Type: schema.TypeSet, - Description: "A list of secrets allowed to be used by pods running using this Service Account. More info: http://kubernetes.io/docs/user-guide/secrets", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - Optional: true, - }, - }, - }, - }, - "automount_service_account_token": { - Type: schema.TypeBool, - Description: "True to enable automatic mounting of the service account token", - Optional: true, - }, - "default_secret_name": { - Type: schema.TypeString, - Computed: true, - }, - }, - } -} - -func resourceKubernetesServiceAccountCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - svcAcc := api.ServiceAccount{ - AutomountServiceAccountToken: ptrToBool(d.Get("automount_service_account_token").(bool)), - ObjectMeta: metadata, - ImagePullSecrets: expandLocalObjectReferenceArray(d.Get("image_pull_secret").(*schema.Set).List()), - Secrets: expandServiceAccountSecrets(d.Get("secret").(*schema.Set).List(), ""), - } - log.Printf("[INFO] Creating new service account: %#v", svcAcc) - out, err := conn.CoreV1().ServiceAccounts(metadata.Namespace).Create(ctx, &svcAcc, metav1.CreateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted new service account: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - secret, err := getServiceAccountDefaultSecret(ctx, out.Name, svcAcc, d.Timeout(schema.TimeoutCreate), conn) - d.Set("default_secret_name", secret.Name) - return resourceKubernetesServiceAccountRead(d, meta) -} - -func getServiceAccountDefaultSecret(ctx context.Context, name string, config api.ServiceAccount, timeout time.Duration, conn *kubernetes.Clientset) (*api.Secret, error) { - var svcAccTokens []api.Secret - err := resource.Retry(timeout, func() *resource.RetryError { - resp, err := conn.CoreV1().ServiceAccounts(config.Namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return resource.NonRetryableError(err) - } - - if len(resp.Secrets) == len(config.Secrets) { - log.Printf("[DEBUG] Configuration contains %d secrets, saw %d, expected %d", len(config.Secrets), len(resp.Secrets), len(config.Secrets)+1) - return resource.RetryableError(fmt.Errorf("Waiting for default secret of %q to appear", buildId(resp.ObjectMeta))) - } - - diff := diffObjectReferences(config.Secrets, resp.Secrets) - secretList, err := conn.CoreV1().Secrets(config.Namespace).List(ctx, metav1.ListOptions{ - FieldSelector: fmt.Sprintf("type=%s", api.SecretTypeServiceAccountToken), - }) - for _, secret := range secretList.Items { - for _, svcSecret := range diff { - if secret.Name != svcSecret.Name { - continue - } - svcAccTokens = append(svcAccTokens, secret) - } - } - - if len(svcAccTokens) == 0 { - return resource.RetryableError(fmt.Errorf("Expected 1 generated service account token, %d found", len(svcAccTokens))) - } - - if len(svcAccTokens) > 1 { - return resource.NonRetryableError(fmt.Errorf("Expected 1 generated service account token, %d found: %s", len(svcAccTokens), err)) - } - - return nil - }) - if err != nil { - return nil, err - } - - return &svcAccTokens[0], nil -} - -func findDefaultServiceAccount(ctx context.Context, sa *api.ServiceAccount, conn *kubernetes.Clientset) (string, error) { - /* - The default service account token secret would have: - - been created either at the same moment as the service account or _just_ after (Kubernetes controllers appears to work off a queue) - - have a name starting with "[service account name]-token-" - - See this for where the default token is created in Kubernetes - https://github.com/kubernetes/kubernetes/blob/release-1.13/pkg/controller/serviceaccount/tokens_controller.go#L384 - */ - for _, saSecret := range sa.Secrets { - if !strings.HasPrefix(saSecret.Name, fmt.Sprintf("%s-token-", sa.Name)) { - log.Printf("[DEBUG] Skipping %s as it doesn't have the right name", saSecret.Name) - continue - } - - secret, err := conn.CoreV1().Secrets(sa.Namespace).Get(ctx, saSecret.Name, metav1.GetOptions{}) - if err != nil { - return "", fmt.Errorf("Unable to fetch secret %s/%s from Kubernetes: %s", sa.Namespace, saSecret.Name, err) - } - - if secret.Type != api.SecretTypeServiceAccountToken { - log.Printf("[DEBUG] Skipping %s as it is of the wrong type", saSecret.Name) - continue - } - - if secret.CreationTimestamp.Before(&sa.CreationTimestamp) { - log.Printf("[DEBUG] Skipping %s as it existed before the service account", saSecret.Name) - continue - } - - if secret.CreationTimestamp.Sub(sa.CreationTimestamp.Time) > (3 * time.Second) { - log.Printf("[DEBUG] Skipping %s as it wasn't created at the same time as the service account", saSecret.Name) - continue - } - - log.Printf("[DEBUG] Found %s as a candidate for the default service account token", saSecret.Name) - - return saSecret.Name, nil - } - - return "", fmt.Errorf("Unable to find any service accounts tokens which could have been the default one") -} - -func diffObjectReferences(origOrs []api.ObjectReference, ors []api.ObjectReference) []api.ObjectReference { - var diff []api.ObjectReference - uniqueRefs := make(map[string]*api.ObjectReference, 0) - for _, or := range origOrs { - uniqueRefs[or.Name] = &or - } - - for _, or := range ors { - _, found := uniqueRefs[or.Name] - if !found { - diff = append(diff, or) - } - } - - return diff -} - -func resourceKubernetesServiceAccountRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Reading service account %s", name) - svcAcc, err := conn.CoreV1().ServiceAccounts(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received service account: %#v", svcAcc) - err = d.Set("metadata", flattenMetadata(svcAcc.ObjectMeta, d)) - if err != nil { - return err - } - - if svcAcc.AutomountServiceAccountToken == nil { - err = d.Set("automount_service_account_token", false) - if err != nil { - return err - } - } else { - err = d.Set("automount_service_account_token", *svcAcc.AutomountServiceAccountToken) - if err != nil { - return err - } - } - d.Set("image_pull_secret", flattenLocalObjectReferenceArray(svcAcc.ImagePullSecrets)) - - defaultSecretName := d.Get("default_secret_name").(string) - log.Printf("[DEBUG] Default secret name is %q", defaultSecretName) - secrets := flattenServiceAccountSecrets(svcAcc.Secrets, defaultSecretName) - log.Printf("[DEBUG] Flattened secrets: %#v", secrets) - d.Set("secret", secrets) - - return nil -} - -func resourceKubernetesServiceAccountUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - ops := patchMetadata("metadata.0.", "/metadata/", d) - if d.HasChange("image_pull_secret") { - v := d.Get("image_pull_secret").(*schema.Set).List() - ops = append(ops, &ReplaceOperation{ - Path: "/imagePullSecrets", - Value: expandLocalObjectReferenceArray(v), - }) - } - if d.HasChange("secret") { - v := d.Get("secret").(*schema.Set).List() - defaultSecretName := d.Get("default_secret_name").(string) - - ops = append(ops, &ReplaceOperation{ - Path: "/secrets", - Value: expandServiceAccountSecrets(v, defaultSecretName), - }) - } - if d.HasChange("automount_service_account_token") { - v := d.Get("automount_service_account_token").(bool) - ops = append(ops, &ReplaceOperation{ - Path: "/automountServiceAccountToken", - Value: v, - }) - } - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating service account %q: %v", name, string(data)) - out, err := conn.CoreV1().ServiceAccounts(namespace).Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update service account: %s", err) - } - log.Printf("[INFO] Submitted updated service account: %#v", out) - d.SetId(buildId(out.ObjectMeta)) - - return resourceKubernetesServiceAccountRead(d, meta) -} - -func resourceKubernetesServiceAccountDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return err - } - - log.Printf("[INFO] Deleting service account: %#v", name) - err = conn.CoreV1().ServiceAccounts(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Service account %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesServiceAccountExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking service account %s", name) - _, err = conn.CoreV1().ServiceAccounts(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} - -func resourceKubernetesServiceAccountImportState(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return nil, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return nil, fmt.Errorf("Unable to parse identifier %s: %s", d.Id(), err) - } - - sa, err := conn.CoreV1().ServiceAccounts(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return nil, fmt.Errorf("Unable to fetch service account from Kubernetes: %s", err) - } - defaultSecret, err := findDefaultServiceAccount(ctx, sa, conn) - if err != nil { - return nil, fmt.Errorf("Failed to discover the default service account token: %s", err) - } - - err = d.Set("default_secret_name", defaultSecret) - if err != nil { - return nil, fmt.Errorf("Unable to set default_secret_name: %s", err) - } - d.SetId(buildId(sa.ObjectMeta)) - - return []*schema.ResourceData{d}, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_stateful_set.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_stateful_set.go deleted file mode 100644 index dc8e7f03038..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_stateful_set.go +++ /dev/null @@ -1,280 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - appsv1 "k8s.io/api/apps/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - kubernetes "k8s.io/client-go/kubernetes" - polymorphichelpers "k8s.io/kubectl/pkg/polymorphichelpers" -) - -func resourceKubernetesStatefulSet() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesStatefulSetCreate, - Read: resourceKubernetesStatefulSetRead, - Update: resourceKubernetesStatefulSetUpdate, - Delete: resourceKubernetesStatefulSetDelete, - Exists: resourceKubernetesStatefulSetExists, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - Schema: map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("stateful set", true), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the desired identities of pods in this set.", - Required: true, - MaxItems: 1, - MinItems: 1, - ForceNew: true, - Elem: &schema.Resource{ - Schema: statefulSetSpecFields(false), - }, - }, - "wait_for_rollout": { - Type: schema.TypeBool, - Description: "Wait for the rollout of the stateful set to complete. Defaults to false.", - Default: false, - Optional: true, - }, - }, - } -} - -func resourceKubernetesStatefulSetCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandStatefulSetSpec(d.Get("spec").([]interface{})) - if err != nil { - return err - } - statefulSet := appsv1.StatefulSet{ - ObjectMeta: metadata, - Spec: *spec, - } - log.Printf("[INFO] Creating new StatefulSet: %#v", statefulSet) - - out, err := conn.AppsV1().StatefulSets(metadata.Namespace).Create(ctx, &statefulSet, metav1.CreateOptions{}) - - if err != nil { - return err - } - log.Printf("[INFO] Submitted new StatefulSet: %#v", out) - - id := buildId(out.ObjectMeta) - d.SetId(id) - - log.Printf("[INFO] StatefulSet %s created", id) - - if d.Get("wait_for_rollout").(bool) { - log.Printf("[INFO] Waiting for StatefulSet %s to rollout", id) - namespace := out.ObjectMeta.Namespace - name := out.ObjectMeta.Name - return resource.Retry(d.Timeout(schema.TimeoutCreate), - retryUntilStatefulSetRolloutComplete(ctx, conn, namespace, name)) - } - - return resourceKubernetesStatefulSetRead(d, meta) -} - -func resourceKubernetesStatefulSetExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return false, err - } - - log.Printf("[INFO] Checking StatefulSet %s", name) - _, err = conn.AppsV1().StatefulSets(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if errors.IsNotFound(err) { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} - -func resourceKubernetesStatefulSetRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - id := d.Id() - namespace, name, err := idParts(id) - if err != nil { - return fmt.Errorf("Error parsing resource ID: %#v", err) - } - log.Printf("[INFO] Reading stateful set %s", id) - statefulSet, err := conn.AppsV1().StatefulSets(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - switch { - case errors.IsNotFound(err): - log.Printf("[DEBUG] Stateful Set %q was not found in Namespace %q - removing from state!", namespace, name) - d.SetId("") - return nil - default: - log.Printf("[DEBUG] Error reading stateful set: %#v", err) - return err - } - } - log.Printf("[INFO] Received stateful set: %#v", statefulSet) - if d.Set("metadata", flattenMetadata(statefulSet.ObjectMeta, d)) != nil { - return fmt.Errorf("Error setting `metadata`: %+v", err) - } - sss, err := flattenStatefulSetSpec(statefulSet.Spec, d) - if err != nil { - return fmt.Errorf("Error flattening `spec`: %+v", err) - } - err = d.Set("spec", sss) - if err != nil { - return fmt.Errorf("Error setting `spec`: %+v", err) - } - return nil -} - -func resourceKubernetesStatefulSetUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return fmt.Errorf("Error parsing resource ID: %#v", err) - } - ops := patchMetadata("metadata.0.", "/metadata/", d) - - if d.HasChange("spec") { - log.Println("[TRACE] StatefulSet.Spec has changes") - specPatch, err := patchStatefulSetSpec(d) - if err != nil { - return err - } - ops = append(ops, specPatch...) - } - - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations for StatefulSet: %s", err) - } - log.Printf("[INFO] Updating StatefulSet %q: %v", name, string(data)) - out, err := conn.AppsV1().StatefulSets(namespace).Patch(ctx, name, types.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update StatefulSet: %s", err) - } - log.Printf("[INFO] Submitted updated StatefulSet: %#v", out) - - if d.Get("wait_for_rollout").(bool) { - log.Printf("[INFO] Waiting for StatefulSet %s to rollout", d.Id()) - return resource.Retry(d.Timeout(schema.TimeoutCreate), - retryUntilStatefulSetRolloutComplete(ctx, conn, namespace, name)) - } - - return resourceKubernetesStatefulSetRead(d, meta) -} - -func resourceKubernetesStatefulSetDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - namespace, name, err := idParts(d.Id()) - if err != nil { - return fmt.Errorf("Error parsing resource ID: %#v", err) - } - log.Printf("[INFO] Deleting StatefulSet: %#v", name) - err = conn.AppsV1().StatefulSets(namespace).Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - out, err := conn.AppsV1().StatefulSets(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - switch { - case errors.IsNotFound(err): - return nil - default: - return resource.NonRetryableError(err) - } - } - - log.Printf("[DEBUG] Current state of StatefulSet: %#v", out.Status.Conditions) - e := fmt.Errorf("StatefulSet %s still exists %#v", name, out.Status.Conditions) - return resource.RetryableError(e) - }) - if err != nil { - return err - } - - log.Printf("[INFO] StatefulSet %s deleted", name) - - return nil -} - -// retryUntilStatefulSetRolloutComplete checks if a given job finished its execution and is either in 'Complete' or 'Failed' state. -func retryUntilStatefulSetRolloutComplete(ctx context.Context, conn *kubernetes.Clientset, ns, name string) resource.RetryFunc { - return func() *resource.RetryError { - res, err := conn.AppsV1().StatefulSets(ns).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return resource.NonRetryableError(err) - } - - // NOTE: This is what kubectl uses to determine if a rollout is done. - // We are using this here because the logic for determining if a StatefulSet - // is done is gnarly and we don't want to duplicate it in the provider. - gvk := appsv1.SchemeGroupVersion.WithKind("StatefulSet") - gk := gvk.GroupKind() - statusViewer, err := polymorphichelpers.StatusViewerFor(gk) - if err != nil { - return resource.NonRetryableError(err) - } - - obj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(res) - if err != nil { - return resource.NonRetryableError(err) - } - - // NOTE: For some reason, the Kind and apiVersion get lost when converting to unstructured. - obj["apiVersion"] = gvk.GroupVersion().String() - obj["kind"] = gvk.Kind - u := unstructured.Unstructured{Object: obj} - - // NOTE: the revision parameter of the Status function below is not actually used. - // for StatefulSet so it is set to 0 here - _, done, err := statusViewer.Status(&u, 0) - if err != nil { - return resource.NonRetryableError(err) - } - - if done { - return nil - } - - return resource.RetryableError(fmt.Errorf("StatefulSet %s/%s is not finished rolling out", ns, name)) - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_storage_class.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_storage_class.go deleted file mode 100644 index 4dd89baf9b4..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_storage_class.go +++ /dev/null @@ -1,202 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - v1 "k8s.io/api/core/v1" - api "k8s.io/api/storage/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -func resourceKubernetesStorageClass() *schema.Resource { - return &schema.Resource{ - Create: resourceKubernetesStorageClassCreate, - Read: resourceKubernetesStorageClassRead, - Exists: resourceKubernetesStorageClassExists, - Update: resourceKubernetesStorageClassUpdate, - Delete: resourceKubernetesStorageClassDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("storage class", true), - "parameters": { - Type: schema.TypeMap, - Description: "The parameters for the provisioner that should create volumes of this storage class", - Optional: true, - ForceNew: true, - }, - "storage_provisioner": { - Type: schema.TypeString, - Description: "Indicates the type of the provisioner", - Required: true, - ForceNew: true, - }, - "reclaim_policy": { - Type: schema.TypeString, - Description: "Indicates the type of the reclaim policy", - Optional: true, - Default: "Delete", - }, - "volume_binding_mode": { - Type: schema.TypeString, - Description: "Indicates when volume binding and dynamic provisioning should occur", - Optional: true, - ForceNew: true, - Default: "Immediate", - }, - "allow_volume_expansion": { - Type: schema.TypeBool, - Description: "Indicates whether the storage class allow volume expand", - Optional: true, - Default: true, - }, - "mount_options": { - Type: schema.TypeSet, - Description: "Persistent Volumes that are dynamically created by a storage class will have the mount options specified", - Optional: true, - ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - }, - } -} - -func resourceKubernetesStorageClassCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - reclaimPolicy := v1.PersistentVolumeReclaimPolicy(d.Get("reclaim_policy").(string)) - volumeBindingMode := api.VolumeBindingMode(d.Get("volume_binding_mode").(string)) - allowVolumeExpansion := d.Get("allow_volume_expansion").(bool) - storageClass := api.StorageClass{ - ObjectMeta: metadata, - Provisioner: d.Get("storage_provisioner").(string), - ReclaimPolicy: &reclaimPolicy, - VolumeBindingMode: &volumeBindingMode, - AllowVolumeExpansion: &allowVolumeExpansion, - } - - if v, ok := d.GetOk("parameters"); ok { - storageClass.Parameters = expandStringMap(v.(map[string]interface{})) - } - - if v, ok := d.GetOk("mount_options"); ok { - storageClass.MountOptions = schemaSetToStringArray(v.(*schema.Set)) - } - - log.Printf("[INFO] Creating new storage class: %#v", storageClass) - out, err := conn.StorageV1().StorageClasses().Create(ctx, &storageClass, metav1.CreateOptions{}) - if err != nil { - return err - } - log.Printf("[INFO] Submitted new storage class: %#v", out) - d.SetId(out.Name) - - return resourceKubernetesStorageClassRead(d, meta) -} - -func resourceKubernetesStorageClassRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Reading storage class %s", name) - storageClass, err := conn.StorageV1().StorageClasses().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return err - } - log.Printf("[INFO] Received storage class: %#v", storageClass) - err = d.Set("metadata", flattenMetadata(storageClass.ObjectMeta, d)) - if err != nil { - return err - } - d.Set("parameters", storageClass.Parameters) - d.Set("storage_provisioner", storageClass.Provisioner) - d.Set("reclaim_policy", storageClass.ReclaimPolicy) - d.Set("volume_binding_mode", storageClass.VolumeBindingMode) - d.Set("mount_options", newStringSet(schema.HashString, storageClass.MountOptions)) - if storageClass.AllowVolumeExpansion != nil { - d.Set("allow_volume_expansion", *storageClass.AllowVolumeExpansion) - } - - return nil -} - -func resourceKubernetesStorageClassUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - ops := patchMetadata("metadata.0.", "/metadata/", d) - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating storage class %q: %v", name, string(data)) - out, err := conn.StorageV1().StorageClasses().Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return fmt.Errorf("Failed to update storage class: %s", err) - } - log.Printf("[INFO] Submitted updated storage class: %#v", out) - d.SetId(out.ObjectMeta.Name) - - return resourceKubernetesStorageClassRead(d, meta) -} - -func resourceKubernetesStorageClassDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Deleting storage class: %#v", name) - err = conn.StorageV1().StorageClasses().Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - return err - } - - log.Printf("[INFO] Storage class %s deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesStorageClassExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - name := d.Id() - log.Printf("[INFO] Checking storage class %s", name) - _, err = conn.StorageV1().StorageClasses().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_validating_webhook_configuration.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_validating_webhook_configuration.go deleted file mode 100644 index 5d111bd5c1c..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/resource_kubernetes_validating_webhook_configuration.go +++ /dev/null @@ -1,319 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - - copier "github.com/jinzhu/copier" -) - -func resourceKubernetesValidatingWebhookConfiguration() *schema.Resource { - apiDoc := admissionregistrationv1.ValidatingWebhookConfiguration{}.SwaggerDoc() - webhookDoc := admissionregistrationv1.ValidatingWebhook{}.SwaggerDoc() - return &schema.Resource{ - Create: resourceKubernetesValidatingWebhookConfigurationCreate, - Read: resourceKubernetesValidatingWebhookConfigurationRead, - Exists: resourceKubernetesValidatingWebhookConfigurationExists, - Update: resourceKubernetesValidatingWebhookConfigurationUpdate, - Delete: resourceKubernetesValidatingWebhookConfigurationDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("validating webhook configuration", true), - "webhook": { - Type: schema.TypeList, - Description: apiDoc["webhooks"], - Required: true, - MinItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "admission_review_versions": { - Type: schema.TypeList, - Description: webhookDoc["admissionReviewVersions"], - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "client_config": { - Type: schema.TypeList, - Description: webhookDoc["clientConfig"], - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: webhookClientConfigFields(), - }, - }, - "failure_policy": { - Type: schema.TypeString, - Description: webhookDoc["failurePolicy"], - Optional: true, - Default: "Fail", - }, - "match_policy": { - Type: schema.TypeString, - Description: webhookDoc["matchPolicy"], - Optional: true, - Default: "Equivalent", - }, - "name": { - Type: schema.TypeString, - Description: webhookDoc["name"], - Required: true, - }, - "namespace_selector": { - Type: schema.TypeList, - Description: webhookDoc["namespaceSelector"], - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - "object_selector": { - Type: schema.TypeList, - Description: webhookDoc["objectSelector"], - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - "rule": { - Type: schema.TypeList, - Description: webhookDoc["rules"], - Required: true, - MinItems: 1, - Elem: &schema.Resource{ - Schema: ruleWithOperationsFields(), - }, - }, - "side_effects": { - Type: schema.TypeString, - Description: webhookDoc["sideEffects"], - Optional: true, - }, - "timeout_seconds": { - Type: schema.TypeInt, - Description: webhookDoc["timeoutSeconds"], - Default: 10, - Optional: true, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesValidatingWebhookConfigurationCreate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - cfg := admissionregistrationv1.ValidatingWebhookConfiguration{ - ObjectMeta: expandMetadata(d.Get("metadata").([]interface{})), - Webhooks: expandValidatingWebhooks(d.Get("webhook").([]interface{})), - } - - log.Printf("[INFO] Creating new ValidatingWebhookConfiguration: %#v", cfg) - - res := &admissionregistrationv1.ValidatingWebhookConfiguration{} - - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return err - } - if useadmissionregistrationv1beta1 { - requestv1beta1 := &admissionregistrationv1beta1.ValidatingWebhookConfiguration{} - responsev1beta1 := &admissionregistrationv1beta1.ValidatingWebhookConfiguration{} - copier.Copy(requestv1beta1, cfg) - responsev1beta1, err = conn.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().Create(ctx, requestv1beta1, metav1.CreateOptions{}) - copier.Copy(res, responsev1beta1) - } else { - res, err = conn.AdmissionregistrationV1().ValidatingWebhookConfigurations().Create(ctx, &cfg, metav1.CreateOptions{}) - } - - if err != nil { - return err - } - - log.Printf("[INFO] Submitted new ValidatingWebhookConfiguration: %#v", res) - - d.SetId(res.Name) - - return resourceKubernetesValidatingWebhookConfigurationRead(d, meta) -} - -func resourceKubernetesValidatingWebhookConfigurationRead(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - cfg := &admissionregistrationv1.ValidatingWebhookConfiguration{} - - log.Printf("[INFO] Reading ValidatingWebhookConfiguration %s", name) - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return err - } - if useadmissionregistrationv1beta1 { - cfgv1beta1 := &admissionregistrationv1beta1.ValidatingWebhookConfiguration{} - cfgv1beta1, err = conn.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().Get(ctx, name, metav1.GetOptions{}) - copier.Copy(cfg, cfgv1beta1) - } else { - cfg, err = conn.AdmissionregistrationV1().ValidatingWebhookConfigurations().Get(ctx, name, metav1.GetOptions{}) - } - if err != nil { - return err - } - - err = d.Set("metadata", flattenMetadata(cfg.ObjectMeta, d)) - if err != nil { - return nil - } - - log.Printf("[DEBUG] Setting webhook to: %#v", cfg.Webhooks) - - err = d.Set("webhook", flattenValidatingWebhooks(cfg.Webhooks)) - if err != nil { - return err - } - - return nil -} - -func resourceKubernetesValidatingWebhookConfigurationUpdate(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - ops := patchMetadata("metadata.0.", "/metadata/", d) - - if d.HasChange("webhook") { - op := &ReplaceOperation{ - Path: "/webhooks", - } - - patch := expandValidatingWebhooks(d.Get("webhook").([]interface{})) - - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return err - } - if useadmissionregistrationv1beta1 { - patchv1beta1 := []admissionregistrationv1beta1.ValidatingWebhook{} - copier.Copy(&patchv1beta1, &patch) - op.Value = patchv1beta1 - } else { - op.Value = patch - } - - ops = append(ops, op) - } - - data, err := ops.MarshalJSON() - if err != nil { - return fmt.Errorf("Failed to marshal update operations: %s", err) - } - - name := d.Id() - log.Printf("[INFO] Updating ValidatingWebhookCoßnfiguration %q: %v", name, string(data)) - - res := &admissionregistrationv1.ValidatingWebhookConfiguration{} - - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return err - } - if useadmissionregistrationv1beta1 { - responsev1beta1 := &admissionregistrationv1beta1.ValidatingWebhookConfiguration{} - responsev1beta1, err = conn.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().Patch(ctx, name, types.JSONPatchType, data, metav1.PatchOptions{}) - copier.Copy(res, responsev1beta1) - } else { - res, err = conn.AdmissionregistrationV1().ValidatingWebhookConfigurations().Patch(ctx, name, types.JSONPatchType, data, metav1.PatchOptions{}) - } - if err != nil { - return fmt.Errorf("Failed to update ValidatingWebhookConfiguration: %s", err) - } - - log.Printf("[INFO] Submitted updated ValidatingWebhookConfiguration: %#v", res) - - return resourceKubernetesValidatingWebhookConfigurationRead(d, meta) -} - -func resourceKubernetesValidatingWebhookConfigurationDelete(d *schema.ResourceData, meta interface{}) error { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Deleting ValidatingWebhookConfiguration: %#v", name) - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return err - } - if useadmissionregistrationv1beta1 { - err = conn.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().Delete(ctx, name, metav1.DeleteOptions{}) - } else { - err = conn.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(ctx, name, metav1.DeleteOptions{}) - } - if err != nil { - return err - } - - log.Printf("[INFO] ValidatingWebhookConfiguration %#v is deleted", name) - - d.SetId("") - return nil -} - -func resourceKubernetesValidatingWebhookConfigurationExists(d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - ctx := context.TODO() - - name := d.Id() - - log.Printf("[INFO] Checking ValidatingWebhookConfiguration %s", name) - - useadmissionregistrationv1beta1, err := useAdmissionregistrationV1beta1(conn) - if err != nil { - return false, err - } - if useadmissionregistrationv1beta1 { - _, err = conn.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().Get(ctx, name, metav1.GetOptions{}) - } else { - _, err = conn.AdmissionregistrationV1().ValidatingWebhookConfigurations().Get(ctx, name, metav1.GetOptions{}) - } - - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { - return false, nil - } - return false, err - } - - return true, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_affinity_spec.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_affinity_spec.go deleted file mode 100644 index 3569bc1ba5c..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_affinity_spec.go +++ /dev/null @@ -1,192 +0,0 @@ -package kubernetes - -import ( - "regexp" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" -) - -func affinityFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "node_affinity": { - Type: schema.TypeList, - Description: "Node affinity scheduling rules for the pod.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: nodeAffinityFields(), - }, - }, - "pod_affinity": { - Type: schema.TypeList, - Description: "Inter-pod topological affinity. rules that specify that certain pods should be placed in the same topological domain (e.g. same node, same rack, same zone, same power domain, etc.)", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: podAffinityFields(), - }, - }, - "pod_anti_affinity": { - Type: schema.TypeList, - Description: "Inter-pod topological affinity. rules that specify that certain pods should be placed in the same topological domain (e.g. same node, same rack, same zone, same power domain, etc.)", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: podAffinityFields(), - }, - }, - } -} - -func nodeAffinityFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "required_during_scheduling_ignored_during_execution": { - Type: schema.TypeList, - Description: "If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a node label update), the system may or may not try to eventually evict the pod from its node.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: nodeSelectorFields(), - }, - }, - "preferred_during_scheduling_ignored_during_execution": { - Type: schema.TypeList, - Description: "The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, RequiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding 'weight' to the sum if the node matches the corresponding MatchExpressions; the node(s) with the highest sum are the most preferred.", - Optional: true, - Elem: &schema.Resource{ - Schema: preferredSchedulingTermFields(), - }, - }, - } -} - -func nodeSelectorFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "node_selector_term": { - Type: schema.TypeList, - Description: "List of node selector terms. The terms are ORed.", - Optional: true, - Elem: &schema.Resource{ - Schema: nodeSelectorRequirementsFields(), - }, - }, - } -} - -func preferredSchedulingTermFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "weight": { - Type: schema.TypeInt, - Description: "weight is in the range 1-100", - Required: true, - }, - "preference": { - Type: schema.TypeList, - Description: "A node selector term, associated with the corresponding weight.", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: nodeSelectorRequirementsFields(), - }, - }, - } -} - -func nodeSelectorRequirementsFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "match_expressions": { - Type: schema.TypeList, - Description: "List of node selector requirements. The requirements are ANDed.", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, - Description: "The label key that the selector applies to.", - Optional: true, - }, - "operator": { - Type: schema.TypeString, - Description: "Operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt.", - Optional: true, - ValidateFunc: validation.StringInSlice([]string{"In", "NotIn", "Exists", "DoesNotExist", "Gt", "Lt"}, false), - }, - "values": { - Type: schema.TypeSet, - Description: "Values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. This array is replaced during a strategic merge patch.", - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - }, - }, - }, - } -} - -func podAffinityFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "required_during_scheduling_ignored_during_execution": { - Type: schema.TypeList, - Description: "If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a pod label update), the system may or may not try to eventually evict the pod from its node. When there are multiple elements, the lists of nodes corresponding to each PodAffinityTerm are intersected, i.e. all terms must be satisfied.", - Optional: true, - Elem: &schema.Resource{ - Schema: podAffinityTermFields(), - }, - }, - "preferred_during_scheduling_ignored_during_execution": { - Type: schema.TypeList, - Description: "The scheduler will prefer to schedule pods to nodes that satisfy the anti-affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, RequiredDuringScheduling anti-affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding 'weight' to the sum if the node matches the corresponding MatchExpressions; the node(s) with the highest sum are the most preferred.", - Optional: true, - Elem: &schema.Resource{ - Schema: weightedPodAffinityTermFields(), - }, - }, - } -} - -func podAffinityTermFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "label_selector": { - Type: schema.TypeList, - Description: "A label query over a set of resources, in this case pods.", - Optional: true, - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - "namespaces": { - Type: schema.TypeSet, - Description: "namespaces specifies which namespaces the labelSelector applies to (matches against); null or empty list means 'this pod's namespace'", - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "topology_key": { - Type: schema.TypeString, - Description: "empty topology key is interpreted by the scheduler as 'all topologies'", - Optional: true, - ValidateFunc: validation.StringMatch(regexp.MustCompile(`^.+$`), "value cannot be empty"), - }, - } -} - -func weightedPodAffinityTermFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "weight": { - Type: schema.TypeInt, - Description: "weight associated with matching the corresponding podAffinityTerm, in the range 1-100", - Required: true, - }, - "pod_affinity_term": { - Type: schema.TypeList, - Description: "A pod affinity term, associated with the corresponding weight", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: podAffinityTermFields(), - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_backend_spec.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_backend_spec.go deleted file mode 100644 index b2650bccacc..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_backend_spec.go +++ /dev/null @@ -1,32 +0,0 @@ -package kubernetes - -import "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - -const defaultBackendDescription = `A default backend capable of servicing requests that don't match any rule. At least one of 'backend' or 'rules' must be specified. This field is optional to allow the loadbalancer controller or defaulting logic to specify a global default.` -const ruleBackedDescription = `Backend defines the referenced service endpoint to which the traffic will be forwarded to.` - -func backendSpecFields(description string) *schema.Schema { - s := &schema.Schema{ - Type: schema.TypeList, - Description: description, - MaxItems: 1, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "service_name": { - Type: schema.TypeString, - Description: "Specifies the name of the referenced service.", - Optional: true, - }, - "service_port": { - Type: schema.TypeString, - Description: "Specifies the port of the referenced service.", - Computed: true, - Optional: true, - }, - }, - }, - } - - return s -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_container.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_container.go deleted file mode 100644 index c85cfdc7813..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_container.go +++ /dev/null @@ -1,685 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" -) - -func handlerFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "exec": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "exec specifies the action to take.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "command": { - Type: schema.TypeList, - Description: `Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.`, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }, - }, - }, - "http_get": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Specifies the http request to perform.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "host": { - Type: schema.TypeString, - Optional: true, - Description: `Host name to connect to, defaults to the pod IP. You probably want to set "Host" in httpHeaders instead.`, - }, - "path": { - Type: schema.TypeString, - Optional: true, - Description: `Path to access on the HTTP server.`, - }, - "scheme": { - Type: schema.TypeString, - Optional: true, - Default: "HTTP", - Description: `Scheme to use for connecting to the host.`, - }, - "port": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validatePortNumOrName, - Description: `Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.`, - }, - "http_header": { - Type: schema.TypeList, - Optional: true, - Description: `Scheme to use for connecting to the host.`, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Optional: true, - Description: "The header field name", - }, - "value": { - Type: schema.TypeString, - Optional: true, - Description: "The header field value", - }, - }, - }, - }, - }, - }, - }, - "tcp_socket": { - Type: schema.TypeList, - Optional: true, - Description: "TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "port": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validatePortNumOrName, - Description: "Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.", - }, - }, - }, - }, - } -} - -func resourcesField() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "limits": { - Type: schema.TypeList, - Optional: true, - Computed: true, - MaxItems: 1, - Description: "Describes the maximum amount of compute resources allowed. More info: http://kubernetes.io/docs/user-guide/compute-resources/", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cpu": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validateResourceQuantity, - DiffSuppressFunc: suppressEquivalentResourceQuantity, - }, - "memory": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validateResourceQuantity, - DiffSuppressFunc: suppressEquivalentResourceQuantity, - }, - }, - }, - }, - "requests": { - Type: schema.TypeList, - Optional: true, - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cpu": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validateResourceQuantity, - DiffSuppressFunc: suppressEquivalentResourceQuantity, - }, - "memory": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validateResourceQuantity, - DiffSuppressFunc: suppressEquivalentResourceQuantity, - }, - }, - }, - }, - } -} - -func seLinuxOptionsField() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "level": { - Type: schema.TypeString, - Optional: true, - Description: "Level is SELinux level label that applies to the container.", - }, - "role": { - Type: schema.TypeString, - Optional: true, - Description: "Role is a SELinux role label that applies to the container.", - }, - "type": { - Type: schema.TypeString, - Optional: true, - Description: "Type is a SELinux type label that applies to the container.", - }, - "user": { - Type: schema.TypeString, - Optional: true, - Description: "User is a SELinux user label that applies to the container.", - }, - } -} - -func volumeMountFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "mount_path": { - Type: schema.TypeString, - Required: true, - Description: "Path within the container at which the volume should be mounted. Must not contain ':'.", - }, - "name": { - Type: schema.TypeString, - Required: true, - Description: "This must match the Name of a Volume.", - }, - "read_only": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.", - }, - "sub_path": { - Type: schema.TypeString, - Optional: true, - Description: `Path within the volume from which the container's volume should be mounted. Defaults to "" (volume's root).`, - }, - "mount_propagation": { - Type: schema.TypeString, - Description: "Mount propagation mode. mount_propagation determines how mounts are propagated from the host to container and the other way around. Valid values are None (default), HostToContainer and Bidirectional.", - Optional: true, - Default: "None", - ValidateFunc: validation.StringInSlice([]string{"None", "HostToContainer", "Bidirectional"}, false), - }, - } -} - -func containerFields(isUpdatable, isInitContainer bool) map[string]*schema.Schema { - s := map[string]*schema.Schema{ - "args": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Description: "Arguments to the entrypoint. The docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers#containers-and-commands", - }, - "command": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Description: "Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers#containers-and-commands", - }, - "env": { - Type: schema.TypeList, - Optional: true, - Description: "List of environment variables to set in the container. Cannot be updated.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - Description: "Name of the environment variable. Must be a C_IDENTIFIER", - }, - "value": { - Type: schema.TypeString, - ForceNew: !isUpdatable, - Optional: true, - Description: `Variable references $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Defaults to "".`, - }, - "value_from": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Source for the environment variable's value", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "config_map_key_ref": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Selects a key of a ConfigMap.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, - Optional: true, - Description: "The key to select.", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - }, - "optional": { - Type: schema.TypeBool, - Optional: true, - Description: "Specify whether the ConfigMap or its key must be defined.", - }, - }, - }, - }, - "field_ref": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.podIP.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "api_version": { - Type: schema.TypeString, - Optional: true, - Default: "v1", - Description: `Version of the schema the FieldPath is written in terms of, defaults to "v1".`, - }, - "field_path": { - Type: schema.TypeString, - Optional: true, - Description: "Path of the field to select in the specified API version", - }, - }, - }, - }, - "resource_field_ref": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, limits.ephemeral-storage, requests.cpu, requests.memory and requests.ephemeral-storage) are currently supported.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "container_name": { - Type: schema.TypeString, - Optional: true, - }, - "resource": { - Type: schema.TypeString, - Required: true, - Description: "Resource to select", - }, - }, - }, - }, - "secret_key_ref": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Selects a key of a secret in the pod's namespace.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, - Optional: true, - Description: "The key of the secret to select from. Must be a valid secret key.", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - }, - "optional": { - Type: schema.TypeBool, - Optional: true, - Description: "Specify whether the Secret or its key must be defined.", - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - "env_from": { - Type: schema.TypeList, - Optional: true, - Description: "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "config_map_ref": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "The ConfigMap to select from", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - }, - "optional": { - Type: schema.TypeBool, - Optional: true, - Description: "Specify whether the ConfigMap must be defined", - }, - }, - }, - }, - "prefix": { - Type: schema.TypeString, - Optional: true, - Description: "An optional identifer to prepend to each key in the ConfigMap. Must be a C_IDENTIFIER.", - }, - "secret_ref": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "The Secret to select from", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - }, - "optional": { - Type: schema.TypeBool, - Optional: true, - Description: "Specify whether the Secret must be defined", - }, - }, - }, - }, - }, - }, - }, - "image": { - Type: schema.TypeString, - Optional: true, - Description: "Docker image name. More info: http://kubernetes.io/docs/user-guide/images", - }, - "image_pull_policy": { - Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/images#updating-images", - }, - "lifecycle": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Actions that the management system should take in response to container lifecycle events", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "post_start": { - Type: schema.TypeList, - Description: `post_start is called immediately after a container is created. If the handler fails, the container is terminated and restarted according to its restart policy. Other management of the container blocks until the hook completes. More info: http://kubernetes.io/docs/user-guide/container-environment#hook-details`, - Optional: true, - Elem: &schema.Resource{ - Schema: handlerFields(), - }, - }, - "pre_stop": { - Type: schema.TypeList, - Description: `pre_stop is called immediately before a container is terminated. The container is terminated after the handler completes. The reason for termination is passed to the handler. Regardless of the outcome of the handler, the container is eventually terminated. Other management of the container blocks until the hook completes. More info: http://kubernetes.io/docs/user-guide/container-environment#hook-details`, - Optional: true, - Elem: &schema.Resource{ - Schema: handlerFields(), - }, - }, - }, - }, - }, - "liveness_probe": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes", - Elem: probeSchema(), - }, - "name": { - Type: schema.TypeString, - Required: true, - Description: "Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated.", - }, - "port": { - Type: schema.TypeList, - Optional: true, - Description: `List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default "0.0.0.0" address inside a container will be accessible from the network. Cannot be updated.`, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "container_port": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validatePortNumOrName, - Description: "Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536.", - }, - "host_ip": { - Type: schema.TypeString, - Optional: true, - Description: "What host IP to bind the external port to.", - }, - "host_port": { - Type: schema.TypeInt, - Optional: true, - Description: "Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this.", - }, - "name": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validatePortNumOrName, - Description: "If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services", - }, - "protocol": { - Type: schema.TypeString, - Optional: true, - Description: `Protocol for port. Must be UDP or TCP. Defaults to "TCP".`, - Default: "TCP", - }, - }, - }, - }, - "readiness_probe": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes", - Elem: probeSchema(), - }, - "resources": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Computed: true, - Description: "Compute Resources required by this container. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#resources", - Elem: &schema.Resource{ - Schema: resourcesField(), - }, - }, - "security_context": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Security options the pod should run with. More info: http://releases.k8s.io/HEAD/docs/design/security_context.md", - Elem: securityContextSchema(), - }, - "startup_probe": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "StartupProbe indicates that the Pod has successfully initialized. If specified, no other probes are executed until this completes successfully. If this probe fails, the Pod will be restarted, just as if the livenessProbe failed. This can be used to provide different probe parameters at the beginning of a Pod's lifecycle, when it might take a long time to load data or warm a cache, than during steady-state operation. This cannot be updated. This is an alpha feature enabled by the StartupProbe feature flag. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Elem: probeSchema(), - }, - "stdin": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. ", - }, - "stdin_once": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF.", - }, - "termination_message_path": { - Type: schema.TypeString, - Optional: true, - Default: "/dev/termination-log", - Description: "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Defaults to /dev/termination-log. Cannot be updated.", - }, - "termination_message_policy": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice([]string{"File", "FallbackToLogsOnError"}, false), - Computed: true, - Description: "Optional: Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.", - }, - "tty": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "Whether this container should allocate a TTY for itself", - }, - "volume_mount": { - Type: schema.TypeList, - Optional: true, - Computed: true, - Description: "Pod volumes to mount into the container's filesystem. Cannot be updated.", - Elem: &schema.Resource{ - Schema: volumeMountFields(), - }, - }, - "working_dir": { - Type: schema.TypeString, - Optional: true, - Description: "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", - }, - } - - if !isUpdatable { - for k := range s { - if k == "image" && !isInitContainer { - // this field is updatable for non-init containers - continue - } - s[k].ForceNew = true - } - } - - return s -} - -func probeSchema() *schema.Resource { - h := handlerFields() - h["failure_threshold"] = &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - Description: "Minimum consecutive failures for the probe to be considered failed after having succeeded.", - Default: 3, - ValidateFunc: validatePositiveInteger, - } - h["initial_delay_seconds"] = &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - Description: "Number of seconds after the container has started before liveness probes are initiated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes", - } - h["period_seconds"] = &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - Default: 10, - ValidateFunc: validatePositiveInteger, - Description: "How often (in seconds) to perform the probe", - } - h["success_threshold"] = &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - Default: 1, - ValidateFunc: validatePositiveInteger, - Description: "Minimum consecutive successes for the probe to be considered successful after having failed.", - } - - h["timeout_seconds"] = &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - Default: 1, - ValidateFunc: validatePositiveInteger, - Description: "Number of seconds after which the probe times out. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes", - } - return &schema.Resource{ - Schema: h, - } - -} - -func securityContextSchema() *schema.Resource { - m := map[string]*schema.Schema{ - "allow_privilege_escalation": { - Type: schema.TypeBool, - Optional: true, - Default: true, - Description: `AllowPrivilegeEscalation controls whether a process can gain more privileges than its parent process. This bool directly controls if the no_new_privs flag will be set on the container process. AllowPrivilegeEscalation is true always when the container is: 1) run as Privileged 2) has CAP_SYS_ADMIN`, - }, - "capabilities": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "The capabilities to add/drop when running containers. Defaults to the default set of capabilities granted by the container runtime.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "add": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Description: "Added capabilities", - }, - "drop": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Description: "Removed capabilities", - }, - }, - }, - }, - "privileged": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: `Run container in privileged mode. Processes in privileged containers are essentially equivalent to root on the host. Defaults to false.`, - }, - "read_only_root_filesystem": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "Whether this container has a read-only root filesystem. Default is false.", - }, - "run_as_group": { - Type: schema.TypeInt, - Description: "The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - Optional: true, - }, - "run_as_non_root": { - Type: schema.TypeBool, - Description: "Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - Optional: true, - }, - "run_as_user": { - Type: schema.TypeInt, - Description: "The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - Optional: true, - }, - "se_linux_options": { - Type: schema.TypeList, - Description: "The SELinux context to be applied to the container. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: seLinuxOptionsField(), - }, - }, - } - - return &schema.Resource{ - Schema: m, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_cron_job_spec.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_cron_job_spec.go deleted file mode 100644 index 9896c42b21e..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_cron_job_spec.go +++ /dev/null @@ -1,88 +0,0 @@ -package kubernetes - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/robfig/cron" -) - -func cronJobSpecFields() map[string]*schema.Schema { - s := map[string]*schema.Schema{ - "concurrency_policy": { - Type: schema.TypeString, - Optional: true, - Default: "Allow", - ValidateFunc: validation.StringInSlice([]string{"Allow", "Forbid", "Replace"}, false), - Description: "Specifies how to treat concurrent executions of a Job. Defaults to Allow.", - }, - "failed_jobs_history_limit": { - Type: schema.TypeInt, - Optional: true, - Default: 1, - Description: "The number of failed finished jobs to retain. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.", - }, - "job_template": { - Type: schema.TypeList, - Description: "Describes the pod that will be created when executing a cron job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("jobTemplateSpec", true), - "spec": { - Type: schema.TypeList, - Description: "Specification of the desired behavior of the job", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: jobSpecFields(), - }, - }, - }, - }, - }, - "schedule": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validateCronExpression(), - Description: "Cron format string, e.g. 0 * * * * or @hourly, as schedule time of its jobs to be created and executed.", - }, - "starting_deadline_seconds": { - Type: schema.TypeInt, - Optional: true, - Default: 0, - Description: "Optional deadline in seconds for starting the job if it misses scheduled time for any reason. Missed jobs executions will be counted as failed ones.", - }, - "successful_jobs_history_limit": { - Type: schema.TypeInt, - Optional: true, - Default: 3, - Description: "The number of successful finished jobs to retain. Defaults to 3.", - }, - "suspend": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "This flag tells the controller to suspend subsequent executions, it does not apply to already started executions. Defaults to false.", - }, - } - - return s -} - -func validateCronExpression() schema.SchemaValidateFunc { - return func(i interface{}, k string) (s []string, es []error) { - v, ok := i.(string) - if !ok { - es = append(es, fmt.Errorf("expected type of '%s' to be string", k)) - return - } - _, err := cron.ParseStandard(v) - if err != nil { - es = append(es, fmt.Errorf("'%s' should be an valid Cron expression", k)) - } - return - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_endpoints.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_endpoints.go deleted file mode 100644 index 0ea21999011..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_endpoints.go +++ /dev/null @@ -1,93 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -func schemaEndpointsSubset() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - "address": { - Type: schema.TypeSet, - Description: "IP address which offers the related ports that are marked as ready. These endpoints should be considered safe for load balancers and clients to utilize.", - Optional: true, - MinItems: 1, - Elem: schemaEndpointsSubsetAddress(), - Set: hashEndpointsSubsetAddress(), - }, - "not_ready_address": { - Type: schema.TypeSet, - Description: "IP address which offers the related ports but is not currently marked as ready because it have not yet finished starting, have recently failed a readiness check, or have recently failed a liveness check.", - Optional: true, - MinItems: 1, - Elem: schemaEndpointsSubsetAddress(), - Set: hashEndpointsSubsetAddress(), - }, - "port": { - Type: schema.TypeSet, - Description: "Port number available on the related IP addresses.", - Optional: true, - MinItems: 1, - Elem: schemaEndpointsSubsetPort(), - Set: hashEndpointsSubsetPort(), - }, - }, - } -} - -func hashEndpointsSubset() schema.SchemaSetFunc { - return schema.HashResource(schemaEndpointsSubset()) -} - -func schemaEndpointsSubsetAddress() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ip": { - Type: schema.TypeString, - Description: "The IP of this endpoint. May not be loopback (127.0.0.0/8), link-local (169.254.0.0/16), or link-local multicast ((224.0.0.0/24).", - Required: true, - }, - "hostname": { - Type: schema.TypeString, - Description: "The Hostname of this endpoint.", - Optional: true, - }, - "node_name": { - Type: schema.TypeString, - Description: "Node hosting this endpoint. This can be used to determine endpoints local to a node.", - Optional: true, - }, - }, - } -} - -func hashEndpointsSubsetAddress() schema.SchemaSetFunc { - return schema.HashResource(schemaEndpointsSubsetAddress()) -} - -func schemaEndpointsSubsetPort() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "The name of this port within the endpoint. Must be a DNS_LABEL. Optional if only one Port is defined on this endpoint.", - Optional: true, - }, - "port": { - Type: schema.TypeInt, - Description: "The port that will be exposed by this endpoint.", - Required: true, - }, - "protocol": { - Type: schema.TypeString, - Description: "The IP protocol for this port. Supports `TCP` and `UDP`. Default is `TCP`.", - Optional: true, - Default: "TCP", - }, - }, - } -} - -func hashEndpointsSubsetPort() schema.SchemaSetFunc { - return schema.HashResource(schemaEndpointsSubsetPort()) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_helpers.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_helpers.go deleted file mode 100644 index 86a22c057dc..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_helpers.go +++ /dev/null @@ -1,9 +0,0 @@ -package kubernetes - -func conditionalDefault(condition bool, defaultValue interface{}) interface{} { - if !condition { - return nil - } - - return defaultValue -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_horizontal_pod_autoscaler.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_horizontal_pod_autoscaler.go deleted file mode 100644 index 5cfcfb5b229..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_horizontal_pod_autoscaler.go +++ /dev/null @@ -1,201 +0,0 @@ -package kubernetes - -import "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - -func metricTargetFields() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - "average_utilization": { - Type: schema.TypeInt, - Optional: true, - Description: "averageUtilization is the target value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods. Currently only valid for Resource metric source type", - }, - "average_value": { - Type: schema.TypeString, - Optional: true, - Description: "averageValue is the target value of the average of the metric across all relevant pods (as a quantity)", - }, - "type": { - Type: schema.TypeString, - Required: true, - Description: "type represents whether the metric type is Utilization, Value, or AverageValue", - }, - "value": { - Type: schema.TypeString, - Optional: true, - Description: "value is the target value of the metric (as a quantity).", - }, - }, - } -} - -func resourceMetricSourceFields() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - Description: "name is the name of the resource in question.", - }, - "target": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: metricTargetFields(), - Description: "Target specifies the target value for the given metric", - }, - }, - } -} - -func metricIdentifierFields() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - Description: "name is the name of the given metric", - }, - "selector": { - Type: schema.TypeList, - Optional: true, - Description: "selector is the string-encoded form of a standard kubernetes label selector for the given metric When set, it is passed as an additional parameter to the metrics server for more specific metrics scoping. When unset, just the metricName will be used to gather metrics.", - Elem: &schema.Resource{ - Schema: labelSelectorFields(true), - }, - }, - }, - } -} - -func podsMetricSourceFields() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - "metric": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: metricIdentifierFields(), - Description: "metric identifies the target metric by name and selector", - }, - "target": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: metricTargetFields(), - Description: "target specifies the target value for the given metric", - }, - }, - } -} - -func externalMetricSourceFields() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - "metric": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: metricIdentifierFields(), - Description: "metric identifies the target metric by name and selector", - }, - "target": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: metricTargetFields(), - Description: "target specifies the target value for the given metric", - }, - }, - } -} - -func crossVersionObjectReferenceFields() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - "api_version": { - Type: schema.TypeString, - Required: true, - Description: "API version of the referent", - }, - "kind": { - Type: schema.TypeString, - Required: true, - Description: "Kind of the referent; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - }, - "name": { - Type: schema.TypeString, - Required: true, - Description: "Name of the referent; More info: http://kubernetes.io/docs/user-guide/identifiers#names", - }, - }, - } -} - -func objectMetricSourceFields() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - "described_object": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: crossVersionObjectReferenceFields(), - // NOTE Description is undocumented in K8s API docs - }, - "metric": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: metricIdentifierFields(), - Description: "metric identifies the target metric by name and selector", - }, - "target": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: metricTargetFields(), - Description: "target specifies the target value for the given metric", - }, - }, - } -} - -func metricSpecFields() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - "external": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: externalMetricSourceFields(), - Description: "", - }, - "object": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: objectMetricSourceFields(), - Description: "", - }, - "pods": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: podsMetricSourceFields(), - Description: "", - }, - "resource": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: resourceMetricSourceFields(), - Description: "", - }, - "type": { - Type: schema.TypeString, - Required: true, - Description: `type is the type of metric source. It should be one of "Object", "Pods", "External" or "Resource", each mapping to a matching field in the object.`, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_job_spec.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_job_spec.go deleted file mode 100644 index cb6ef8da172..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_job_spec.go +++ /dev/null @@ -1,140 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -func jobMetadataSchema() *schema.Schema { - m := namespacedMetadataSchema("job", true) - mr := m.Elem.(*schema.Resource) - mr.Schema["labels"].Computed = true - return m -} - -func jobSpecFields() map[string]*schema.Schema { - podTemplateFields := map[string]*schema.Schema{ - "metadata": metadataSchema("job", true), - "spec": { - Type: schema.TypeList, - Description: "Spec of the pods owned by the job", - Optional: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: podSpecFields(false, false, false), - }, - }, - } - // Job and CronJob don't support "Always" as a value for "restart_policy" in Pod templates. - // This changes the default value of "restart_policy" to "Never" - // as expected by Job and CronJob resources. - podTemplateFieldsSpecSchema := podTemplateFields["spec"].Elem.(*schema.Resource) - restartPolicy := podTemplateFieldsSpecSchema.Schema["restart_policy"] - restartPolicy.Default = "Never" - - s := map[string]*schema.Schema{ - "active_deadline_seconds": { - Type: schema.TypeInt, - Optional: true, - ForceNew: true, - ValidateFunc: validatePositiveInteger, - Description: "Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer.", - }, - "backoff_limit": { - Type: schema.TypeInt, - Optional: true, - ForceNew: true, - ValidateFunc: validateNonNegativeInteger, - Description: "Specifies the number of retries before marking this job failed. Defaults to 6", - }, - "completions": { - Type: schema.TypeInt, - Optional: true, - ForceNew: true, - Default: 1, - ValidateFunc: validatePositiveInteger, - Description: "Specifies the desired number of successfully finished pods the job should be run with. Setting to nil means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value. Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/", - }, - "manual_selector": { - Type: schema.TypeBool, - Optional: true, - ForceNew: true, - Description: "Controls generation of pod labels and pod selectors. Leave unset unless you are certain what you are doing. When false or unset, the system pick labels unique to this job and appends those labels to the pod template. When true, the user is responsyble for picking unique labels and specifying the selector. Failure to pick a unique label may cause this and other jobs to not function correctly. More info: https://git.k8s.io/community/contributors/design-proposals/selector-generation.md", - }, - "parallelism": { - Type: schema.TypeInt, - Optional: true, - ForceNew: true, - Default: 1, - ValidateFunc: validatePositiveInteger, - Description: "Specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/", - }, - "selector": { - Type: schema.TypeList, - Description: "A label query over volumes to consider for binding.", - Optional: true, - ForceNew: true, - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "match_expressions": { - Type: schema.TypeList, - Description: "A list of label selector requirements. The requirements are ANDed.", - Optional: true, - ForceNew: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, - Description: "The label key that the selector applies to.", - Optional: true, - ForceNew: true, - }, - "operator": { - Type: schema.TypeString, - Description: "A key's relationship to a set of values. Valid operators ard `In`, `NotIn`, `Exists` and `DoesNotExist`.", - Optional: true, - ForceNew: true, - }, - "values": { - Type: schema.TypeSet, - Description: "An array of string values. If the operator is `In` or `NotIn`, the values array must be non-empty. If the operator is `Exists` or `DoesNotExist`, the values array must be empty. This array is replaced during a strategic merge patch.", - Optional: true, - ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - }, - }, - }, - "match_labels": { - Type: schema.TypeMap, - Description: "A map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of `match_expressions`, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.", - Optional: true, - ForceNew: true, - }, - }, - }, - }, - "template": { - Type: schema.TypeList, - Description: "Describes the pod that will be created when executing a job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/", - Required: true, - MaxItems: 1, - ForceNew: true, - Elem: &schema.Resource{ - Schema: podTemplateFields, - }, - }, - "ttl_seconds_after_finished": { - Type: schema.TypeInt, - Optional: true, - ForceNew: true, - ValidateFunc: validateNonNegativeInteger, - Description: "ttlSecondsAfterFinished limits the lifetime of a Job that has finished execution (either Complete or Failed). If this field is set, ttlSecondsAfterFinished after the Job finishes, it is eligible to be automatically deleted. When the Job is being deleted, its lifecycle guarantees (e.g. finalizers) will be honored. If this field is unset, the Job won't be automatically deleted. If this field is set to zero, the Job becomes eligible to be deleted immediately after it finishes.", - }, - } - - return s -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_label_selector.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_label_selector.go deleted file mode 100644 index b50fc3c3af6..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_label_selector.go +++ /dev/null @@ -1,46 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -func labelSelectorFields(updatable bool) map[string]*schema.Schema { - return map[string]*schema.Schema{ - "match_expressions": { - Type: schema.TypeList, - Description: "A list of label selector requirements. The requirements are ANDed.", - Optional: true, - ForceNew: !updatable, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, - Description: "The label key that the selector applies to.", - Optional: true, - ForceNew: !updatable, - }, - "operator": { - Type: schema.TypeString, - Description: "A key's relationship to a set of values. Valid operators ard `In`, `NotIn`, `Exists` and `DoesNotExist`.", - Optional: true, - ForceNew: !updatable, - }, - "values": { - Type: schema.TypeSet, - Description: "An array of string values. If the operator is `In` or `NotIn`, the values array must be non-empty. If the operator is `Exists` or `DoesNotExist`, the values array must be empty. This array is replaced during a strategic merge patch.", - Optional: true, - ForceNew: !updatable, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - }, - }, - }, - "match_labels": { - Type: schema.TypeMap, - Description: "A map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of `match_expressions`, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.", - Optional: true, - ForceNew: !updatable, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_metadata.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_metadata.go deleted file mode 100644 index 5fdcccea433..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_metadata.go +++ /dev/null @@ -1,121 +0,0 @@ -package kubernetes - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -func metadataFields(objectName string) map[string]*schema.Schema { - return map[string]*schema.Schema{ - "annotations": { - Type: schema.TypeMap, - Description: fmt.Sprintf("An unstructured key value map stored with the %s that may be used to store arbitrary metadata. More info: http://kubernetes.io/docs/user-guide/annotations", objectName), - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - ValidateFunc: validateAnnotations, - }, - "generation": { - Type: schema.TypeInt, - Description: "A sequence number representing a specific generation of the desired state.", - Computed: true, - }, - "labels": { - Type: schema.TypeMap, - Description: fmt.Sprintf("Map of string keys and values that can be used to organize and categorize (scope and select) the %s. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels", objectName), - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - ValidateFunc: validateLabels, - }, - "name": { - Type: schema.TypeString, - Description: fmt.Sprintf("Name of the %s, must be unique. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names", objectName), - Optional: true, - ForceNew: true, - Computed: true, - ValidateFunc: validateName, - }, - "resource_version": { - Type: schema.TypeString, - Description: fmt.Sprintf("An opaque value that represents the internal version of this %s that can be used by clients to determine when %s has changed. Read more: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", objectName, objectName), - Computed: true, - }, - "self_link": { - Type: schema.TypeString, - Description: fmt.Sprintf("A URL representing this %s.", objectName), - Computed: true, - }, - "uid": { - Type: schema.TypeString, - Description: fmt.Sprintf("The unique in time and space value for this %s. More info: http://kubernetes.io/docs/user-guide/identifiers#uids", objectName), - Computed: true, - }, - } -} - -func metadataSchema(objectName string, generatableName bool) *schema.Schema { - fields := metadataFields(objectName) - - if generatableName { - fields["generate_name"] = &schema.Schema{ - Type: schema.TypeString, - Description: "Prefix, used by the server, to generate a unique name ONLY IF the `name` field has not been provided. This value will also be combined with a unique suffix. Read more: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#idempotency", - Optional: true, - ForceNew: true, - ValidateFunc: validateGenerateName, - ConflictsWith: []string{"metadata.0.name"}, - } - fields["name"].ConflictsWith = []string{"metadata.0.generate_name"} - } - - return &schema.Schema{ - Type: schema.TypeList, - Description: fmt.Sprintf("Standard %s's metadata. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata", objectName), - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: fields, - }, - } -} - -func metadataSchemaForceNew(s *schema.Schema) *schema.Schema { - s.ForceNew = true - return s -} - -func namespacedMetadataSchema(objectName string, generatableName bool) *schema.Schema { - return namespacedMetadataSchemaIsTemplate(objectName, generatableName, false) -} - -func namespacedMetadataSchemaIsTemplate(objectName string, generatableName, isTemplate bool) *schema.Schema { - fields := metadataFields(objectName) - fields["namespace"] = &schema.Schema{ - Type: schema.TypeString, - Description: fmt.Sprintf("Namespace defines the space within which name of the %s must be unique.", objectName), - Optional: true, - ForceNew: true, - Default: conditionalDefault(!isTemplate, "default"), - } - if generatableName { - fields["generate_name"] = &schema.Schema{ - Type: schema.TypeString, - Description: "Prefix, used by the server, to generate a unique name ONLY IF the `name` field has not been provided. This value will also be combined with a unique suffix. Read more: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#idempotency", - Optional: true, - ForceNew: true, - ValidateFunc: validateGenerateName, - ConflictsWith: []string{"metadata.name"}, - } - fields["name"].ConflictsWith = []string{"metadata.generate_name"} - } - - return &schema.Schema{ - Type: schema.TypeList, - Description: fmt.Sprintf("Standard %s's metadata. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata", objectName), - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: fields, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_node_selector_term.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_node_selector_term.go deleted file mode 100644 index 71645642dfc..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_node_selector_term.go +++ /dev/null @@ -1,53 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -func nodeSelectorRequirementFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, - Description: "The label key that the selector applies to.", - Required: true, - ForceNew: true, - }, - "operator": { - Type: schema.TypeString, - Description: "A key's relationship to a set of values. Valid operators ard `In`, `NotIn`, `Exists`, `DoesNotExist`, `Gt`, and `Lt`.", - Required: true, - ForceNew: true, - }, - "values": { - Type: schema.TypeSet, - Description: "An array of string values. If the operator is `In` or `NotIn`, the values array must be non-empty. If the operator is `Exists` or `DoesNotExist`, the values array must be empty. This array is replaced during a strategic merge patch.", - Optional: true, - ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - } -} - -func nodeSelectorTermFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "match_expressions": { - Type: schema.TypeList, - Description: "A list of node selector requirements by node's labels. The requirements are ANDed.", - Optional: true, - ForceNew: true, - Elem: &schema.Resource{ - Schema: nodeSelectorRequirementFields(), - }, - }, - "match_fields": { - Type: schema.TypeList, - Description: "A list of node selector requirements by node's fields. The requirements are ANDed.", - Optional: true, - ForceNew: true, - Elem: &schema.Resource{ - Schema: nodeSelectorRequirementFields(), - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_persistent_volume_claim.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_persistent_volume_claim.go deleted file mode 100644 index 0472d6f89e9..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_persistent_volume_claim.go +++ /dev/null @@ -1,87 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" -) - -func persistentVolumeClaimFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "metadata": namespacedMetadataSchema("persistent volume claim", true), - "spec": { - Type: schema.TypeList, - Description: "Spec defines the desired characteristics of a volume requested by a pod author. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#persistentvolumeclaims", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: persistentVolumeClaimSpecFields(), - }, - }, - } -} - -func persistentVolumeClaimSpecFields() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "access_modes": { - Type: schema.TypeSet, - Description: "A set of the desired access modes the volume should have. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#access-modes-1", - Required: true, - ForceNew: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: validation.StringInSlice([]string{ - "ReadWriteOnce", - "ReadOnlyMany", - "ReadWriteMany", - }, false), - }, - Set: schema.HashString, - }, - "resources": { - Type: schema.TypeList, - Description: "A list of the minimum resources the volume should have. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#resources", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "limits": { - Type: schema.TypeMap, - Description: "Map describing the maximum amount of compute resources allowed. More info: http://kubernetes.io/docs/user-guide/compute-resources/", - Optional: true, - ForceNew: true, - }, - // This is the only field the API will allow modifying in-place, so ForceNew is not used. - "requests": { - Type: schema.TypeMap, - Description: "Map describing the minimum amount of compute resources required. If this is omitted for a container, it defaults to `limits` if that is explicitly specified, otherwise to an implementation-defined value. More info: http://kubernetes.io/docs/user-guide/compute-resources/", - Optional: true, - }, - }, - }, - }, - "selector": { - Type: schema.TypeList, - Description: "A label query over volumes to consider for binding.", - Optional: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(false), - }, - }, - "volume_name": { - Type: schema.TypeString, - Description: "The binding reference to the PersistentVolume backing this claim.", - Optional: true, - ForceNew: true, - Computed: true, - }, - "storage_class_name": { - Type: schema.TypeString, - Description: "Name of the storage class requested by the claim", - Optional: true, - Computed: true, - ForceNew: true, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_pod_spec.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_pod_spec.go deleted file mode 100644 index ec02fb4ee0f..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_pod_spec.go +++ /dev/null @@ -1,897 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" -) - -func podSpecFields(isUpdatable, isDeprecated, isComputed bool) map[string]*schema.Schema { - var deprecatedMessage string - if isDeprecated { - deprecatedMessage = "This field is deprecated because template was incorrectly defined as a PodSpec preventing the definition of metadata. Please use the one under the spec field" - } - s := map[string]*schema.Schema{ - "affinity": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Optional pod scheduling constraints.", - Elem: &schema.Resource{ - Schema: affinityFields(), - }, - }, - "active_deadline_seconds": { - Type: schema.TypeInt, - Optional: true, - Computed: isComputed, - ValidateFunc: validatePositiveInteger, - Description: "Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer.", - Deprecated: deprecatedMessage, - }, - "automount_service_account_token": { - Type: schema.TypeBool, - Optional: true, - Description: "AutomountServiceAccountToken indicates whether a service account token should be automatically mounted.", - }, - "container": { - Type: schema.TypeList, - Optional: true, - Computed: isComputed, - Description: "List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers", - Deprecated: deprecatedMessage, - Elem: &schema.Resource{ - Schema: containerFields(isUpdatable, false), - }, - }, - "readiness_gate": { - Type: schema.TypeList, - Optional: true, - Computed: isComputed, - ForceNew: true, - Description: "If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://git.k8s.io/enhancements/keps/sig-network/0007-pod-ready%2B%2B.md", - Deprecated: deprecatedMessage, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "condition_type": { - Type: schema.TypeString, - Required: true, - Description: "refers to a condition in the pod's condition list with matching type.", - }, - }, - }, - }, - "init_container": { - Type: schema.TypeList, - Optional: true, - Computed: isComputed, - ForceNew: true, - Description: "List of init containers belonging to the pod. Init containers always run to completion and each must complete successfully before the next is started. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/", - Deprecated: deprecatedMessage, - Elem: &schema.Resource{ - Schema: containerFields(isUpdatable, true), - }, - }, - "dns_policy": { - Type: schema.TypeString, - Optional: true, - Computed: isComputed, - Default: conditionalDefault(!isComputed, "ClusterFirst"), - Description: "Set DNS policy for containers within the pod. Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. To have DNS options set along with hostNetwork, you have to specify DNS policy explicitly to 'ClusterFirstWithHostNet'. Optional: Defaults to 'ClusterFirst', see [Kubernetes reference](https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-s-dns-policy).", - Deprecated: deprecatedMessage, - }, - "dns_config": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy. Optional: Defaults to empty", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "nameservers": { - Type: schema.TypeList, - Description: "A list of DNS name server IP addresses. This will be appended to the base nameservers generated from DNSPolicy. Duplicated nameservers will be removed.", - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: validation.IsIPAddress, - }, - }, - "option": { - Type: schema.TypeList, - Description: "A list of DNS resolver options. This will be merged with the base options generated from DNSPolicy. Duplicated entries will be removed. Resolution options given in Options will override those that appear in the base DNSPolicy.", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "Name of the option.", - Required: true, - }, - "value": { - Type: schema.TypeString, - Description: "Value of the option. Optional: Defaults to empty.", - Optional: true, - }, - }, - }, - }, - "searches": { - Type: schema.TypeList, - Description: "A list of DNS search domains for host-name lookup. This will be appended to the base search paths generated from DNSPolicy. Duplicated search paths will be removed.", - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: validateName, - }, - }, - }, - }, - }, - "enable_service_links": { - Type: schema.TypeBool, - Optional: true, - Default: true, - Description: "Enables generating environment variables for service discovery. Optional: Defaults to true.", - }, - "host_aliases": { - Type: schema.TypeList, - Optional: true, - ForceNew: true, - Computed: isComputed, - Description: "List of hosts and IPs that will be injected into the pod's hosts file if specified. Optional: Defaults to empty.", - Deprecated: deprecatedMessage, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "hostnames": { - Type: schema.TypeList, - Required: true, - Description: "Hostnames for the IP address.", - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "ip": { - Type: schema.TypeString, - Required: true, - Description: "IP address of the host file entry.", - }, - }, - }, - }, - "host_ipc": { - Type: schema.TypeBool, - Optional: true, - Computed: isComputed, - Default: conditionalDefault(!isComputed, false), - Description: "Use the host's ipc namespace. Optional: Defaults to false.", - Deprecated: deprecatedMessage, - }, - "host_network": { - Type: schema.TypeBool, - Optional: true, - Computed: isComputed, - Default: conditionalDefault(!isComputed, false), - Description: "Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified.", - Deprecated: deprecatedMessage, - }, - - "host_pid": { - Type: schema.TypeBool, - Optional: true, - Computed: isComputed, - Default: conditionalDefault(!isComputed, false), - Description: "Use the host's pid namespace.", - Deprecated: deprecatedMessage, - }, - - "hostname": { - Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value.", - Deprecated: deprecatedMessage, - }, - "image_pull_secrets": { - Type: schema.TypeList, - Description: "ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. For example, in the case of docker, only DockerConfig type secrets are honored. More info: http://kubernetes.io/docs/user-guide/images#specifying-imagepullsecrets-on-a-pod", - Deprecated: deprecatedMessage, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - Required: true, - }, - }, - }, - }, - "node_name": { - Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements.", - Deprecated: deprecatedMessage, - }, - "node_selector": { - Type: schema.TypeMap, - Optional: true, - Computed: isComputed, - Description: "NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: http://kubernetes.io/docs/user-guide/node-selection.", - Deprecated: deprecatedMessage, - }, - "priority_class_name": { - Type: schema.TypeString, - Optional: true, - Computed: isComputed, - Description: `If specified, indicates the pod's priority. "system-node-critical" and "system-cluster-critical" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default.`, - Deprecated: deprecatedMessage, - }, - "restart_policy": { - Type: schema.TypeString, - Optional: true, - Computed: isComputed, - Default: conditionalDefault(!isComputed, "Always"), - Description: "Restart policy for all containers within the pod. One of Always, OnFailure, Never. More info: http://kubernetes.io/docs/user-guide/pod-states#restartpolicy.", - Deprecated: deprecatedMessage, - }, - "security_context": { - Type: schema.TypeList, - Optional: true, - Computed: isComputed, - MaxItems: 1, - Description: "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty", - Deprecated: deprecatedMessage, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "fs_group": { - Type: schema.TypeInt, - Description: "A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod: 1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw---- If unset, the Kubelet will not modify the ownership and permissions of any volume.", - Optional: true, - }, - "run_as_group": { - Type: schema.TypeInt, - Description: "The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.", - Optional: true, - }, - "run_as_non_root": { - Type: schema.TypeBool, - Description: "Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - Optional: true, - }, - "run_as_user": { - Type: schema.TypeInt, - Description: "The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.", - Optional: true, - }, - "se_linux_options": { - Type: schema.TypeList, - Description: "The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: seLinuxOptionsField(), - }, - }, - "supplemental_groups": { - Type: schema.TypeSet, - Description: "A list of groups applied to the first process run in each container, in addition to the container's primary GID. If unspecified, no groups will be added to any container.", - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "sysctl": { - Type: schema.TypeList, - Optional: true, - Description: "holds a list of namespaced sysctls used for the pod.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "Name of a property to set.", - Required: true, - }, - "value": { - Type: schema.TypeString, - Description: "Value of a property to set.", - Required: true, - }, - }, - }, - }, - }, - }, - }, - "service_account_name": { - Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: http://releases.k8s.io/HEAD/docs/design/service_accounts.md.", - Deprecated: deprecatedMessage, - }, - "share_process_namespace": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "Share a single process namespace between all of the containers in a pod. When this is set containers will be able to view and signal processes from other containers in the same pod, and the first process in each container will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both be set. Optional: Defaults to false.", - }, - "subdomain": { - Type: schema.TypeString, - Optional: true, - Computed: isComputed, - Description: `If specified, the fully qualified Pod hostname will be "...svc.". If not specified, the pod will not have a domainname at all..`, - Deprecated: deprecatedMessage, - }, - "termination_grace_period_seconds": { - Type: schema.TypeInt, - Optional: true, - Computed: isComputed, - Default: conditionalDefault(!isComputed, 30), - ValidateFunc: validateTerminationGracePeriodSeconds, - Description: "Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process.", - Deprecated: deprecatedMessage, - }, - "toleration": { - Type: schema.TypeList, - Optional: true, - Description: "If specified, the pod's toleration. Optional: Defaults to empty", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "effect": { - Type: schema.TypeString, - Description: "Effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute.", - Optional: true, - ValidateFunc: validation.StringInSlice([]string{"NoSchedule", "PreferNoSchedule", "NoExecute"}, false), - }, - "key": { - Type: schema.TypeString, - Description: "Key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys.", - Optional: true, - }, - "operator": { - Type: schema.TypeString, - Description: "Operator represents a key's relationship to the value. Valid operators are Exists and Equal. Defaults to Equal. Exists is equivalent to wildcard for value, so that a pod can tolerate all taints of a particular category.", - Default: "Equal", - Optional: true, - ValidateFunc: validation.StringInSlice([]string{"Exists", "Equal"}, false), - }, - "toleration_seconds": { - // Use TypeString to allow an "unspecified" value, - Type: schema.TypeString, - Description: "TolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system.", - Optional: true, - ValidateFunc: validateTypeStringNullableInt, - }, - "value": { - Type: schema.TypeString, - Description: "Value is the taint value the toleration matches to. If the operator is Exists, the value should be empty, otherwise just a regular string.", - Optional: true, - }, - }, - }, - }, - "volume": { - Type: schema.TypeList, - Optional: true, - Computed: true, - Description: "List of volumes that can be mounted by containers belonging to the pod. More info: http://kubernetes.io/docs/user-guide/volumes", - Deprecated: deprecatedMessage, - Elem: volumeSchema(isUpdatable), - }, - } - - if !isUpdatable { - for k := range s { - if k == "active_deadline_seconds" { - // This field is always updatable - continue - } - if k == "container" { - // Some fields are always updatable - continue - } - s[k].ForceNew = true - } - } - - return s -} - -func volumeSchema(isUpdatable bool) *schema.Resource { - v := commonVolumeSources() - - v["config_map"] = &schema.Schema{ - Type: schema.TypeList, - Description: "ConfigMap represents a configMap that should populate this volume", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "items": { - Type: schema.TypeList, - Description: `If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.`, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, - Optional: true, - Description: "The key to project.", - }, - "mode": { - Type: schema.TypeString, - Optional: true, - Description: `Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.`, - ValidateFunc: validateModeBits, - }, - "path": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validateAttributeValueDoesNotContain(".."), - Description: `The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.`, - }, - }, - }, - }, - "default_mode": { - Type: schema.TypeString, - Description: "Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Optional: true, - Default: "0644", - ValidateFunc: validateModeBits, - }, - "optional": { - Type: schema.TypeBool, - Description: "Optional: Specify whether the ConfigMap or its keys must be defined.", - Optional: true, - }, - "name": { - Type: schema.TypeString, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - Optional: true, - }, - }, - }, - } - - v["git_repo"] = &schema.Schema{ - Type: schema.TypeList, - Description: "GitRepo represents a git repository at a particular revision.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "directory": { - Type: schema.TypeString, - Description: "Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name.", - Optional: true, - ValidateFunc: validateAttributeValueDoesNotContain(".."), - }, - "repository": { - Type: schema.TypeString, - Description: "Repository URL", - Optional: true, - }, - "revision": { - Type: schema.TypeString, - Description: "Commit hash for the specified revision.", - Optional: true, - }, - }, - }, - } - v["downward_api"] = &schema.Schema{ - Type: schema.TypeList, - Description: "DownwardAPI represents downward API about the pod that should populate this volume", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "default_mode": { - Type: schema.TypeString, - Description: "Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Optional: true, - Default: "0644", - ValidateFunc: validateModeBits, - }, - "items": { - Type: schema.TypeList, - Description: `If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error. Paths must be relative and may not contain the '..' path or start with '..'.`, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "field_ref": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Description: "Required: Selects a field of the pod: only annotations, labels, name and namespace are supported.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "api_version": { - Type: schema.TypeString, - Optional: true, - Default: "v1", - Description: `Version of the schema the FieldPath is written in terms of, defaults to "v1".`, - }, - "field_path": { - Type: schema.TypeString, - Optional: true, - Description: "Path of the field to select in the specified API version", - }, - }, - }, - }, - "mode": { - Type: schema.TypeString, - Optional: true, - Description: `Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.`, - ValidateFunc: validateModeBits, - }, - "path": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validateAttributeValueDoesNotContain(".."), - Description: `Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'`, - }, - "resource_field_ref": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "container_name": { - Type: schema.TypeString, - Required: true, - }, - "quantity": { - Type: schema.TypeString, - Optional: true, - }, - "resource": { - Type: schema.TypeString, - Required: true, - Description: "Resource to select", - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - - v["empty_dir"] = &schema.Schema{ - Type: schema.TypeList, - Description: "EmptyDir represents a temporary directory that shares a pod's lifetime. More info: http://kubernetes.io/docs/user-guide/volumes#emptydir", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "medium": { - Type: schema.TypeString, - Description: `What type of storage medium should back this directory. The default is "" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: http://kubernetes.io/docs/user-guide/volumes#emptydir`, - Optional: true, - Default: "", - ForceNew: !isUpdatable, - ValidateFunc: validateAttributeValueIsIn([]string{"", "Memory"}), - }, - "size_limit": { - Type: schema.TypeString, - Description: `Total amount of local storage required for this EmptyDir volume.`, - Optional: true, - ForceNew: !isUpdatable, - ValidateFunc: validateResourceQuantity, - DiffSuppressFunc: suppressEquivalentResourceQuantity, - }, - }, - }, - } - - v["persistent_volume_claim"] = &schema.Schema{ - Type: schema.TypeList, - Description: "The specification of a persistent volume.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "claim_name": { - Type: schema.TypeString, - Description: "ClaimName is the name of a PersistentVolumeClaim in the same ", - Optional: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Will force the ReadOnly setting in VolumeMounts.", - Optional: true, - Default: false, - }, - }, - }, - } - - v["secret"] = &schema.Schema{ - Type: schema.TypeList, - Description: "Secret represents a secret that should populate this volume. More info: http://kubernetes.io/docs/user-guide/volumes#secrets", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "default_mode": { - Type: schema.TypeString, - Description: "Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Optional: true, - Default: "0644", - ValidateFunc: validateModeBits, - }, - "items": { - Type: schema.TypeList, - Description: "If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, - Optional: true, - Description: "The key to project.", - }, - "mode": { - Type: schema.TypeString, - Optional: true, - Description: "Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - ValidateFunc: validateModeBits, - }, - "path": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validateAttributeValueDoesNotContain(".."), - Description: "The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.", - }, - }, - }, - }, - "optional": { - Type: schema.TypeBool, - Description: "Optional: Specify whether the Secret or its keys must be defined.", - Optional: true, - }, - "secret_name": { - Type: schema.TypeString, - Description: "Name of the secret in the pod's namespace to use. More info: http://kubernetes.io/docs/user-guide/volumes#secrets", - Optional: true, - }, - }, - }, - } - v["name"] = &schema.Schema{ - Type: schema.TypeString, - Description: "Volume's name. Must be a DNS_LABEL and unique within the pod. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - Optional: true, - } - - v["projected"] = &schema.Schema{ - Type: schema.TypeList, - Description: "Projected represents a single volume that projects several volume sources into the same directory. More info: https://kubernetes.io/docs/concepts/storage/volumes/#projected", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "default_mode": { - Type: schema.TypeString, - Description: "Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Optional: true, - Default: "0644", - ValidateFunc: validateModeBits, - }, - "sources": { - Type: schema.TypeList, - Description: "Source of the volume to project in the directory.", - Required: true, - MinItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - // identical to SecretVolumeSource but without the default mode and uses a local object reference as name instead of a secret name. - "secret": &schema.Schema{ - Type: schema.TypeList, - Description: "Secret represents a secret that should populate this volume. More info: http://kubernetes.io/docs/user-guide/volumes#secrets", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "Name of the secret in the pod's namespace to use. More info: http://kubernetes.io/docs/user-guide/volumes#secrets", - Optional: true, - }, - "items": { - Type: schema.TypeList, - Description: "If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, - Optional: true, - Description: "The key to project.", - }, - "mode": { - Type: schema.TypeString, - Optional: true, - Description: "Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - ValidateFunc: validateModeBits, - }, - "path": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validateAttributeValueDoesNotContain(".."), - Description: "The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.", - }, - }, - }, - }, - "optional": { - Type: schema.TypeBool, - Description: "Optional: Specify whether the Secret or it's keys must be defined.", - Optional: true, - }, - }, - }, - }, - // identical to ConfigMapVolumeSource but without the default mode and uses a local object reference as name instead of a secret name. - "config_map": &schema.Schema{ - Type: schema.TypeList, - Description: "ConfigMap represents a configMap that should populate this volume", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - Optional: true, - }, - "items": { - Type: schema.TypeList, - Description: "If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error. Paths must be relative and may not contain the '..' path or start with '..'.", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "key": { - Type: schema.TypeString, - Optional: true, - Description: "The key to project.", - }, - "mode": { - Type: schema.TypeString, - Optional: true, - Description: "Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - ValidateFunc: validateModeBits, - }, - "path": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validateAttributeValueDoesNotContain(".."), - Description: "The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.", - }, - }, - }, - }, - "optional": { - Type: schema.TypeBool, - Description: "Optional: Specify whether the ConfigMap or it's keys must be defined.", - Optional: true, - }, - }, - }, - }, - // identical to DownwardAPIVolumeSource but without the default mode. - "downward_api": &schema.Schema{ - Type: schema.TypeList, - Description: "DownwardAPI represents downward API about the pod that should populate this volume", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "items": { - Type: schema.TypeList, - Description: "Represents a volume containing downward API info. Downward API volumes support ownership management and SELinux relabeling.", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "field_ref": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Selects a field of the pod: only annotations, labels, name and namespace are supported.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "api_version": { - Type: schema.TypeString, - Optional: true, - Default: "v1", - Description: "Version of the schema the FieldPath is written in terms of, defaults to 'v1'.", - }, - "field_path": { - Type: schema.TypeString, - Optional: true, - Description: "Path of the field to select in the specified API version", - }, - }, - }, - }, - "mode": { - Type: schema.TypeString, - Optional: true, - Description: "Mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - ValidateFunc: validateModeBits, - }, - "path": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validateAttributeValueDoesNotContain(".."), - Description: "Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'", - }, - "resource_field_ref": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "container_name": { - Type: schema.TypeString, - Required: true, - }, - "quantity": { - Type: schema.TypeString, - Optional: true, - }, - "resource": { - Type: schema.TypeString, - Required: true, - Description: "Resource to select", - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - "service_account_token": &schema.Schema{ - Type: schema.TypeList, - Description: "A projected service account token volume", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "audience": { - Type: schema.TypeString, - Description: "Audience is the intended audience of the token", - Optional: true, - }, - "expiration_seconds": { - Type: schema.TypeInt, - Optional: true, - Default: 3600, - Description: "ExpirationSeconds is the expected duration of validity of the service account token. It defaults to 1 hour and must be at least 10 minutes (600 seconds).", - ValidateFunc: validateIntGreaterThan(600), - }, - "path": { - Type: schema.TypeString, - Description: "Path specifies a relative path to the mount point of the projected volume.", - Required: true, - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - return &schema.Resource{ - Schema: v, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_pod_template.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_pod_template.go deleted file mode 100644 index ba6b170d18b..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_pod_template.go +++ /dev/null @@ -1,23 +0,0 @@ -package kubernetes - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -func podTemplateFields(owner string) map[string]*schema.Schema { - s := map[string]*schema.Schema{ - "metadata": metadataSchema(owner, true), - "spec": { - Type: schema.TypeList, - Description: fmt.Sprintf("Spec of the pods owned by the %s", owner), - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: podSpecFields(true, false, false), - }, - }, - } - return s -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_rbac.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_rbac.go deleted file mode 100644 index 8faa142312d..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_rbac.go +++ /dev/null @@ -1,127 +0,0 @@ -package kubernetes - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - pathValidation "k8s.io/apimachinery/pkg/api/validation/path" -) - -func metadataSchemaRBAC(objectName string, generatableName bool, namespaced bool) *schema.Schema { - var m *schema.Schema - if namespaced { - m = namespacedMetadataSchema(objectName, generatableName) - } else { - m = metadataSchema(objectName, generatableName) - } - metadataFields := (m.Elem.(*schema.Resource)).Schema - nameSchema := metadataFields["name"] - if nameSchema != nil { - nameSchema.ValidateFunc = validateRBACNameFunc - } - generateNameSchema := metadataFields["generate_name"] - if generateNameSchema != nil { - generateNameSchema.ValidateFunc = validateRBACNameFunc - } - return m -} - -func validateRBACNameFunc(value interface{}, key string) (ws []string, es []error) { - errors := pathValidation.IsValidPathSegmentName(value.(string)) - - if len(errors) > 0 { - for _, err := range errors { - es = append(es, fmt.Errorf("%s %s", key, err)) - } - } - return -} - -func rbacRoleRefSchema() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "api_group": { - Type: schema.TypeString, - Description: "The API group of the user. The only value possible at the moment is `rbac.authorization.k8s.io`.", - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice([]string{"rbac.authorization.k8s.io"}, false), - }, - "kind": { - Type: schema.TypeString, - Description: "The kind of resource.", - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice([]string{"Role", "ClusterRole"}, false), - }, - "name": { - Type: schema.TypeString, - Description: "The name of the User to bind to.", - ForceNew: true, - Required: true, - }, - } -} - -func rbacSubjectSchema() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "api_group": { - Type: schema.TypeString, - Description: "The API group of the subject resource.", - Optional: true, - Computed: true, - }, - "kind": { - Type: schema.TypeString, - Description: "The kind of resource.", - Required: true, - }, - "name": { - Type: schema.TypeString, - Description: "The name of the resource to bind to.", - Required: true, - }, - "namespace": { - Type: schema.TypeString, - Description: "The Namespace of the subject resource.", - Optional: true, - Default: "default", - }, - } -} - -func policyRuleSchema() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "api_groups": { - Type: schema.TypeList, - Description: "APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed.", - Optional: true, - MinItems: 1, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "non_resource_urls": { - Type: schema.TypeList, - Description: `NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"), but not both.`, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "resource_names": { - Type: schema.TypeList, - Description: "ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "resources": { - Type: schema.TypeList, - Description: "Resources is a list of resources this rule applies to. ResourceAll represents all resources.", - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "verbs": { - Type: schema.TypeList, - Description: "Verbs is a list of Verbs that apply to ALL the ResourceKinds and AttributeRestrictions contained in this rule. VerbAll represents all kinds.", - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_rule_with_operations.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_rule_with_operations.go deleted file mode 100644 index 2ee4372a5eb..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_rule_with_operations.go +++ /dev/null @@ -1,46 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" -) - -func ruleWithOperationsFields() map[string]*schema.Schema { - apiDoc := admissionregistrationv1.RuleWithOperations{}.SwaggerDoc() - return map[string]*schema.Schema{ - "api_groups": { - Type: schema.TypeList, - Description: apiDoc["apiGroups"], - Required: true, - MinItems: 1, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "api_versions": { - Type: schema.TypeList, - Description: apiDoc["apiVersions"], - Required: true, - MinItems: 1, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "operations": { - Type: schema.TypeList, - Description: apiDoc["operations"], - Required: true, - MinItems: 1, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "resources": { - Type: schema.TypeList, - Description: apiDoc["resources"], - Required: true, - MinItems: 1, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "scope": { - Type: schema.TypeString, - Description: apiDoc["scope"], - Optional: true, - Default: "*", - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_stateful_set_spec.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_stateful_set_spec.go deleted file mode 100644 index cb626c4d2d2..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_stateful_set_spec.go +++ /dev/null @@ -1,106 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" -) - -func statefulSetSpecFields(isUpdatable bool) map[string]*schema.Schema { - s := map[string]*schema.Schema{ - "pod_management_policy": { - Type: schema.TypeString, - Description: "Controls how pods are created during initial scale up, when replacing pods on nodes, or when scaling down.", - Optional: true, - ForceNew: true, - Computed: true, - ValidateFunc: validation.StringInSlice([]string{ - "OrderedReady", - "Parallel", - }, false), - }, - "replicas": { - Type: schema.TypeInt, - Optional: true, - Default: 1, - Description: "The desired number of replicas of the given Template, in the sense that they are instantiations of the same Template. Value must be a positive integer.", - ValidateFunc: validateNonNegativeInteger, - }, - "revision_history_limit": { - Type: schema.TypeInt, - Optional: true, - ForceNew: true, - Computed: true, - ValidateFunc: validatePositiveInteger, - Description: "The maximum number of revisions that will be maintained in the StatefulSet's revision history. The default value is 10.", - }, - "selector": { - Type: schema.TypeList, - Description: "A label query over pods that should match the replica count. It must match the pod template's labels.", - Required: true, - ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: labelSelectorFields(false), - }, - }, - "service_name": { - Type: schema.TypeString, - Description: "The name of the service that governs this StatefulSet. This service must exist before the StatefulSet, and is responsible for the network identity of the set.", - Required: true, - ForceNew: true, - }, - "template": { - Type: schema.TypeList, - Description: "The object that describes the pod that will be created if insufficient replicas are detected. Each pod stamped out by the StatefulSet will fulfill this Template.", - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: podTemplateFields("stateful set"), - }, - }, - "update_strategy": { - Type: schema.TypeList, - Description: "The strategy that the StatefulSet controller will use to perform updates.", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "type": { - Type: schema.TypeString, - Description: "Indicates the type of the StatefulSet update strategy. Default is RollingUpdate", - Optional: true, - Default: "RollingUpdate", - ValidateFunc: validation.StringInSlice([]string{ - "RollingUpdate", - "OnDelete", - }, false), - }, - "rolling_update": { - Type: schema.TypeList, - Description: "RollingUpdate strategy type for StatefulSet", - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "partition": { - Type: schema.TypeInt, - Optional: true, - Description: "Indicates the ordinal at which the StatefulSet should be partitioned. Default value is 0.", - Default: 0, - }, - }, - }, - }, - }, - }, - }, - "volume_claim_template": { - Type: schema.TypeList, - Optional: true, - ForceNew: true, - Description: "A list of claims that pods are allowed to reference. Every claim in this list must have at least one matching (by name) volumeMount in one container in the template.", - Elem: &schema.Resource{ - Schema: persistentVolumeClaimFields(), - }, - }, - } - return s -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_volume_source.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_volume_source.go deleted file mode 100644 index ebacde6a6a2..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_volume_source.go +++ /dev/null @@ -1,608 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" -) - -func persistentVolumeSourceSchema() *schema.Resource { - return &schema.Resource{ - Schema: commonVolumeSources(), - } -} - -// Common volume sources between Persistent Volumes and Pod Volumes -func commonVolumeSources() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "host_path": { - Type: schema.TypeList, - Description: "Represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: http://kubernetes.io/docs/user-guide/volumes#hostpath", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "path": { - Type: schema.TypeString, - Description: "Path of the directory on the host. More info: http://kubernetes.io/docs/user-guide/volumes#hostpath", - Optional: true, - }, - "type": { - Type: schema.TypeString, - Description: "Type for HostPath volume. Allowed values are \"\" (default), DirectoryOrCreate, Directory, FileOrCreate, File, Socket, CharDevice and BlockDevice", - Optional: true, - ValidateFunc: validation.StringInSlice([]string{"", "DirectoryOrCreate", "Directory", "FileOrCreate", "File", "Socket", "CharDevice", "BlockDevice"}, false), - }, - }, - }, - }, - "local": { - Type: schema.TypeList, - Description: "Represents a mounted local storage device such as a disk, partition or directory. Local volumes can only be used as a statically created PersistentVolume. Dynamic provisioning is not supported yet. More info: http://kubernetes.io/docs/user-guide/volumes#local", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "path": { - Type: schema.TypeString, - Description: "Path of the directory on the host. More info: http://kubernetes.io/docs/user-guide/volumes#local", - Optional: true, - }, - }, - }, - }, - "aws_elastic_block_store": { - Type: schema.TypeList, - Description: "Represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "fs_type": { - Type: schema.TypeString, - Description: "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore", - Optional: true, - }, - "partition": { - Type: schema.TypeInt, - Description: "The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty).", - Optional: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to set the read-only property in VolumeMounts to \"true\". If omitted, the default is \"false\". More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore", - Optional: true, - }, - "volume_id": { - Type: schema.TypeString, - Description: "Unique ID of the persistent disk resource in AWS (Amazon EBS volume). More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore", - Required: true, - }, - }, - }, - }, - "azure_disk": { - Type: schema.TypeList, - Description: "Represents an Azure Data Disk mount on the host and bind mount to the pod.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "caching_mode": { - Type: schema.TypeString, - Description: "Host Caching mode: None, Read Only, Read Write.", - Required: true, - }, - "data_disk_uri": { - Type: schema.TypeString, - Description: "The URI the data disk in the blob storage", - Required: true, - }, - "disk_name": { - Type: schema.TypeString, - Description: "The Name of the data disk in the blob storage", - Required: true, - }, - "fs_type": { - Type: schema.TypeString, - Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Optional: true, - }, - "kind": { - Type: schema.TypeString, - Description: "The type for the data disk. Expected values: Shared, Dedicated, Managed. Defaults to Shared", - Optional: true, - Computed: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write).", - Optional: true, - Default: false, - }, - }, - }, - }, - "azure_file": { - Type: schema.TypeList, - Description: "Represents an Azure File Service mount on the host and bind mount to the pod.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write).", - Optional: true, - }, - "secret_name": { - Type: schema.TypeString, - Description: "The name of secret that contains Azure Storage Account Name and Key", - Required: true, - }, - "share_name": { - Type: schema.TypeString, - Description: "Share Name", - Required: true, - }, - }, - }, - }, - "ceph_fs": { - Type: schema.TypeList, - Description: "Represents a Ceph FS mount on the host that shares a pod's lifetime", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "monitors": { - Type: schema.TypeSet, - Description: "Monitors is a collection of Ceph monitors More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "path": { - Type: schema.TypeString, - Description: "Used as the mounted root, rather than the full Ceph tree, default is /", - Optional: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the read-only setting in VolumeMounts. Defaults to `false` (read/write). More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", - Optional: true, - }, - "secret_file": { - Type: schema.TypeString, - Description: "The path to key ring for User, default is /etc/ceph/user.secret More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", - Optional: true, - }, - "secret_ref": commonVolumeSourcesSecretRef("Reference to the authentication secret for User, default is empty. More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it"), - "user": { - Type: schema.TypeString, - Description: "User is the rados user name, default is admin. More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", - Optional: true, - }, - }, - }, - }, - "cinder": { - Type: schema.TypeList, - Description: "Represents a cinder volume attached and mounted on kubelets host machine. More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "fs_type": { - Type: schema.TypeString, - Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", - Optional: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write). More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", - Optional: true, - }, - "volume_id": { - Type: schema.TypeString, - Description: "Volume ID used to identify the volume in Cinder. More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", - Required: true, - }, - }, - }, - }, - "csi": { - Type: schema.TypeList, - Description: "Represents a CSI Volume. More info: http://kubernetes.io/docs/user-guide/volumes#csi", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "driver": { - Type: schema.TypeString, - Description: "the name of the volume driver to use. More info: https://kubernetes.io/docs/concepts/storage/volumes/#csi", - Required: true, - }, - "volume_handle": { - Type: schema.TypeString, - Description: "A string value that uniquely identifies the volume. More info: https://kubernetes.io/docs/concepts/storage/volumes/#csi", - Required: true, - }, - "volume_attributes": { - Type: schema.TypeMap, - Description: "Attributes of the volume to publish.", - Optional: true, - }, - "fs_type": { - Type: schema.TypeString, - Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Optional: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to set the read-only property in VolumeMounts to \"true\". If omitted, the default is \"false\". More info: http://kubernetes.io/docs/user-guide/volumes#csi", - Optional: true, - }, - "controller_publish_secret_ref": commonVolumeSourcesSecretRef("A reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI ControllerPublishVolume and ControllerUnpublishVolume calls."), - "node_stage_secret_ref": commonVolumeSourcesSecretRef("A reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodeStageVolume and NodeStageVolume and NodeUnstageVolume calls."), - "node_publish_secret_ref": commonVolumeSourcesSecretRef("A reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodePublishVolume and NodeUnpublishVolume calls."), - "controller_expand_secret_ref": commonVolumeSourcesSecretRef("A reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI ControllerExpandVolume call."), - }, - }, - }, - "fc": { - Type: schema.TypeList, - Description: "Represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "fs_type": { - Type: schema.TypeString, - Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Optional: true, - }, - "lun": { - Type: schema.TypeInt, - Description: "FC target lun number", - Required: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write).", - Optional: true, - }, - "target_ww_ns": { - Type: schema.TypeSet, - Description: "FC target worldwide names (WWNs)", - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - }, - }, - }, - "flex_volume": { - Type: schema.TypeList, - Description: "Represents a generic volume resource that is provisioned/attached using an exec based plugin. This is an alpha feature and may change in future.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "driver": { - Type: schema.TypeString, - Description: "Driver is the name of the driver to use for this volume.", - Required: true, - }, - "fs_type": { - Type: schema.TypeString, - Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default filesystem depends on FlexVolume script.", - Optional: true, - }, - "options": { - Type: schema.TypeMap, - Description: "Extra command options if any.", - Optional: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the ReadOnly setting in VolumeMounts. Defaults to false (read/write).", - Optional: true, - }, - "secret_ref": commonVolumeSourcesSecretRef("Reference to the secret object containing sensitive information to pass to the plugin scripts. This may be empty if no secret object is specified. If the secret object contains more than one secret, all secrets are passed to the plugin scripts."), - }, - }, - }, - "flocker": { - Type: schema.TypeList, - Description: "Represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "dataset_name": { - Type: schema.TypeString, - Description: "Name of the dataset stored as metadata -> name on the dataset for Flocker should be considered as deprecated", - Optional: true, - }, - "dataset_uuid": { - Type: schema.TypeString, - Description: "UUID of the dataset. This is unique identifier of a Flocker dataset", - Optional: true, - }, - }, - }, - }, - "gce_persistent_disk": { - Type: schema.TypeList, - Description: "Represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "fs_type": { - Type: schema.TypeString, - Description: "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk", - Optional: true, - }, - "partition": { - Type: schema.TypeInt, - Description: "The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty). More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk", - Optional: true, - }, - "pd_name": { - Type: schema.TypeString, - Description: "Unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk", - Required: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the ReadOnly setting in VolumeMounts. Defaults to false. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk", - Optional: true, - }, - }, - }, - }, - "glusterfs": { - Type: schema.TypeList, - Description: "Represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "endpoints_name": { - Type: schema.TypeString, - Description: "The endpoint name that details Glusterfs topology. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod", - Required: true, - }, - "path": { - Type: schema.TypeString, - Description: "The Glusterfs volume path. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod", - Required: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod", - Optional: true, - }, - }, - }, - }, - "iscsi": { - Type: schema.TypeList, - Description: "Represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin.", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "fs_type": { - Type: schema.TypeString, - Description: "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#iscsi", - Optional: true, - }, - "iqn": { - Type: schema.TypeString, - Description: "Target iSCSI Qualified Name.", - Required: true, - }, - "iscsi_interface": { - Type: schema.TypeString, - Description: "iSCSI interface name that uses an iSCSI transport. Defaults to 'default' (tcp).", - Optional: true, - Default: "default", - }, - "lun": { - Type: schema.TypeInt, - Description: "iSCSI target lun number.", - Optional: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false.", - Optional: true, - }, - "target_portal": { - Type: schema.TypeString, - Description: "iSCSI target portal. The portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", - Required: true, - }, - }, - }, - }, - "nfs": { - Type: schema.TypeList, - Description: "Represents an NFS mount on the host. Provisioned by an admin. More info: http://kubernetes.io/docs/user-guide/volumes#nfs", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "path": { - Type: schema.TypeString, - Description: "Path that is exported by the NFS server. More info: http://kubernetes.io/docs/user-guide/volumes#nfs", - Required: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the NFS export to be mounted with read-only permissions. Defaults to false. More info: http://kubernetes.io/docs/user-guide/volumes#nfs", - Optional: true, - }, - "server": { - Type: schema.TypeString, - Description: "Server is the hostname or IP address of the NFS server. More info: http://kubernetes.io/docs/user-guide/volumes#nfs", - Required: true, - }, - }, - }, - }, - "photon_persistent_disk": { - Type: schema.TypeList, - Description: "Represents a PhotonController persistent disk attached and mounted on kubelets host machine", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "fs_type": { - Type: schema.TypeString, - Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Optional: true, - }, - "pd_id": { - Type: schema.TypeString, - Description: "ID that identifies Photon Controller persistent disk", - Required: true, - }, - }, - }, - }, - "quobyte": { - Type: schema.TypeList, - Description: "Quobyte represents a Quobyte mount on the host that shares a pod's lifetime", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "group": { - Type: schema.TypeString, - Description: "Group to map volume access to Default is no group", - Optional: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the Quobyte volume to be mounted with read-only permissions. Defaults to false.", - Optional: true, - }, - "registry": { - Type: schema.TypeString, - Description: "Registry represents a single or multiple Quobyte Registry services specified as a string as host:port pair (multiple entries are separated with commas) which acts as the central registry for volumes", - Required: true, - }, - "user": { - Type: schema.TypeString, - Description: "User to map volume access to Defaults to serivceaccount user", - Optional: true, - }, - "volume": { - Type: schema.TypeString, - Description: "Volume is a string that references an already created Quobyte volume by name.", - Required: true, - }, - }, - }, - }, - "rbd": { - Type: schema.TypeList, - Description: "Represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ceph_monitors": { - Type: schema.TypeSet, - Description: "A collection of Ceph monitors. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "fs_type": { - Type: schema.TypeString, - Description: "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#rbd", - Optional: true, - }, - "keyring": { - Type: schema.TypeString, - Description: "Keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", - Optional: true, - Computed: true, - }, - "rados_user": { - Type: schema.TypeString, - Description: "The rados user name. Default is admin. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", - Optional: true, - Default: "admin", - }, - "rbd_image": { - Type: schema.TypeString, - Description: "The rados image name. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", - Required: true, - }, - "rbd_pool": { - Type: schema.TypeString, - Description: "The rados pool name. Default is rbd. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it.", - Optional: true, - Default: "rbd", - }, - "read_only": { - Type: schema.TypeBool, - Description: "Whether to force the read-only setting in VolumeMounts. Defaults to false. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", - Optional: true, - Default: false, - }, - "secret_ref": commonVolumeSourcesSecretRef("Name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it"), - }, - }, - }, - "vsphere_volume": { - Type: schema.TypeList, - Description: "Represents a vSphere volume attached and mounted on kubelets host machine", - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "fs_type": { - Type: schema.TypeString, - Description: "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Optional: true, - }, - "volume_path": { - Type: schema.TypeString, - Description: "Path that identifies vSphere volume vmdk", - Required: true, - }, - }, - }, - }, - } -} - -func commonVolumeSourcesSecretRef(description string) *schema.Schema { - return &schema.Schema{ - Type: schema.TypeList, - Description: description, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - Optional: true, - }, - "namespace": { - Type: schema.TypeString, - Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - Optional: true, - Computed: true, - }, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_webhook_client_config.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_webhook_client_config.go deleted file mode 100644 index dbb1dbcedb6..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/schema_webhook_client_config.go +++ /dev/null @@ -1,87 +0,0 @@ -package kubernetes - -import ( - "errors" - "net/url" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" -) - -func serviceReferenceFields() map[string]*schema.Schema { - apiDoc := admissionregistrationv1.ServiceReference{}.SwaggerDoc() - return map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Description: apiDoc["name"], - Required: true, - }, - "namespace": { - Type: schema.TypeString, - Description: apiDoc["namespace"], - Required: true, - }, - "path": { - Type: schema.TypeString, - Description: apiDoc["path"], - Optional: true, - }, - "port": { - Type: schema.TypeInt, - Description: apiDoc["port"], - Optional: true, - Default: 443, - }, - } -} - -func webhookClientConfigFields() map[string]*schema.Schema { - apiDoc := admissionregistrationv1.WebhookClientConfig{}.SwaggerDoc() - return map[string]*schema.Schema{ - "ca_bundle": { - Type: schema.TypeString, - Description: apiDoc["caBundle"], - Optional: true, - }, - "service": { - Type: schema.TypeList, - Optional: true, - Description: apiDoc["service"], - MaxItems: 1, - Elem: &schema.Resource{ - Schema: serviceReferenceFields(), - }, - }, - "url": { - Type: schema.TypeString, - Description: apiDoc["url"], - Optional: true, - ValidateFunc: func(v interface{}, k string) ([]string, []error) { - u, err := url.Parse(v.(string)) - if err != nil { - return nil, []error{err} - } - - errs := []error{} - - if u.Scheme != "https" { - errs = append(errs, errors.New("url: scheme must be https")) - } - - if u.Host == "" { - errs = append(errs, errors.New("url: host must be provided")) - } - - if u.User != nil { - errs = append(errs, errors.New("url: user info is not permitted")) - } - - if u.Fragment != "" || u.RawQuery != "" { - errs = append(errs, errors.New("url: fragments and query parameters are not permitted")) - } - - return nil, errs - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_api_service_spec.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_api_service_spec.go deleted file mode 100644 index 6f36e57c475..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_api_service_spec.go +++ /dev/null @@ -1,73 +0,0 @@ -package kubernetes - -import ( - v1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" -) - -// Flatteners - -func flattenAPIServiceSpec(in v1.APIServiceSpec) []interface{} { - att := make(map[string]interface{}) - - att["ca_bundle"] = string(in.CABundle) - att["group"] = in.Group - att["group_priority_minimum"] = in.GroupPriorityMinimum - att["insecure_skip_tls_verify"] = in.InsecureSkipTLSVerify - - if in.Service != nil { - m := make(map[string]interface{}) - m["name"] = in.Service.Name - m["namespace"] = in.Service.Namespace - if in.Service.Port != nil { - m["port"] = *in.Service.Port - } - att["service"] = []interface{}{m} - } - - att["version"] = in.Version - att["version_priority"] = in.VersionPriority - - return []interface{}{att} -} - -// Expanders - -func expandAPIServiceSpec(l []interface{}) v1.APIServiceSpec { - if len(l) == 0 || l[0] == nil { - return v1.APIServiceSpec{} - } - in := l[0].(map[string]interface{}) - obj := v1.APIServiceSpec{} - - if v, ok := in["ca_bundle"].(string); ok { - obj.CABundle = []byte(v) - } - if v, ok := in["group"].(string); ok { - obj.Group = v - } - if v, ok := in["group_priority_minimum"].(int); ok { - obj.GroupPriorityMinimum = int32(v) - } - if v, ok := in["insecure_skip_tls_verify"].(bool); ok { - obj.InsecureSkipTLSVerify = v - } - if v, ok := in["service"].([]interface{}); ok && len(v) > 0 { - m := v[0].(map[string]interface{}) - obj.Service = &v1.ServiceReference{ - Name: m["name"].(string), - Namespace: m["namespace"].(string), - } - - if v, ok := m["port"].(int); ok && v > 0 { - obj.Service.Port = ptrToInt32(int32(v)) - } - } - if v, ok := in["version"].(string); ok { - obj.Version = v - } - if v, ok := in["version_priority"].(int); ok { - obj.VersionPriority = int32(v) - } - - return obj -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_cron_job.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_cron_job.go deleted file mode 100644 index 42c2be57662..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_cron_job.go +++ /dev/null @@ -1,116 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "k8s.io/api/batch/v1beta1" -) - -func flattenCronJobSpec(in v1beta1.CronJobSpec, d *schema.ResourceData) ([]interface{}, error) { - att := make(map[string]interface{}) - - att["concurrency_policy"] = in.ConcurrencyPolicy - - if in.FailedJobsHistoryLimit != nil { - att["failed_jobs_history_limit"] = int(*in.FailedJobsHistoryLimit) - } - - att["schedule"] = in.Schedule - - jobTemplate, err := flattenJobTemplate(in.JobTemplate, d) - if err != nil { - return nil, err - } - att["job_template"] = jobTemplate - - if in.StartingDeadlineSeconds != nil { - att["starting_deadline_seconds"] = int(*in.StartingDeadlineSeconds) - } - - if in.SuccessfulJobsHistoryLimit != nil { - att["successful_jobs_history_limit"] = int(*in.SuccessfulJobsHistoryLimit) - } - - att["suspend"] = in.Suspend - - return []interface{}{att}, nil -} - -func flattenJobTemplate(in v1beta1.JobTemplateSpec, d *schema.ResourceData) ([]interface{}, error) { - att := make(map[string]interface{}) - - meta := flattenMetadata(in.ObjectMeta, d) - att["metadata"] = meta - - jobSpec, err := flattenJobSpec(in.Spec, d, "spec.0.job_template.0.spec.0.template.0.") - if err != nil { - return nil, err - } - att["spec"] = jobSpec - - return []interface{}{att}, nil -} - -func expandCronJobSpec(j []interface{}) (v1beta1.CronJobSpec, error) { - obj := v1beta1.CronJobSpec{} - - if len(j) == 0 || j[0] == nil { - return obj, nil - } - - in := j[0].(map[string]interface{}) - - if v, ok := in["concurrency_policy"].(string); ok && v != "" { - obj.ConcurrencyPolicy = v1beta1.ConcurrencyPolicy(v) - } - - if v, ok := in["failed_jobs_history_limit"].(int); ok && v != 1 { - obj.FailedJobsHistoryLimit = ptrToInt32(int32(v)) - } - - if v, ok := in["schedule"].(string); ok && v != "" { - obj.Schedule = v - } - - jtSpec, err := expandJobTemplate(in["job_template"].([]interface{})) - if err != nil { - return obj, err - } - obj.JobTemplate = jtSpec - - if v, ok := in["starting_deadline_seconds"].(int); ok && v > 0 { - obj.StartingDeadlineSeconds = ptrToInt64(int64(v)) - } - - if v, ok := in["successful_jobs_history_limit"].(int); ok && v != 3 { - obj.SuccessfulJobsHistoryLimit = ptrToInt32(int32(v)) - } - - if v, ok := in["suspend"].(bool); ok { - obj.Suspend = ptrToBool(v) - } - - return obj, nil -} - -func expandJobTemplate(in []interface{}) (v1beta1.JobTemplateSpec, error) { - obj := v1beta1.JobTemplateSpec{} - - if len(in) == 0 || in[0] == nil { - return obj, nil - } - - tpl := in[0].(map[string]interface{}) - - spec, err := expandJobSpec(tpl["spec"].([]interface{})) - if err != nil { - return obj, err - } - obj.Spec = spec - - if metaCfg, ok := tpl["metadata"].([]interface{}); ok { - metadata := expandMetadata(metaCfg) - obj.ObjectMeta = metadata - } - - return obj, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_csi_driver.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_csi_driver.go deleted file mode 100644 index 429151475cd..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_csi_driver.go +++ /dev/null @@ -1,78 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - storage "k8s.io/api/storage/v1beta1" -) - -func expandCSIDriverSpec(l []interface{}) storage.CSIDriverSpec { - if len(l) == 0 || l[0] == nil { - return storage.CSIDriverSpec{} - } - in := l[0].(map[string]interface{}) - obj := storage.CSIDriverSpec{} - - if v, ok := in["attach_required"].(bool); ok { - obj.AttachRequired = ptrToBool(v) - } - - if v, ok := in["pod_info_on_mount"].(bool); ok { - obj.PodInfoOnMount = ptrToBool(v) - } - - if v, ok := in["volume_lifecycle_modes"].([]interface{}); ok && len(v) > 0 { - obj.VolumeLifecycleModes = expandCSIDriverVolumeLifecycleModes(v) - } - - return obj -} - -func expandCSIDriverVolumeLifecycleModes(l []interface{}) []storage.VolumeLifecycleMode { - lifecycleModes := make([]storage.VolumeLifecycleMode, 0, 0) - for _, lifecycleMode := range l { - lifecycleModes = append(lifecycleModes, storage.VolumeLifecycleMode(lifecycleMode.(string))) - } - return lifecycleModes -} - -func flattenCSIDriverSpec(in storage.CSIDriverSpec) ([]interface{}, error) { - att := make(map[string]interface{}) - - att["attach_required"] = in.AttachRequired - - if in.PodInfoOnMount != nil { - att["pod_info_on_mount"] = in.PodInfoOnMount - } - - if len(in.VolumeLifecycleModes) > 0 { - att["volume_lifecycle_modes"] = in.VolumeLifecycleModes - } - - return []interface{}{att}, nil -} - -func patchCSIDriverSpec(keyPrefix, pathPrefix string, d *schema.ResourceData) (*PatchOperations, error) { - ops := make(PatchOperations, 0, 0) - if d.HasChange(keyPrefix + "attach_required") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/attachRequired", - Value: d.Get(keyPrefix + "attach_required").(bool), - }) - } - - if d.HasChange(keyPrefix + "pod_info_on_mount") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/podInfoOnMount", - Value: d.Get(keyPrefix + "pod_info_on_mount").(bool), - }) - } - - if d.HasChange(keyPrefix + "volume_lifecycle_modes") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/volumeLifecycleModes", - Value: expandCSIDriverVolumeLifecycleModes(d.Get(keyPrefix + "volume_lifecycle_modes").([]interface{})), - }) - } - - return &ops, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_endpoints.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_endpoints.go deleted file mode 100644 index 1256b5b0325..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_endpoints.go +++ /dev/null @@ -1,120 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" -) - -func expandEndpointsAddresses(in *schema.Set) []api.EndpointAddress { - if in == nil || in.Len() == 0 { - return []api.EndpointAddress{} - } - addresses := make([]api.EndpointAddress, in.Len()) - for i, addr := range in.List() { - r := api.EndpointAddress{} - addrCfg := addr.(map[string]interface{}) - if v, ok := addrCfg["hostname"].(string); ok { - r.Hostname = v - } - if v, ok := addrCfg["ip"].(string); ok { - r.IP = v - } - if v, ok := addrCfg["node_name"].(string); ok && v != "" { - r.NodeName = ptrToString(v) - } - addresses[i] = r - } - return addresses -} - -func expandEndpointsPorts(in *schema.Set) []api.EndpointPort { - if in == nil || in.Len() == 0 { - return []api.EndpointPort{} - } - ports := make([]api.EndpointPort, in.Len()) - for i, port := range in.List() { - r := api.EndpointPort{} - portCfg := port.(map[string]interface{}) - if v, ok := portCfg["name"].(string); ok { - r.Name = v - } - if v, ok := portCfg["port"].(int); ok { - r.Port = int32(v) - } - if v, ok := portCfg["protocol"].(string); ok { - r.Protocol = api.Protocol(v) - } - ports[i] = r - } - return ports -} - -func expandEndpointsSubsets(in *schema.Set) []api.EndpointSubset { - if in == nil || in.Len() == 0 { - return []api.EndpointSubset{} - } - subsets := make([]api.EndpointSubset, in.Len()) - for i, subset := range in.List() { - r := api.EndpointSubset{} - subsetCfg := subset.(map[string]interface{}) - if v, ok := subsetCfg["address"].(*schema.Set); ok { - r.Addresses = expandEndpointsAddresses(v) - } - if v, ok := subsetCfg["not_ready_address"].(*schema.Set); ok { - r.NotReadyAddresses = expandEndpointsAddresses(v) - } - if v, ok := subsetCfg["port"]; ok { - r.Ports = expandEndpointsPorts(v.(*schema.Set)) - } - subsets[i] = r - } - return subsets -} - -func flattenEndpointsAddresses(in []api.EndpointAddress) *schema.Set { - att := make([]interface{}, len(in), len(in)) - for i, n := range in { - m := make(map[string]interface{}) - if n.Hostname != "" { - m["hostname"] = n.Hostname - } - m["ip"] = n.IP - if n.NodeName != nil { - m["node_name"] = *n.NodeName - } - att[i] = m - } - return schema.NewSet(hashEndpointsSubsetAddress(), att) -} - -func flattenEndpointsPorts(in []api.EndpointPort) *schema.Set { - att := make([]interface{}, len(in), len(in)) - for i, n := range in { - m := make(map[string]interface{}) - if n.Name != "" { - m["name"] = n.Name - } - m["port"] = int(n.Port) - m["protocol"] = string(n.Protocol) - att[i] = m - } - return schema.NewSet(hashEndpointsSubsetPort(), att) -} - -func flattenEndpointsSubsets(in []api.EndpointSubset) *schema.Set { - att := make([]interface{}, len(in), len(in)) - for i, n := range in { - m := make(map[string]interface{}) - if len(n.Addresses) > 0 { - m["address"] = flattenEndpointsAddresses(n.Addresses) - } - if len(n.NotReadyAddresses) > 0 { - m["not_ready_address"] = flattenEndpointsAddresses(n.NotReadyAddresses) - } - if len(n.Ports) > 0 { - m["port"] = flattenEndpointsPorts(n.Ports) - } - att[i] = m - } - return schema.NewSet(hashEndpointsSubset(), att) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_horizontal_pod_autoscaler.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_horizontal_pod_autoscaler.go deleted file mode 100644 index a817bfd4781..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_horizontal_pod_autoscaler.go +++ /dev/null @@ -1,107 +0,0 @@ -package kubernetes - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/autoscaling/v1" -) - -func expandHorizontalPodAutoscalerSpec(in []interface{}) (*api.HorizontalPodAutoscalerSpec, error) { - spec := &api.HorizontalPodAutoscalerSpec{} - if len(in) == 0 || in[0] == nil { - return nil, fmt.Errorf("failed to expand HorizontalPodAutoscaler.Spec: null or empty input") - } - m := in[0].(map[string]interface{}) - if v, ok := m["max_replicas"]; ok { - spec.MaxReplicas = int32(v.(int)) - } - if v, ok := m["min_replicas"].(int); ok && v > 0 { - spec.MinReplicas = ptrToInt32(int32(v)) - } - if v, ok := m["scale_target_ref"]; ok { - spec.ScaleTargetRef = expandCrossVersionObjectReference(v.([]interface{})) - } - if v, ok := m["target_cpu_utilization_percentage"].(int); ok && v > 0 { - spec.TargetCPUUtilizationPercentage = ptrToInt32(int32(v)) - } - - return spec, nil -} - -func expandCrossVersionObjectReference(in []interface{}) api.CrossVersionObjectReference { - if len(in) == 0 || in[0] == nil { - return api.CrossVersionObjectReference{} - } - ref := api.CrossVersionObjectReference{} - m := in[0].(map[string]interface{}) - - if v, ok := m["api_version"]; ok { - ref.APIVersion = v.(string) - } - if v, ok := m["kind"]; ok { - ref.Kind = v.(string) - } - if v, ok := m["name"]; ok { - ref.Name = v.(string) - } - return ref -} - -func flattenHorizontalPodAutoscalerSpec(spec api.HorizontalPodAutoscalerSpec) []interface{} { - m := make(map[string]interface{}, 0) - m["max_replicas"] = spec.MaxReplicas - if spec.MinReplicas != nil { - m["min_replicas"] = *spec.MinReplicas - } - m["scale_target_ref"] = flattenCrossVersionObjectReference(spec.ScaleTargetRef) - if spec.TargetCPUUtilizationPercentage != nil { - m["target_cpu_utilization_percentage"] = *spec.TargetCPUUtilizationPercentage - } - return []interface{}{m} -} - -func flattenCrossVersionObjectReference(ref api.CrossVersionObjectReference) []interface{} { - m := make(map[string]interface{}, 0) - if ref.APIVersion != "" { - m["api_version"] = ref.APIVersion - } - if ref.Kind != "" { - m["kind"] = ref.Kind - } - if ref.Name != "" { - m["name"] = ref.Name - } - return []interface{}{m} -} - -func patchHorizontalPodAutoscalerSpec(prefix string, pathPrefix string, d *schema.ResourceData) []PatchOperation { - ops := make([]PatchOperation, 0) - - if d.HasChange(prefix + "max_replicas") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/maxReplicas", - Value: d.Get(prefix + "max_replicas").(int), - }) - } - if d.HasChange(prefix + "min_replicas") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/minReplicas", - Value: d.Get(prefix + "min_replicas").(int), - }) - } - if d.HasChange(prefix + "scale_target_ref") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/scaleTargetRef", - Value: expandCrossVersionObjectReference(d.Get(prefix + "scale_target_ref").([]interface{})), - }) - } - if d.HasChange(prefix + "target_cpu_utilization_percentage") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/targetCPUUtilizationPercentage", - Value: d.Get(prefix + "target_cpu_utilization_percentage").(int), - }) - } - - return ops -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_horizontal_pod_autoscaler_v2.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_horizontal_pod_autoscaler_v2.go deleted file mode 100644 index 6b3c2b6257b..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_horizontal_pod_autoscaler_v2.go +++ /dev/null @@ -1,352 +0,0 @@ -package kubernetes - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - autoscalingv2beta2 "k8s.io/api/autoscaling/v2beta2" - v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" -) - -func expandHorizontalPodAutoscalerV2Spec(in []interface{}) (*autoscalingv2beta2.HorizontalPodAutoscalerSpec, error) { - if len(in) == 0 || in[0] == nil { - return nil, fmt.Errorf("failed to expand HorizontalPodAutoscaler.Spec: null or empty input") - } - - spec := &autoscalingv2beta2.HorizontalPodAutoscalerSpec{} - m := in[0].(map[string]interface{}) - - if v, ok := m["max_replicas"]; ok { - spec.MaxReplicas = int32(v.(int)) - } - - if v, ok := m["min_replicas"].(int); ok && v > 0 { - spec.MinReplicas = ptrToInt32(int32(v)) - } - - if v, ok := m["scale_target_ref"]; ok { - spec.ScaleTargetRef = expandV2CrossVersionObjectReference(v.([]interface{})) - } - - if v, ok := m["metric"].([]interface{}); ok { - spec.Metrics = expandV2Metrics(v) - } - - return spec, nil -} - -func expandV2Metrics(in []interface{}) []autoscalingv2beta2.MetricSpec { - metrics := []autoscalingv2beta2.MetricSpec{} - - for _, m := range in { - metrics = append(metrics, expandV2MetricSpec(m.(map[string]interface{}))) - } - - return metrics -} - -func expandV2MetricTarget(m map[string]interface{}) autoscalingv2beta2.MetricTarget { - target := autoscalingv2beta2.MetricTarget{} - - if v, ok := m["type"].(string); ok { - target.Type = autoscalingv2beta2.MetricTargetType(v) - } - - switch target.Type { - case autoscalingv2beta2.AverageValueMetricType: - if v, ok := m["average_value"].(string); ok && v != "0" && v != "" { - q := resource.MustParse(v) - target.AverageValue = &q - } - case autoscalingv2beta2.UtilizationMetricType: - if v, ok := m["average_utilization"].(int); ok && v > 0 { - target.AverageUtilization = ptrToInt32(int32(v)) - } - case autoscalingv2beta2.ValueMetricType: - if v, ok := m["value"].(string); ok && v != "0" && v != "" { - q := resource.MustParse(v) - target.Value = &q - } - } - - return target -} - -func expandV2ResourceMetricSource(m map[string]interface{}) *autoscalingv2beta2.ResourceMetricSource { - source := &autoscalingv2beta2.ResourceMetricSource{} - - if v, ok := m["name"].(string); ok { - source.Name = v1.ResourceName(v) - } - - if v, ok := m["target"].([]interface{}); ok && len(v) == 1 { - source.Target = expandV2MetricTarget(v[0].(map[string]interface{})) - } - - return source -} - -func expandV2MetricIdentifier(m map[string]interface{}) autoscalingv2beta2.MetricIdentifier { - identifier := autoscalingv2beta2.MetricIdentifier{} - identifier.Name = m["name"].(string) - - if v, ok := m["selector"].([]interface{}); ok && len(v) == 1 { - identifier.Selector = expandLabelSelector(v) - } - - return identifier -} - -func expandV2ExternalMetricSource(m map[string]interface{}) *autoscalingv2beta2.ExternalMetricSource { - source := &autoscalingv2beta2.ExternalMetricSource{} - - if v, ok := m["metric"].([]interface{}); ok && len(v) == 1 { - source.Metric = expandV2MetricIdentifier(v[0].(map[string]interface{})) - } - - if v, ok := m["target"].([]interface{}); ok && len(v) == 1 { - source.Target = expandV2MetricTarget(v[0].(map[string]interface{})) - } - - return source -} - -func expandV2PodsMetricSource(m map[string]interface{}) *autoscalingv2beta2.PodsMetricSource { - source := &autoscalingv2beta2.PodsMetricSource{} - - if v, ok := m["metric"].([]interface{}); ok && len(v) == 1 { - source.Metric = expandV2MetricIdentifier(v[0].(map[string]interface{})) - } - - if v, ok := m["target"].([]interface{}); ok && len(v) == 1 { - source.Target = expandV2MetricTarget(v[0].(map[string]interface{})) - } - - return source -} - -func expandV2ObjectMetricSource(m map[string]interface{}) *autoscalingv2beta2.ObjectMetricSource { - source := &autoscalingv2beta2.ObjectMetricSource{} - - if v, ok := m["described_object"].([]interface{}); ok && len(v) == 1 { - source.DescribedObject = expandV2CrossVersionObjectReference(v) - } - - if v, ok := m["metric"].([]interface{}); ok && len(v) == 1 { - source.Metric = expandV2MetricIdentifier(v[0].(map[string]interface{})) - } - - if v, ok := m["target"].([]interface{}); ok && len(v) == 1 { - source.Target = expandV2MetricTarget(v[0].(map[string]interface{})) - } - - return source -} - -func expandV2MetricSpec(m map[string]interface{}) autoscalingv2beta2.MetricSpec { - spec := autoscalingv2beta2.MetricSpec{} - - if v, ok := m["type"].(string); ok { - spec.Type = autoscalingv2beta2.MetricSourceType(v) - } - - if v, ok := m["resource"].([]interface{}); ok && len(v) == 1 { - spec.Resource = expandV2ResourceMetricSource(v[0].(map[string]interface{})) - } - - if v, ok := m["external"].([]interface{}); ok && len(v) == 1 { - spec.External = expandV2ExternalMetricSource(v[0].(map[string]interface{})) - } - - if v, ok := m["pods"].([]interface{}); ok && len(v) == 1 { - spec.Pods = expandV2PodsMetricSource(v[0].(map[string]interface{})) - } - - if v, ok := m["object"].([]interface{}); ok && len(v) == 1 { - spec.Object = expandV2ObjectMetricSource(v[0].(map[string]interface{})) - } - - return spec -} - -func expandV2CrossVersionObjectReference(in []interface{}) autoscalingv2beta2.CrossVersionObjectReference { - ref := autoscalingv2beta2.CrossVersionObjectReference{} - - if len(in) == 0 || in[0] == nil { - return ref - } - - m := in[0].(map[string]interface{}) - - if v, ok := m["api_version"]; ok { - ref.APIVersion = v.(string) - } - - if v, ok := m["kind"]; ok { - ref.Kind = v.(string) - } - - if v, ok := m["name"]; ok { - ref.Name = v.(string) - } - return ref -} - -func flattenV2MetricTarget(target autoscalingv2beta2.MetricTarget) []interface{} { - m := map[string]interface{}{ - "type": target.Type, - } - - switch target.Type { - case autoscalingv2beta2.AverageValueMetricType: - m["average_value"] = target.AverageValue.String() - case autoscalingv2beta2.UtilizationMetricType: - m["average_utilization"] = *target.AverageUtilization - case autoscalingv2beta2.ValueMetricType: - m["value"] = target.Value.String() - } - - return []interface{}{m} -} - -func flattenV2MetricIdentifier(identifier autoscalingv2beta2.MetricIdentifier) []interface{} { - m := map[string]interface{}{ - "name": identifier.Name, - } - - if identifier.Selector != nil { - m["selector"] = flattenLabelSelector(identifier.Selector) - } - - return []interface{}{m} -} - -func flattenV2ExternalMetricSource(external *autoscalingv2beta2.ExternalMetricSource) []interface{} { - m := map[string]interface{}{ - "metric": flattenV2MetricIdentifier(external.Metric), - "target": flattenV2MetricTarget(external.Target), - } - return []interface{}{m} -} - -func flattenV2PodsMetricSource(pods *autoscalingv2beta2.PodsMetricSource) []interface{} { - m := map[string]interface{}{ - "metric": flattenV2MetricIdentifier(pods.Metric), - "target": flattenV2MetricTarget(pods.Target), - } - return []interface{}{m} -} - -func flattenV2ObjectMetricSource(object *autoscalingv2beta2.ObjectMetricSource) []interface{} { - m := map[string]interface{}{ - "described_object": flattenV2CrossVersionObjectReference(object.DescribedObject), - "metric": flattenV2MetricIdentifier(object.Metric), - "target": flattenV2MetricTarget(object.Target), - } - return []interface{}{m} -} - -func flattenV2ResourceMetricSource(resource *autoscalingv2beta2.ResourceMetricSource) []interface{} { - m := map[string]interface{}{ - "name": resource.Name, - "target": flattenV2MetricTarget(resource.Target), - } - return []interface{}{m} -} - -func flattenV2MetricSpec(spec autoscalingv2beta2.MetricSpec) map[string]interface{} { - m := map[string]interface{}{} - - m["type"] = spec.Type - - if spec.Resource != nil { - m["resource"] = flattenV2ResourceMetricSource(spec.Resource) - } - - if spec.External != nil { - m["external"] = flattenV2ExternalMetricSource(spec.External) - } - - if spec.Pods != nil { - m["pods"] = flattenV2PodsMetricSource(spec.Pods) - } - - if spec.Object != nil { - m["object"] = flattenV2ObjectMetricSource(spec.Object) - } - - return m -} - -func flattenHorizontalPodAutoscalerV2Spec(spec autoscalingv2beta2.HorizontalPodAutoscalerSpec) []interface{} { - m := make(map[string]interface{}, 0) - - m["max_replicas"] = spec.MaxReplicas - - if spec.MinReplicas != nil { - m["min_replicas"] = *spec.MinReplicas - } - - m["scale_target_ref"] = flattenV2CrossVersionObjectReference(spec.ScaleTargetRef) - - metrics := []interface{}{} - for _, m := range spec.Metrics { - metrics = append(metrics, flattenV2MetricSpec(m)) - } - m["metric"] = metrics - - return []interface{}{m} -} - -func flattenV2CrossVersionObjectReference(ref autoscalingv2beta2.CrossVersionObjectReference) []interface{} { - m := make(map[string]interface{}, 0) - - if ref.APIVersion != "" { - m["api_version"] = ref.APIVersion - } - - if ref.Kind != "" { - m["kind"] = ref.Kind - } - - if ref.Name != "" { - m["name"] = ref.Name - } - - return []interface{}{m} -} - -func patchHorizontalPodAutoscalerV2Spec(prefix string, pathPrefix string, d *schema.ResourceData) []PatchOperation { - ops := make([]PatchOperation, 0) - - if d.HasChange(prefix + "max_replicas") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/maxReplicas", - Value: d.Get(prefix + "max_replicas").(int), - }) - } - - if d.HasChange(prefix + "min_replicas") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/minReplicas", - Value: d.Get(prefix + "min_replicas").(int), - }) - } - - if d.HasChange(prefix + "scale_target_ref") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/scaleTargetRef", - Value: expandCrossVersionObjectReference(d.Get(prefix + "scale_target_ref").([]interface{})), - }) - } - - if d.HasChange(prefix + "metric") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/metrics", - Value: expandV2Metrics(d.Get(prefix + "metric").([]interface{})), - }) - } - - return ops -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_hostalias.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_hostalias.go deleted file mode 100644 index 8f97892c89b..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_hostalias.go +++ /dev/null @@ -1,35 +0,0 @@ -package kubernetes - -import "k8s.io/api/core/v1" - -func flattenHostaliases(in []v1.HostAlias) []interface{} { - att := make([]interface{}, len(in)) - for i, v := range in { - ha := make(map[string]interface{}) - ha["ip"] = v.IP - if len(v.Hostnames) > 0 { - ha["hostnames"] = v.Hostnames - } - att[i] = ha - } - return att -} -func expandHostaliases(hostalias []interface{}) ([]v1.HostAlias, error) { - if len(hostalias) == 0 { - return []v1.HostAlias{}, nil - } - - hs := make([]v1.HostAlias, len(hostalias)) - for i, ha := range hostalias { - hoas := ha.(map[string]interface{}) - - if ip, ok := hoas["ip"]; ok { - hs[i].IP = ip.(string) - } - - if hostnames, ok := hoas["hostnames"].([]interface{}); ok { - hs[i].Hostnames = expandStringSlice(hostnames) - } - } - return hs, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_ingress_spec.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_ingress_spec.go deleted file mode 100644 index 3230b1f826b..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_ingress_spec.go +++ /dev/null @@ -1,219 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "k8s.io/api/extensions/v1beta1" - "k8s.io/apimachinery/pkg/util/intstr" -) - -// Flatteners - -func flattenIngressRule(in []v1beta1.IngressRule) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, r := range in { - m := make(map[string]interface{}) - - m["host"] = r.Host - m["http"] = flattenIngressRuleHttp(r.HTTP) - att[i] = m - } - return att -} - -func flattenIngressRuleHttp(in *v1beta1.HTTPIngressRuleValue) []interface{} { - if in == nil { - return []interface{}{} - } - pathAtts := make([]interface{}, len(in.Paths), len(in.Paths)) - for i, p := range in.Paths { - path := map[string]interface{}{ - "path": p.Path, - "backend": flattenIngressBackend(&p.Backend), - } - pathAtts[i] = path - } - - httpAtt := map[string]interface{}{ - "path": pathAtts, - } - - return []interface{}{httpAtt} -} - -func flattenIngressBackend(in *v1beta1.IngressBackend) []interface{} { - att := make([]interface{}, 1, 1) - - m := make(map[string]interface{}) - m["service_name"] = in.ServiceName - m["service_port"] = in.ServicePort.String() - - att[0] = m - - return att -} - -func flattenIngressSpec(in v1beta1.IngressSpec) []interface{} { - att := make(map[string]interface{}) - - if in.Backend != nil { - att["backend"] = flattenIngressBackend(in.Backend) - } - - if len(in.Rules) > 0 { - att["rule"] = flattenIngressRule(in.Rules) - } - - if len(in.TLS) > 0 { - att["tls"] = flattenIngressTLS(in.TLS) - } - - return []interface{}{att} -} - -func flattenIngressTLS(in []v1beta1.IngressTLS) []interface{} { - att := make([]interface{}, len(in), len(in)) - - for i, v := range in { - m := make(map[string]interface{}) - m["hosts"] = v.Hosts - m["secret_name"] = v.SecretName - - att[i] = m - } - - return att -} - -// Expanders - -func expandIngressRule(l []interface{}) []v1beta1.IngressRule { - if len(l) == 0 || l[0] == nil { - return []v1beta1.IngressRule{} - } - obj := make([]v1beta1.IngressRule, len(l), len(l)) - for i, n := range l { - cfg := n.(map[string]interface{}) - - var paths []v1beta1.HTTPIngressPath - - if httpCfg, ok := cfg["http"]; ok { - httpList := httpCfg.([]interface{}) - for _, h := range httpList { - http := h.(map[string]interface{}) - if v, ok := http["path"]; ok { - pathList := v.([]interface{}) - paths = make([]v1beta1.HTTPIngressPath, len(pathList), len(pathList)) - for i, path := range pathList { - p := path.(map[string]interface{}) - hip := v1beta1.HTTPIngressPath{ - Path: p["path"].(string), - Backend: *expandIngressBackend(p["backend"].([]interface{})), - } - paths[i] = hip - } - } - } - } - - obj[i] = v1beta1.IngressRule{ - Host: cfg["host"].(string), - IngressRuleValue: v1beta1.IngressRuleValue{ - HTTP: &v1beta1.HTTPIngressRuleValue{ - Paths: paths, - }, - }, - } - } - return obj -} - -func expandIngressSpec(l []interface{}) v1beta1.IngressSpec { - if len(l) == 0 || l[0] == nil { - return v1beta1.IngressSpec{} - } - in := l[0].(map[string]interface{}) - obj := v1beta1.IngressSpec{} - - if v, ok := in["backend"].([]interface{}); ok && len(v) > 0 { - obj.Backend = expandIngressBackend(v) - } - - if v, ok := in["rule"].([]interface{}); ok && len(v) > 0 { - obj.Rules = expandIngressRule(v) - } - - if v, ok := in["tls"].([]interface{}); ok && len(v) > 0 { - obj.TLS = expandIngressTLS(v) - } - - return obj -} - -func expandIngressBackend(l []interface{}) *v1beta1.IngressBackend { - if len(l) == 0 || l[0] == nil { - return &v1beta1.IngressBackend{} - } - in := l[0].(map[string]interface{}) - obj := &v1beta1.IngressBackend{} - - if v, ok := in["service_name"].(string); ok { - obj.ServiceName = v - } - - if v, ok := in["service_port"].(string); ok { - obj.ServicePort = intstr.Parse(v) - } - - return obj -} - -func expandIngressTLS(l []interface{}) []v1beta1.IngressTLS { - if len(l) == 0 || l[0] == nil { - return nil - } - - tlsList := make([]v1beta1.IngressTLS, len(l), len(l)) - for i, t := range l { - in := t.(map[string]interface{}) - obj := v1beta1.IngressTLS{} - - if v, ok := in["hosts"]; ok { - obj.Hosts = expandStringSlice(v.([]interface{})) - } - - if v, ok := in["secret_name"].(string); ok { - obj.SecretName = v - } - tlsList[i] = obj - } - - return tlsList -} - -// Patch Ops - -func patchIngressSpec(keyPrefix, pathPrefix string, d *schema.ResourceData) PatchOperations { - ops := make([]PatchOperation, 0, 0) - if d.HasChange(keyPrefix + "backend") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "backend", - Value: expandIngressBackend(d.Get(keyPrefix + "backend").([]interface{})), - }) - } - - if d.HasChange(keyPrefix + "rule") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "rules", - Value: expandIngressRule(d.Get(keyPrefix + "rule").([]interface{})), - }) - } - - if d.HasChange(keyPrefix + "tls") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "tls", - Value: expandIngressTLS(d.Get(keyPrefix + "tls").([]interface{})), - }) - } - - return ops -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_job.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_job.go deleted file mode 100644 index 502f5dad75e..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_job.go +++ /dev/null @@ -1,116 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - batchv1 "k8s.io/api/batch/v1" -) - -func flattenJobSpec(in batchv1.JobSpec, d *schema.ResourceData, prefix ...string) ([]interface{}, error) { - att := make(map[string]interface{}) - - if in.ActiveDeadlineSeconds != nil { - att["active_deadline_seconds"] = *in.ActiveDeadlineSeconds - } - - if in.BackoffLimit != nil { - att["backoff_limit"] = *in.BackoffLimit - } - - if in.Completions != nil { - att["completions"] = *in.Completions - } - - if in.ManualSelector != nil { - att["manual_selector"] = *in.ManualSelector - } - - if in.Parallelism != nil { - att["parallelism"] = *in.Parallelism - } - - if in.Selector != nil { - att["selector"] = flattenLabelSelector(in.Selector) - } - // Remove server-generated labels - labels := in.Template.ObjectMeta.Labels - - if _, ok := labels["controller-uid"]; ok { - delete(labels, "controller-uid") - } - - if _, ok := labels["job-name"]; ok { - delete(labels, "job-name") - } - - podSpec, err := flattenPodTemplateSpec(in.Template, d, prefix...) - if err != nil { - return nil, err - } - att["template"] = podSpec - - if in.TTLSecondsAfterFinished != nil { - att["ttl_seconds_after_finished"] = *in.TTLSecondsAfterFinished - } - - return []interface{}{att}, nil -} - -func expandJobSpec(j []interface{}) (batchv1.JobSpec, error) { - obj := batchv1.JobSpec{} - - if len(j) == 0 || j[0] == nil { - return obj, nil - } - - in := j[0].(map[string]interface{}) - - if v, ok := in["active_deadline_seconds"].(int); ok && v > 0 { - obj.ActiveDeadlineSeconds = ptrToInt64(int64(v)) - } - - if v, ok := in["backoff_limit"].(int); ok && v != 6 { - obj.BackoffLimit = ptrToInt32(int32(v)) - } - - if v, ok := in["completions"].(int); ok && v > 0 { - obj.Completions = ptrToInt32(int32(v)) - } - - if v, ok := in["manual_selector"]; ok { - obj.ManualSelector = ptrToBool(v.(bool)) - } - - if v, ok := in["parallelism"].(int); ok && v > 0 { - obj.Parallelism = ptrToInt32(int32(v)) - } - - if v, ok := in["selector"].([]interface{}); ok && len(v) > 0 { - obj.Selector = expandLabelSelector(v) - } - - template, err := expandPodTemplate(in["template"].([]interface{})) - if err != nil { - return obj, err - } - obj.Template = *template - - if v, ok := in["ttl_seconds_after_finished"].(int); ok && v >= 0 { - obj.TTLSecondsAfterFinished = ptrToInt32(int32(v)) - } - - return obj, nil -} - -func patchJobSpec(pathPrefix, prefix string, d *schema.ResourceData) (PatchOperations, error) { - ops := make([]PatchOperation, 0) - - if d.HasChange(prefix + "active_deadline_seconds") { - v := d.Get(prefix + "active_deadline_seconds").(int) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/activeDeadlineSeconds", - Value: v, - }) - } - - return ops, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_label_selector.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_label_selector.go deleted file mode 100644 index fcf125068e7..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_label_selector.go +++ /dev/null @@ -1,64 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// Flatteners - -func flattenLabelSelector(in *metav1.LabelSelector) []interface{} { - att := make(map[string]interface{}) - if len(in.MatchLabels) > 0 { - att["match_labels"] = in.MatchLabels - } - if len(in.MatchExpressions) > 0 { - att["match_expressions"] = flattenLabelSelectorRequirement(in.MatchExpressions) - } - return []interface{}{att} -} - -func flattenLabelSelectorRequirement(in []metav1.LabelSelectorRequirement) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, n := range in { - m := make(map[string]interface{}) - m["key"] = n.Key - m["operator"] = n.Operator - m["values"] = newStringSet(schema.HashString, n.Values) - att[i] = m - } - return att -} - -// Expanders - -func expandLabelSelector(l []interface{}) *metav1.LabelSelector { - if len(l) == 0 || l[0] == nil { - return &metav1.LabelSelector{} - } - in := l[0].(map[string]interface{}) - obj := &metav1.LabelSelector{} - if v, ok := in["match_labels"].(map[string]interface{}); ok && len(v) > 0 { - obj.MatchLabels = expandStringMap(v) - } - if v, ok := in["match_expressions"].([]interface{}); ok && len(v) > 0 { - obj.MatchExpressions = expandLabelSelectorRequirement(v) - } - return obj -} - -func expandLabelSelectorRequirement(l []interface{}) []metav1.LabelSelectorRequirement { - if len(l) == 0 || l[0] == nil { - return []metav1.LabelSelectorRequirement{} - } - obj := make([]metav1.LabelSelectorRequirement, len(l), len(l)) - for i, n := range l { - in := n.(map[string]interface{}) - obj[i] = metav1.LabelSelectorRequirement{ - Key: in["key"].(string), - Operator: metav1.LabelSelectorOperator(in["operator"].(string)), - Values: sliceOfString(in["values"].(*schema.Set).List()), - } - } - return obj -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_mutating_webhook_configuration.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_mutating_webhook_configuration.go deleted file mode 100644 index bd0d1b87217..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_mutating_webhook_configuration.go +++ /dev/null @@ -1,129 +0,0 @@ -package kubernetes - -import ( - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" -) - -func flattenMutatingWebhook(in admissionregistrationv1.MutatingWebhook) map[string]interface{} { - att := map[string]interface{}{} - - att["admission_review_versions"] = in.AdmissionReviewVersions - - att["client_config"] = flattenWebhookClientConfig(in.ClientConfig) - - if in.FailurePolicy != nil { - att["failure_policy"] = *in.FailurePolicy - } - - if in.MatchPolicy != nil { - att["match_policy"] = *in.MatchPolicy - } - - att["name"] = in.Name - - if in.NamespaceSelector != nil { - if in.NamespaceSelector.MatchExpressions != nil || in.NamespaceSelector.MatchLabels != nil { - att["namespace_selector"] = flattenLabelSelector(in.NamespaceSelector) - } - } - - if in.ObjectSelector != nil { - if in.ObjectSelector.MatchExpressions != nil || in.ObjectSelector.MatchLabels != nil { - att["object_selector"] = flattenLabelSelector(in.ObjectSelector) - } - } - - if in.ReinvocationPolicy != nil { - att["reinvocation_policy"] = *in.ReinvocationPolicy - } - - rules := []interface{}{} - for _, rule := range in.Rules { - rules = append(rules, flattenRuleWithOperations(rule)) - } - att["rule"] = rules - - if in.SideEffects != nil { - att["side_effects"] = *in.SideEffects - } - - if in.TimeoutSeconds != nil { - att["timeout_seconds"] = *in.TimeoutSeconds - } - - return att -} - -func expandMutatingWebhook(in map[string]interface{}) admissionregistrationv1.MutatingWebhook { - obj := admissionregistrationv1.MutatingWebhook{} - - if v, ok := in["admission_review_versions"].([]interface{}); ok { - obj.AdmissionReviewVersions = expandStringSlice(v) - } - - if v, ok := in["client_config"].([]interface{}); ok { - obj.ClientConfig = expandWebhookClientConfig(v) - } - - if v, ok := in["failure_policy"].(string); ok { - policy := admissionregistrationv1.FailurePolicyType(v) - obj.FailurePolicy = &policy - } - - if v, ok := in["match_policy"].(string); ok { - policy := admissionregistrationv1.MatchPolicyType(v) - obj.MatchPolicy = &policy - } - - if v, ok := in["name"].(string); ok { - obj.Name = v - } - - if v, ok := in["namespace_selector"].([]interface{}); ok && len(v) != 0 { - obj.NamespaceSelector = expandLabelSelector(v) - } - - if v, ok := in["object_selector"].([]interface{}); ok && len(v) != 0 { - obj.ObjectSelector = expandLabelSelector(v) - } - - if v, ok := in["reinvocation_policy"].(string); ok { - policy := admissionregistrationv1.ReinvocationPolicyType(v) - obj.ReinvocationPolicy = &policy - } - - if v, ok := in["rule"].([]interface{}); ok { - rules := []admissionregistrationv1.RuleWithOperations{} - for _, r := range v { - rules = append(rules, expandRuleWithOperations(r.(map[string]interface{}))) - } - obj.Rules = rules - } - - if v, ok := in["side_effects"].(string); ok { - sideEffects := admissionregistrationv1.SideEffectClass(v) - obj.SideEffects = &sideEffects - } - - if v, ok := in["timeout_seconds"].(int); ok { - obj.TimeoutSeconds = ptrToInt32(int32(v)) - } - - return obj -} - -func expandMutatingWebhooks(in []interface{}) []admissionregistrationv1.MutatingWebhook { - webhooks := []admissionregistrationv1.MutatingWebhook{} - for _, h := range in { - webhooks = append(webhooks, expandMutatingWebhook(h.(map[string]interface{}))) - } - return webhooks -} - -func flattenMutatingWebhooks(in []admissionregistrationv1.MutatingWebhook) []interface{} { - webhooks := []interface{}{} - for _, h := range in { - webhooks = append(webhooks, flattenMutatingWebhook(h)) - } - return webhooks -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_network_policy.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_network_policy.go deleted file mode 100644 index f65ee0b21c6..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_network_policy.go +++ /dev/null @@ -1,327 +0,0 @@ -package kubernetes - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/api/networking/v1" - "k8s.io/apimachinery/pkg/util/intstr" -) - -// Flatteners - -func flattenNetworkPolicySpec(in v1.NetworkPolicySpec) []interface{} { - att := make(map[string]interface{}) - att["ingress"] = flattenNetworkPolicyIngress(in.Ingress) - att["egress"] = flattenNetworkPolicyEgress(in.Egress) - if len(in.PodSelector.MatchExpressions) > 0 || len(in.PodSelector.MatchLabels) > 0 { - att["pod_selector"] = flattenLabelSelector(&in.PodSelector) - } else { - att["pod_selector"] = []interface{}{make(map[string]interface{})} - } - if len(in.PolicyTypes) > 0 { - att["policy_types"] = in.PolicyTypes - } - return []interface{}{att} -} - -func flattenNetworkPolicyIngress(in []v1.NetworkPolicyIngressRule) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, ingress := range in { - m := make(map[string]interface{}) - if ingress.Ports != nil && len(ingress.Ports) > 0 { - m["ports"] = flattenNetworkPolicyPorts(ingress.Ports) - } - if ingress.From != nil && len(ingress.From) > 0 { - m["from"] = flattenNetworkPolicyPeer(ingress.From) - } - att[i] = m - } - return att -} - -func flattenNetworkPolicyEgress(in []v1.NetworkPolicyEgressRule) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, egress := range in { - m := make(map[string]interface{}) - if egress.Ports != nil && len(egress.Ports) > 0 { - m["ports"] = flattenNetworkPolicyPorts(egress.Ports) - } - if egress.To != nil && len(egress.To) > 0 { - m["to"] = flattenNetworkPolicyPeer(egress.To) - } - att[i] = m - } - return att -} - -func flattenNetworkPolicyPorts(in []v1.NetworkPolicyPort) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, port := range in { - m := make(map[string]interface{}) - if port.Port != nil { - m["port"] = port.Port.String() - } - if port.Protocol != nil { - m["protocol"] = string(*port.Protocol) - } - att[i] = m - } - return att -} - -func flattenNetworkPolicyPeer(in []v1.NetworkPolicyPeer) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, peer := range in { - m := make(map[string]interface{}) - if peer.IPBlock != nil { - m["ip_block"] = flattenIPBlock(peer.IPBlock) - } - if peer.NamespaceSelector != nil { - m["namespace_selector"] = flattenLabelSelector(peer.NamespaceSelector) - } - if peer.PodSelector != nil { - m["pod_selector"] = flattenLabelSelector(peer.PodSelector) - } - att[i] = m - } - return att -} - -func flattenIPBlock(in *v1.IPBlock) []interface{} { - att := make(map[string]interface{}) - if in.CIDR != "" { - att["cidr"] = in.CIDR - } - if len(in.Except) > 0 { - att["except"] = in.Except - } - return []interface{}{att} -} - -// Expanders - -func expandNetworkPolicySpec(in []interface{}) (*v1.NetworkPolicySpec, error) { - spec := v1.NetworkPolicySpec{} - - if len(in) == 0 || in[0] == nil { - return nil, fmt.Errorf("failed to expand NetworkPolicy.Spec: null or empty input") - } - - m, ok := in[0].(map[string]interface{}) - if !ok { - return nil, fmt.Errorf("failed to expand NetworkPolicy.Spec: malformed input") - } - spec.PodSelector = *expandLabelSelector(m["pod_selector"].([]interface{})) - if v, ok := m["ingress"].([]interface{}); ok && len(v) > 0 { - ingress, err := expandNetworkPolicyIngress(v) - if err != nil { - return nil, err - } - spec.Ingress = *ingress - } - if v, ok := m["egress"].([]interface{}); ok && len(v) > 0 { - egress, err := expandNetworkPolicyEgress(v) - if err != nil { - return nil, err - } - spec.Egress = *egress - } - policyTypes, err := expandNetworkPolicyTypes(m["policy_types"].([]interface{})) - if err != nil { - return nil, err - } - spec.PolicyTypes = *policyTypes - - return &spec, nil -} - -func expandNetworkPolicyIngress(l []interface{}) (*[]v1.NetworkPolicyIngressRule, error) { - ingresses := make([]v1.NetworkPolicyIngressRule, len(l), len(l)) - for i, ingress := range l { - if ingress == nil { - continue - } - in, ok := ingress.(map[string]interface{}) - if !ok { - continue - } - ingresses[i] = v1.NetworkPolicyIngressRule{} - if v, ok := in["ports"].([]interface{}); ok && len(v) > 0 { - policyPorts, err := expandNetworkPolicyPorts(v) - if err != nil { - return nil, err - } - ingresses[i].Ports = *policyPorts - } - if v, ok := in["from"].([]interface{}); ok && len(v) > 0 { - policyPeers, err := expandNetworkPolicyPeer(v) - if err != nil { - return nil, err - } - ingresses[i].From = *policyPeers - } - } - return &ingresses, nil -} - -func expandNetworkPolicyEgress(l []interface{}) (*[]v1.NetworkPolicyEgressRule, error) { - egresses := make([]v1.NetworkPolicyEgressRule, len(l), len(l)) - for i, egress := range l { - if egress == nil { - continue - } - in, ok := egress.(map[string]interface{}) - if !ok { - continue - } - egresses[i] = v1.NetworkPolicyEgressRule{} - if v, ok := in["ports"].([]interface{}); ok && len(v) > 0 { - policyPorts, err := expandNetworkPolicyPorts(v) - if err != nil { - return nil, err - } - egresses[i].Ports = *policyPorts - } - if v, ok := in["to"].([]interface{}); ok && len(v) > 0 { - policyPeers, err := expandNetworkPolicyPeer(v) - if err != nil { - return nil, err - } - egresses[i].To = *policyPeers - } - } - return &egresses, nil -} - -func expandNetworkPolicyPorts(l []interface{}) (*[]v1.NetworkPolicyPort, error) { - policyPorts := make([]v1.NetworkPolicyPort, len(l), len(l)) - for i, port := range l { - in, ok := port.(map[string]interface{}) - if !ok { - continue - } - if v, ok := in["port"].(string); ok && len(v) > 0 { - val := intstr.Parse(v) - policyPorts[i].Port = &val - } - if in["protocol"] != nil && in["protocol"] != "" { - v := api.Protocol(in["protocol"].(string)) - policyPorts[i].Protocol = &v - } - } - return &policyPorts, nil -} - -func expandNetworkPolicyPeer(l []interface{}) (*[]v1.NetworkPolicyPeer, error) { - policyPeers := make([]v1.NetworkPolicyPeer, len(l), len(l)) - for i, peer := range l { - if peer == nil { - continue - } - in, ok := peer.(map[string]interface{}) - if !ok { - continue - } - if v, ok := in["ip_block"].([]interface{}); ok && len(v) > 0 { - ipBlock, err := expandIPBlock(v) - if err != nil { - return nil, err - } - policyPeers[i].IPBlock = ipBlock - } - if v, ok := in["namespace_selector"].([]interface{}); ok && len(v) > 0 { - policyPeers[i].NamespaceSelector = expandLabelSelector(v) - } - if v, ok := in["pod_selector"].([]interface{}); ok && len(v) > 0 { - policyPeers[i].PodSelector = expandLabelSelector(v) - } - } - return &policyPeers, nil -} - -func expandIPBlock(l []interface{}) (*v1.IPBlock, error) { - ipBlock := v1.IPBlock{} - if len(l) == 0 || l[0] == nil { - return nil, fmt.Errorf("failed to expand IPBlock: null or empty input") - } - in, ok := l[0].(map[string]interface{}) - if !ok { - return nil, fmt.Errorf("failed to expand IPBlock: malformed input") - } - if v, ok := in["cidr"].(string); ok && v != "" { - ipBlock.CIDR = v - } - if v, ok := in["except"].([]interface{}); ok && len(v) > 0 { - ipBlock.Except = expandStringSlice(v) - } - return &ipBlock, nil -} - -func expandNetworkPolicyTypes(l []interface{}) (*[]v1.PolicyType, error) { - policyTypes := make([]v1.PolicyType, 0, 0) - for _, policyType := range l { - policyTypes = append(policyTypes, v1.PolicyType(policyType.(string))) - } - return &policyTypes, nil -} - -// Patchers - -func patchNetworkPolicySpec(keyPrefix, pathPrefix string, d *schema.ResourceData) (*PatchOperations, error) { - ops := make(PatchOperations, 0, 0) - if d.HasChange(keyPrefix + "ingress") { - oldV, _ := d.GetChange(keyPrefix + "ingress") - ingress, err := expandNetworkPolicyIngress(d.Get(keyPrefix + "ingress").([]interface{})) - if err != nil { - return nil, err - } - if len(oldV.([]interface{})) == 0 { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/ingress", - Value: ingress, - }) - } else { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/ingress", - Value: ingress, - }) - } - } - if d.HasChange(keyPrefix + "egress") { - oldV, _ := d.GetChange(keyPrefix + "egress") - egress, err := expandNetworkPolicyEgress(d.Get(keyPrefix + "egress").([]interface{})) - if err != nil { - return nil, err - } - if len(oldV.([]interface{})) == 0 { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/egress", - Value: egress, - }) - } else { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/egress", - Value: egress, - }) - } - } - if d.HasChange(keyPrefix + "pod_selector") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/podSelector", - Value: expandLabelSelector(d.Get(keyPrefix + "pod_selector").([]interface{})), - }) - } - if d.HasChange(keyPrefix + "policy_types") { - policyTypes, err := expandNetworkPolicyTypes(d.Get(keyPrefix + "policy_types").([]interface{})) - if err != nil { - return nil, err - } - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/policyTypes", - Value: *policyTypes, - }) - } - return &ops, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_persistent_volume_claim.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_persistent_volume_claim.go deleted file mode 100644 index f120521c5c4..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_persistent_volume_claim.go +++ /dev/null @@ -1,109 +0,0 @@ -package kubernetes - -import ( - "errors" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "k8s.io/api/core/v1" - corev1 "k8s.io/api/core/v1" -) - -// Flatteners - -func flattenPersistentVolumeClaimSpec(in v1.PersistentVolumeClaimSpec) []interface{} { - att := make(map[string]interface{}) - att["access_modes"] = flattenPersistentVolumeAccessModes(in.AccessModes) - att["resources"] = flattenResourceRequirements(in.Resources) - if in.Selector != nil { - att["selector"] = flattenLabelSelector(in.Selector) - } - if in.VolumeName != "" { - att["volume_name"] = in.VolumeName - } - if in.StorageClassName != nil { - att["storage_class_name"] = *in.StorageClassName - } - return []interface{}{att} -} - -func flattenResourceRequirements(in v1.ResourceRequirements) []interface{} { - att := make(map[string]interface{}) - if len(in.Limits) > 0 { - att["limits"] = flattenResourceList(in.Limits) - } - if len(in.Requests) > 0 { - att["requests"] = flattenResourceList(in.Requests) - } - return []interface{}{att} -} - -// Expanders - -func expandPersistentVolumeClaim(p map[string]interface{}) (*corev1.PersistentVolumeClaim, error) { - pvc := &corev1.PersistentVolumeClaim{} - if len(p) == 0 { - return pvc, nil - } - m, ok := p["metadata"].([]interface{}) - if !ok { - return pvc, errors.New("persistent_volume_claim: failed to expand 'metadata'") - } - pvc.ObjectMeta = expandMetadata(m) - s, ok := p["spec"].([]interface{}) - if !ok { - return pvc, errors.New("persistent_volume_claim: failed to expand 'spec'") - } - spec, err := expandPersistentVolumeClaimSpec(s) - if err != nil { - return pvc, err - } - pvc.Spec = *spec - return pvc, nil -} - -func expandPersistentVolumeClaimSpec(l []interface{}) (*v1.PersistentVolumeClaimSpec, error) { - obj := &v1.PersistentVolumeClaimSpec{} - if len(l) == 0 || l[0] == nil { - return obj, nil - } - in := l[0].(map[string]interface{}) - resourceRequirements, err := expandResourceRequirements(in["resources"].([]interface{})) - if err != nil { - return nil, err - } - obj.AccessModes = expandPersistentVolumeAccessModes(in["access_modes"].(*schema.Set).List()) - obj.Resources = *resourceRequirements - if v, ok := in["selector"].([]interface{}); ok && len(v) > 0 { - obj.Selector = expandLabelSelector(v) - } - if v, ok := in["volume_name"].(string); ok { - obj.VolumeName = v - } - if v, ok := in["storage_class_name"].(string); ok && v != "" { - obj.StorageClassName = ptrToString(v) - } - return obj, nil -} - -func expandResourceRequirements(l []interface{}) (*v1.ResourceRequirements, error) { - obj := &v1.ResourceRequirements{} - if len(l) == 0 || l[0] == nil { - return obj, nil - } - in := l[0].(map[string]interface{}) - if v, ok := in["limits"].(map[string]interface{}); ok && len(v) > 0 { - rl, err := expandMapToResourceList(v) - if err != nil { - return obj, err - } - obj.Limits = *rl - } - if v, ok := in["requests"].(map[string]interface{}); ok && len(v) > 0 { - rq, err := expandMapToResourceList(v) - if err != nil { - return obj, err - } - obj.Requests = *rq - } - return obj, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_persistent_volume_spec.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_persistent_volume_spec.go deleted file mode 100644 index 333ca045007..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_persistent_volume_spec.go +++ /dev/null @@ -1,1663 +0,0 @@ -package kubernetes - -import ( - v1 "k8s.io/api/core/v1" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -// Flatteners - -func flattenAWSElasticBlockStoreVolumeSource(in *v1.AWSElasticBlockStoreVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["volume_id"] = in.VolumeID - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if in.Partition != 0 { - att["partition"] = in.Partition - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenAzureDiskVolumeSource(in *v1.AzureDiskVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["disk_name"] = in.DiskName - att["data_disk_uri"] = in.DataDiskURI - if in.Kind != nil { - att["kind"] = string(*in.Kind) - } - att["caching_mode"] = string(*in.CachingMode) - if in.FSType != nil { - att["fs_type"] = *in.FSType - } - if in.ReadOnly != nil { - att["read_only"] = *in.ReadOnly - } - return []interface{}{att} -} - -func flattenAzureFileVolumeSource(in *v1.AzureFileVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["secret_name"] = in.SecretName - att["share_name"] = in.ShareName - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenAzureFilePersistentVolumeSource(in *v1.AzureFilePersistentVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["secret_name"] = in.SecretName - att["share_name"] = in.ShareName - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenCephFSVolumeSource(in *v1.CephFSVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["monitors"] = newStringSet(schema.HashString, in.Monitors) - if in.Path != "" { - att["path"] = in.Path - } - if in.User != "" { - att["user"] = in.User - } - if in.SecretFile != "" { - att["secret_file"] = in.SecretFile - } - if in.SecretRef != nil { - att["secret_ref"] = flattenLocalObjectReference(in.SecretRef) - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenCephFSPersistentVolumeSource(in *v1.CephFSPersistentVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["monitors"] = newStringSet(schema.HashString, in.Monitors) - if in.Path != "" { - att["path"] = in.Path - } - if in.User != "" { - att["user"] = in.User - } - if in.SecretFile != "" { - att["secret_file"] = in.SecretFile - } - if in.SecretRef != nil { - att["secret_ref"] = flattenSecretReference(in.SecretRef) - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenCinderPersistentVolumeSource(in *v1.CinderPersistentVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["volume_id"] = in.VolumeID - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenCinderVolumeSource(in *v1.CinderVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["volume_id"] = in.VolumeID - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenFCVolumeSource(in *v1.FCVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["target_ww_ns"] = newStringSet(schema.HashString, in.TargetWWNs) - att["lun"] = *in.Lun - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenFlexPersistentVolumeSource(in *v1.FlexPersistentVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["driver"] = in.Driver - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if in.SecretRef != nil { - att["secret_ref"] = flattenSecretReference(in.SecretRef) - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - if len(in.Options) > 0 { - att["options"] = in.Options - } - return []interface{}{att} -} - -func flattenFlexVolumeSource(in *v1.FlexVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["driver"] = in.Driver - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if in.SecretRef != nil { - att["secret_ref"] = flattenLocalObjectReference(in.SecretRef) - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - if len(in.Options) > 0 { - att["options"] = in.Options - } - return []interface{}{att} -} - -func flattenFlockerVolumeSource(in *v1.FlockerVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["dataset_name"] = in.DatasetName - att["dataset_uuid"] = in.DatasetUUID - return []interface{}{att} -} - -func flattenGCEPersistentDiskVolumeSource(in *v1.GCEPersistentDiskVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["pd_name"] = in.PDName - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if in.Partition != 0 { - att["partition"] = in.Partition - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenGlusterfsPersistentVolumeSource(in *v1.GlusterfsPersistentVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["endpoints_name"] = in.EndpointsName - att["path"] = in.Path - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenGlusterfsVolumeSource(in *v1.GlusterfsVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["endpoints_name"] = in.EndpointsName - att["path"] = in.Path - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenHostPathVolumeSource(in *v1.HostPathVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["path"] = in.Path - if in.Type != nil { - att["type"] = string(*in.Type) - } - return []interface{}{att} -} - -func flattenLocalVolumeSource(in *v1.LocalVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["path"] = in.Path - return []interface{}{att} -} - -func flattenISCSIVolumeSource(in *v1.ISCSIVolumeSource) []interface{} { - att := make(map[string]interface{}) - if in.TargetPortal != "" { - att["target_portal"] = in.TargetPortal - } - if in.IQN != "" { - att["iqn"] = in.IQN - } - if in.Lun != 0 { - att["lun"] = in.Lun - } - if in.ISCSIInterface != "" { - att["iscsi_interface"] = in.ISCSIInterface - } - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenISCSIPersistentVolumeSource(in *v1.ISCSIPersistentVolumeSource) []interface{} { - att := make(map[string]interface{}) - if in.TargetPortal != "" { - att["target_portal"] = in.TargetPortal - } - if in.IQN != "" { - att["iqn"] = in.IQN - } - if in.Lun != 0 { - att["lun"] = in.Lun - } - if in.ISCSIInterface != "" { - att["iscsi_interface"] = in.ISCSIInterface - } - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenLocalObjectReference(in *v1.LocalObjectReference) []interface{} { - att := make(map[string]interface{}) - if in.Name != "" { - att["name"] = in.Name - } - return []interface{}{att} -} - -func flattenSecretReference(in *v1.SecretReference) []interface{} { - att := make(map[string]interface{}) - if in.Name != "" { - att["name"] = in.Name - } - if in.Namespace != "" { - att["namespace"] = in.Namespace - } - return []interface{}{att} -} - -func flattenNFSVolumeSource(in *v1.NFSVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["server"] = in.Server - att["path"] = in.Path - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenPersistentVolumeSource(in v1.PersistentVolumeSource) []interface{} { - att := make(map[string]interface{}) - if in.GCEPersistentDisk != nil { - att["gce_persistent_disk"] = flattenGCEPersistentDiskVolumeSource(in.GCEPersistentDisk) - } - if in.AWSElasticBlockStore != nil { - att["aws_elastic_block_store"] = flattenAWSElasticBlockStoreVolumeSource(in.AWSElasticBlockStore) - } - if in.HostPath != nil { - att["host_path"] = flattenHostPathVolumeSource(in.HostPath) - } - if in.Local != nil { - att["local"] = flattenLocalVolumeSource(in.Local) - } - if in.Glusterfs != nil { - att["glusterfs"] = flattenGlusterfsPersistentVolumeSource(in.Glusterfs) - } - if in.NFS != nil { - att["nfs"] = flattenNFSVolumeSource(in.NFS) - } - if in.RBD != nil { - att["rbd"] = flattenRBDPersistentVolumeSource(in.RBD) - } - if in.ISCSI != nil { - att["iscsi"] = flattenISCSIPersistentVolumeSource(in.ISCSI) - } - if in.Cinder != nil { - att["cinder"] = flattenCinderPersistentVolumeSource(in.Cinder) - } - if in.CephFS != nil { - att["ceph_fs"] = flattenCephFSPersistentVolumeSource(in.CephFS) - } - if in.FC != nil { - att["fc"] = flattenFCVolumeSource(in.FC) - } - if in.Flocker != nil { - att["flocker"] = flattenFlockerVolumeSource(in.Flocker) - } - if in.FlexVolume != nil { - att["flex_volume"] = flattenFlexPersistentVolumeSource(in.FlexVolume) - } - if in.AzureFile != nil { - att["azure_file"] = flattenAzureFilePersistentVolumeSource(in.AzureFile) - } - if in.VsphereVolume != nil { - att["vsphere_volume"] = flattenVsphereVirtualDiskVolumeSource(in.VsphereVolume) - } - if in.Quobyte != nil { - att["quobyte"] = flattenQuobyteVolumeSource(in.Quobyte) - } - if in.AzureDisk != nil { - att["azure_disk"] = flattenAzureDiskVolumeSource(in.AzureDisk) - } - if in.PhotonPersistentDisk != nil { - att["photon_persistent_disk"] = flattenPhotonPersistentDiskVolumeSource(in.PhotonPersistentDisk) - } - if in.CSI != nil { - att["csi"] = flattenCSIVolumeSource(in.CSI) - } - return []interface{}{att} -} - -func flattenPersistentVolumeSpec(in v1.PersistentVolumeSpec) []interface{} { - att := make(map[string]interface{}) - if len(in.Capacity) > 0 { - att["capacity"] = flattenResourceList(in.Capacity) - } - - att["persistent_volume_source"] = flattenPersistentVolumeSource(in.PersistentVolumeSource) - if len(in.AccessModes) > 0 { - att["access_modes"] = flattenPersistentVolumeAccessModes(in.AccessModes) - } - if in.PersistentVolumeReclaimPolicy != "" { - att["persistent_volume_reclaim_policy"] = in.PersistentVolumeReclaimPolicy - } - if in.StorageClassName != "" { - att["storage_class_name"] = in.StorageClassName - } - if in.NodeAffinity != nil { - att["node_affinity"] = flattenVolumeNodeAffinity(in.NodeAffinity) - } - if in.MountOptions != nil { - att["mount_options"] = flattenPersistentVolumeMountOptions(in.MountOptions) - } - if in.VolumeMode != nil { - att["volume_mode"] = in.VolumeMode - } - return []interface{}{att} -} - -func flattenPhotonPersistentDiskVolumeSource(in *v1.PhotonPersistentDiskVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["pd_id"] = in.PdID - if in.FSType != "" { - att["fs_type"] = in.FSType - } - return []interface{}{att} -} - -func flattenCSIVolumeSource(in *v1.CSIPersistentVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["driver"] = in.Driver - att["volume_handle"] = in.VolumeHandle - att["read_only"] = in.ReadOnly - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if len(in.VolumeAttributes) > 0 { - att["volume_attributes"] = in.VolumeAttributes - } - if in.ControllerExpandSecretRef != nil { - att["controller_expand_secret_ref"] = flattenSecretReference(in.ControllerExpandSecretRef) - } - if in.ControllerPublishSecretRef != nil { - att["controller_publish_secret_ref"] = flattenSecretReference(in.ControllerPublishSecretRef) - } - if in.NodePublishSecretRef != nil { - att["node_publish_secret_ref"] = flattenSecretReference(in.NodePublishSecretRef) - } - if in.NodeStageSecretRef != nil { - att["node_stage_secret_ref"] = flattenSecretReference(in.NodeStageSecretRef) - } - return []interface{}{att} -} - -func flattenQuobyteVolumeSource(in *v1.QuobyteVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["registry"] = in.Registry - att["volume"] = in.Volume - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - if in.User != "" { - att["user"] = in.User - } - if in.Group != "" { - att["group"] = in.Group - } - return []interface{}{att} -} - -func flattenRBDVolumeSource(in *v1.RBDVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["ceph_monitors"] = newStringSet(schema.HashString, in.CephMonitors) - att["rbd_image"] = in.RBDImage - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if in.RBDPool != "" { - att["rbd_pool"] = in.RBDPool - } - if in.RadosUser != "" { - att["rados_user"] = in.RadosUser - } - if in.Keyring != "" { - att["keyring"] = in.Keyring - } - if in.SecretRef != nil { - att["secret_ref"] = flattenLocalObjectReference(in.SecretRef) - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenRBDPersistentVolumeSource(in *v1.RBDPersistentVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["ceph_monitors"] = newStringSet(schema.HashString, in.CephMonitors) - att["rbd_image"] = in.RBDImage - if in.FSType != "" { - att["fs_type"] = in.FSType - } - if in.RBDPool != "" { - att["rbd_pool"] = in.RBDPool - } - if in.RadosUser != "" { - att["rados_user"] = in.RadosUser - } - if in.Keyring != "" { - att["keyring"] = in.Keyring - } - if in.SecretRef != nil { - att["secret_ref"] = flattenSecretReference(in.SecretRef) - } - if in.ReadOnly != false { - att["read_only"] = in.ReadOnly - } - return []interface{}{att} -} - -func flattenVsphereVirtualDiskVolumeSource(in *v1.VsphereVirtualDiskVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["volume_path"] = in.VolumePath - if in.FSType != "" { - att["fs_type"] = in.FSType - } - return []interface{}{att} -} - -// Expanders - -func expandAWSElasticBlockStoreVolumeSource(l []interface{}) *v1.AWSElasticBlockStoreVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.AWSElasticBlockStoreVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.AWSElasticBlockStoreVolumeSource{ - VolumeID: in["volume_id"].(string), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["partition"].(int); ok { - obj.Partition = int32(v) - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandAzureDiskVolumeSource(l []interface{}) *v1.AzureDiskVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.AzureDiskVolumeSource{} - } - in := l[0].(map[string]interface{}) - cachingMode := v1.AzureDataDiskCachingMode(in["caching_mode"].(string)) - obj := &v1.AzureDiskVolumeSource{ - CachingMode: &cachingMode, - DiskName: in["disk_name"].(string), - DataDiskURI: in["data_disk_uri"].(string), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = ptrToString(v) - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = ptrToBool(v) - } - if v, ok := in["kind"].(string); ok && in["kind"].(string) != "" { - kind := v1.AzureDataDiskKind(v) - obj.Kind = &kind - } - return obj -} - -func expandAzureFileVolumeSource(l []interface{}) *v1.AzureFileVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.AzureFileVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.AzureFileVolumeSource{ - SecretName: in["secret_name"].(string), - ShareName: in["share_name"].(string), - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandAzureFilePersistentVolumeSource(l []interface{}) *v1.AzureFilePersistentVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.AzureFilePersistentVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.AzureFilePersistentVolumeSource{ - SecretName: in["secret_name"].(string), - ShareName: in["share_name"].(string), - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandCephFSVolumeSource(l []interface{}) *v1.CephFSVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.CephFSVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.CephFSVolumeSource{ - Monitors: sliceOfString(in["monitors"].(*schema.Set).List()), - } - if v, ok := in["path"].(string); ok { - obj.Path = v - } - if v, ok := in["user"].(string); ok { - obj.User = v - } - if v, ok := in["secret_file"].(string); ok { - obj.SecretFile = v - } - if v, ok := in["secret_ref"].([]interface{}); ok && len(v) > 0 { - obj.SecretRef = expandLocalObjectReference(v) - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandCephFSPersistentVolumeSource(l []interface{}) *v1.CephFSPersistentVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.CephFSPersistentVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.CephFSPersistentVolumeSource{ - Monitors: sliceOfString(in["monitors"].(*schema.Set).List()), - } - if v, ok := in["path"].(string); ok { - obj.Path = v - } - if v, ok := in["user"].(string); ok { - obj.User = v - } - if v, ok := in["secret_file"].(string); ok { - obj.SecretFile = v - } - if v, ok := in["secret_ref"].([]interface{}); ok && len(v) > 0 { - obj.SecretRef = expandSecretReference(v) - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandCinderPersistentVolumeSource(l []interface{}) *v1.CinderPersistentVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.CinderPersistentVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.CinderPersistentVolumeSource{ - VolumeID: in["volume_id"].(string), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandCinderVolumeSource(l []interface{}) *v1.CinderVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.CinderVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.CinderVolumeSource{ - VolumeID: in["volume_id"].(string), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandFCVolumeSource(l []interface{}) *v1.FCVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.FCVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.FCVolumeSource{ - TargetWWNs: sliceOfString(in["target_ww_ns"].(*schema.Set).List()), - Lun: ptrToInt32(int32(in["lun"].(int))), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandFlexPersistentVolumeSource(l []interface{}) *v1.FlexPersistentVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.FlexPersistentVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.FlexPersistentVolumeSource{ - Driver: in["driver"].(string), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["secret_ref"].([]interface{}); ok && len(v) > 0 { - obj.SecretRef = expandSecretReference(v) - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - if v, ok := in["options"].(map[string]interface{}); ok && len(v) > 0 { - obj.Options = expandStringMap(v) - } - return obj -} - -func expandFlexVolumeSource(l []interface{}) *v1.FlexVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.FlexVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.FlexVolumeSource{ - Driver: in["driver"].(string), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["secret_ref"].([]interface{}); ok && len(v) > 0 { - obj.SecretRef = expandLocalObjectReference(v) - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - if v, ok := in["options"].(map[string]interface{}); ok && len(v) > 0 { - obj.Options = expandStringMap(v) - } - return obj -} - -func expandFlockerVolumeSource(l []interface{}) *v1.FlockerVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.FlockerVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.FlockerVolumeSource{ - DatasetName: in["dataset_name"].(string), - DatasetUUID: in["dataset_uuid"].(string), - } - return obj -} - -func expandGCEPersistentDiskVolumeSource(l []interface{}) *v1.GCEPersistentDiskVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.GCEPersistentDiskVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.GCEPersistentDiskVolumeSource{ - PDName: in["pd_name"].(string), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["partition"].(int); ok { - obj.Partition = int32(v) - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandGlusterfsPersistentVolumeSource(l []interface{}) *v1.GlusterfsPersistentVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.GlusterfsPersistentVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.GlusterfsPersistentVolumeSource{ - EndpointsName: in["endpoints_name"].(string), - Path: in["path"].(string), - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandGlusterfsVolumeSource(l []interface{}) *v1.GlusterfsVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.GlusterfsVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.GlusterfsVolumeSource{ - EndpointsName: in["endpoints_name"].(string), - Path: in["path"].(string), - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandHostPathVolumeSource(l []interface{}) *v1.HostPathVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.HostPathVolumeSource{} - } - in := l[0].(map[string]interface{}) - typ := v1.HostPathType(in["type"].(string)) - obj := &v1.HostPathVolumeSource{ - Path: in["path"].(string), - Type: &typ, - } - return obj -} - -func expandLocalVolumeSource(l []interface{}) *v1.LocalVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.LocalVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.LocalVolumeSource{ - Path: in["path"].(string), - } - return obj -} - -func expandISCSIVolumeSource(l []interface{}) *v1.ISCSIVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.ISCSIVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.ISCSIVolumeSource{ - TargetPortal: in["target_portal"].(string), - IQN: in["iqn"].(string), - } - if v, ok := in["lun"].(int); ok { - obj.Lun = int32(v) - } - if v, ok := in["iscsi_interface"].(string); ok { - obj.ISCSIInterface = v - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandISCSIPersistentVolumeSource(l []interface{}) *v1.ISCSIPersistentVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.ISCSIPersistentVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.ISCSIPersistentVolumeSource{ - TargetPortal: in["target_portal"].(string), - IQN: in["iqn"].(string), - } - if v, ok := in["lun"].(int); ok { - obj.Lun = int32(v) - } - if v, ok := in["iscsi_interface"].(string); ok { - obj.ISCSIInterface = v - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandLocalObjectReference(l []interface{}) *v1.LocalObjectReference { - if len(l) == 0 || l[0] == nil { - return &v1.LocalObjectReference{} - } - in := l[0].(map[string]interface{}) - obj := &v1.LocalObjectReference{} - if v, ok := in["name"].(string); ok { - obj.Name = v - } - return obj -} - -func expandSecretReference(l []interface{}) *v1.SecretReference { - if len(l) == 0 || l[0] == nil { - return &v1.SecretReference{} - } - in := l[0].(map[string]interface{}) - obj := &v1.SecretReference{} - if v, ok := in["name"].(string); ok { - obj.Name = v - } - if v, ok := in["namespace"].(string); ok { - obj.Namespace = v - } - return obj -} - -func expandNFSVolumeSource(l []interface{}) *v1.NFSVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.NFSVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.NFSVolumeSource{ - Server: in["server"].(string), - Path: in["path"].(string), - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandPersistentVolumeSource(l []interface{}) v1.PersistentVolumeSource { - if len(l) == 0 || l[0] == nil { - return v1.PersistentVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := v1.PersistentVolumeSource{} - if v, ok := in["gce_persistent_disk"].([]interface{}); ok && len(v) > 0 { - obj.GCEPersistentDisk = expandGCEPersistentDiskVolumeSource(v) - } - if v, ok := in["aws_elastic_block_store"].([]interface{}); ok && len(v) > 0 { - obj.AWSElasticBlockStore = expandAWSElasticBlockStoreVolumeSource(v) - } - if v, ok := in["host_path"].([]interface{}); ok && len(v) > 0 { - obj.HostPath = expandHostPathVolumeSource(v) - } - if v, ok := in["local"].([]interface{}); ok && len(v) > 0 { - obj.Local = expandLocalVolumeSource(v) - } - if v, ok := in["glusterfs"].([]interface{}); ok && len(v) > 0 { - obj.Glusterfs = expandGlusterfsPersistentVolumeSource(v) - } - if v, ok := in["nfs"].([]interface{}); ok && len(v) > 0 { - obj.NFS = expandNFSVolumeSource(v) - } - if v, ok := in["rbd"].([]interface{}); ok && len(v) > 0 { - obj.RBD = expandRBDPersistentVolumeSource(v) - } - if v, ok := in["iscsi"].([]interface{}); ok && len(v) > 0 { - obj.ISCSI = expandISCSIPersistentVolumeSource(v) - } - if v, ok := in["cinder"].([]interface{}); ok && len(v) > 0 { - obj.Cinder = expandCinderPersistentVolumeSource(v) - } - if v, ok := in["ceph_fs"].([]interface{}); ok && len(v) > 0 { - obj.CephFS = expandCephFSPersistentVolumeSource(v) - } - if v, ok := in["fc"].([]interface{}); ok && len(v) > 0 { - obj.FC = expandFCVolumeSource(v) - } - if v, ok := in["flocker"].([]interface{}); ok && len(v) > 0 { - obj.Flocker = expandFlockerVolumeSource(v) - } - if v, ok := in["flex_volume"].([]interface{}); ok && len(v) > 0 { - obj.FlexVolume = expandFlexPersistentVolumeSource(v) - } - if v, ok := in["azure_file"].([]interface{}); ok && len(v) > 0 { - obj.AzureFile = expandAzureFilePersistentVolumeSource(v) - } - if v, ok := in["vsphere_volume"].([]interface{}); ok && len(v) > 0 { - obj.VsphereVolume = expandVsphereVirtualDiskVolumeSource(v) - } - if v, ok := in["quobyte"].([]interface{}); ok && len(v) > 0 { - obj.Quobyte = expandQuobyteVolumeSource(v) - } - if v, ok := in["azure_disk"].([]interface{}); ok && len(v) > 0 { - obj.AzureDisk = expandAzureDiskVolumeSource(v) - } - if v, ok := in["photon_persistent_disk"].([]interface{}); ok && len(v) > 0 { - obj.PhotonPersistentDisk = expandPhotonPersistentDiskVolumeSource(v) - } - if v, ok := in["csi"].([]interface{}); ok && len(v) > 0 { - obj.CSI = expandCSIPersistentDiskVolumeSource(v) - } - return obj -} - -func expandPersistentVolumeSpec(l []interface{}) (*v1.PersistentVolumeSpec, error) { - obj := &v1.PersistentVolumeSpec{} - if len(l) == 0 || l[0] == nil { - return obj, nil - } - in := l[0].(map[string]interface{}) - if v, ok := in["capacity"].(map[string]interface{}); ok && len(v) > 0 { - c, err := expandMapToResourceList(v) - if err != nil { - return obj, err - } - obj.Capacity = *c - } - if v, ok := in["persistent_volume_source"].([]interface{}); ok && len(v) > 0 { - obj.PersistentVolumeSource = expandPersistentVolumeSource(v) - } - if v, ok := in["access_modes"].(*schema.Set); ok && v.Len() > 0 { - obj.AccessModes = expandPersistentVolumeAccessModes(v.List()) - } - if v, ok := in["persistent_volume_reclaim_policy"].(string); ok { - obj.PersistentVolumeReclaimPolicy = v1.PersistentVolumeReclaimPolicy(v) - } - if v, ok := in["storage_class_name"].(string); ok { - obj.StorageClassName = v - } - if v, ok := in["node_affinity"].([]interface{}); ok && len(v) > 0 { - obj.NodeAffinity = expandVolumeNodeAffinity(v) - } - if v, ok := in["mount_options"].(*schema.Set); ok && v.Len() > 0 { - obj.MountOptions = schemaSetToStringArray(v) - } - if v, ok := in["volume_mode"].(string); ok { - volumeMode := v1.PersistentVolumeMode(v) - obj.VolumeMode = &volumeMode - } - return obj, nil -} - -func expandPhotonPersistentDiskVolumeSource(l []interface{}) *v1.PhotonPersistentDiskVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.PhotonPersistentDiskVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.PhotonPersistentDiskVolumeSource{ - PdID: in["pd_id"].(string), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - return obj -} - -func expandCSIPersistentDiskVolumeSource(l []interface{}) *v1.CSIPersistentVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.CSIPersistentVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.CSIPersistentVolumeSource{ - Driver: in["driver"].(string), - VolumeHandle: in["volume_handle"].(string), - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["volume_attributes"].(map[string]interface{}); ok && len(v) > 0 { - obj.VolumeAttributes = expandStringMap(v) - } - if v, ok := in["controller_publish_secret_ref"].([]interface{}); ok && len(v) > 0 { - obj.ControllerPublishSecretRef = expandSecretReference(v) - } - if v, ok := in["node_stage_secret_ref"].([]interface{}); ok && len(v) > 0 { - obj.NodeStageSecretRef = expandSecretReference(v) - } - if v, ok := in["node_publish_secret_ref"].([]interface{}); ok && len(v) > 0 { - obj.NodePublishSecretRef = expandSecretReference(v) - } - if v, ok := in["controller_expand_secret_ref"].([]interface{}); ok && len(v) > 0 { - obj.ControllerExpandSecretRef = expandSecretReference(v) - } - return obj -} - -func expandQuobyteVolumeSource(l []interface{}) *v1.QuobyteVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.QuobyteVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.QuobyteVolumeSource{ - Registry: in["registry"].(string), - Volume: in["volume"].(string), - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - if v, ok := in["user"].(string); ok { - obj.User = v - } - if v, ok := in["group"].(string); ok { - obj.Group = v - } - return obj -} - -func expandRBDVolumeSource(l []interface{}) *v1.RBDVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.RBDVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.RBDVolumeSource{ - CephMonitors: expandStringSlice(in["ceph_monitors"].(*schema.Set).List()), - RBDImage: in["rbd_image"].(string), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["rbd_pool"].(string); ok { - obj.RBDPool = v - } - if v, ok := in["rados_user"].(string); ok { - obj.RadosUser = v - } - if v, ok := in["keyring"].(string); ok { - obj.Keyring = v - } - if v, ok := in["secret_ref"].([]interface{}); ok && len(v) > 0 { - obj.SecretRef = expandLocalObjectReference(v) - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandRBDPersistentVolumeSource(l []interface{}) *v1.RBDPersistentVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.RBDPersistentVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.RBDPersistentVolumeSource{ - CephMonitors: expandStringSlice(in["ceph_monitors"].(*schema.Set).List()), - RBDImage: in["rbd_image"].(string), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - if v, ok := in["rbd_pool"].(string); ok { - obj.RBDPool = v - } - if v, ok := in["rados_user"].(string); ok { - obj.RadosUser = v - } - if v, ok := in["keyring"].(string); ok { - obj.Keyring = v - } - if v, ok := in["secret_ref"].([]interface{}); ok && len(v) > 0 { - obj.SecretRef = expandSecretReference(v) - } - if v, ok := in["read_only"].(bool); ok { - obj.ReadOnly = v - } - return obj -} - -func expandVsphereVirtualDiskVolumeSource(l []interface{}) *v1.VsphereVirtualDiskVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.VsphereVirtualDiskVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.VsphereVirtualDiskVolumeSource{ - VolumePath: in["volume_path"].(string), - } - if v, ok := in["fs_type"].(string); ok { - obj.FSType = v - } - return obj -} - -func patchPersistentVolumeSpec(pathPrefix, prefix string, d *schema.ResourceData) (PatchOperations, error) { - ops := make([]PatchOperation, 0) - prefix += ".0." - - if d.HasChange(prefix + "capacity") { - v := d.Get(prefix + "capacity").(map[string]interface{}) - capacity, err := expandMapToResourceList(v) - if err != nil { - return ops, err - } - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/capacity", - Value: capacity, - }) - } - - if d.HasChange(prefix + "persistent_volume_source") { - ops = append(ops, patchPersistentVolumeSource( - pathPrefix, - prefix+"persistent_volume_source.0.", - d, - )...) - } - - if d.HasChange(prefix + "access_modes") { - v := d.Get(prefix + "access_modes").(*schema.Set) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/accessModes", - Value: expandPersistentVolumeAccessModes(v.List()), - }) - } - if d.HasChange(prefix + "persistent_volume_reclaim_policy") { - v := d.Get(prefix + "persistent_volume_reclaim_policy").(string) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/persistentVolumeReclaimPolicy", - Value: v1.PersistentVolumeReclaimPolicy(v), - }) - } - if d.HasChange(prefix + "storage_class_name") { - o, n := d.GetChange(prefix + "storage_class_name") - if v, ok := o.(string); ok && len(v) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/storageClassName", - Value: n.(string), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/storageClassName", - Value: n.(string), - }) - } - } - if d.HasChange(prefix + "node_affinity") { - v := d.Get(prefix + "node_affinity").([]interface{}) - nodeAffinity := expandVolumeNodeAffinity(v) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/nodeAffinity", - Value: nodeAffinity, - }) - } - if d.HasChange(prefix + "mount_options") { - v := d.Get(prefix + "mount_options").(*schema.Set) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/mountOptions", - Value: expandPersistentVolumeAccessModes(v.List()), - }) - } - - return ops, nil -} - -func patchPersistentVolumeSource(pathPrefix, prefix string, d *schema.ResourceData) []PatchOperation { - ops := make([]PatchOperation, 0) - - if d.HasChange(prefix + "gce_persistent_disk") { - oldIn, newIn := d.GetChange(prefix + "gce_persistent_disk") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/gcePersistentDisk", - Value: expandGCEPersistentDiskVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/gcePersistentDisk", - Value: expandGCEPersistentDiskVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/gcePersistentDisk"}) - } - } - - if d.HasChange(prefix + "aws_elastic_block_store") { - oldIn, newIn := d.GetChange(prefix + "aws_elastic_block_store") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/awsElasticBlockStore", - Value: expandAWSElasticBlockStoreVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/awsElasticBlockStore", - Value: expandAWSElasticBlockStoreVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/awsElasticBlockStore"}) - } - } - - if d.HasChange(prefix + "host_path") { - oldIn, newIn := d.GetChange(prefix + "host_path") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/hostPath", - Value: expandHostPathVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/hostPath", - Value: expandHostPathVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/hostPath"}) - } - } - - if d.HasChange(prefix + "glusterfs") { - oldIn, newIn := d.GetChange(prefix + "glusterfs") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/glusterfs", - Value: expandGlusterfsVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/glusterfs", - Value: expandGlusterfsVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/glusterfs"}) - } - } - - if d.HasChange(prefix + "nfs") { - oldIn, newIn := d.GetChange(prefix + "nfs") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/nfs", - Value: expandNFSVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/nfs", - Value: expandNFSVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/nfs"}) - } - } - - if d.HasChange(prefix + "rbd") { - oldIn, newIn := d.GetChange(prefix + "rbd") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/rbd", - Value: expandRBDVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/rbd", - Value: expandRBDVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/rbd"}) - } - } - - if d.HasChange(prefix + "iscsi") { - oldIn, newIn := d.GetChange(prefix + "iscsi") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/iscsi", - Value: expandISCSIVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/iscsi", - Value: expandISCSIVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/iscsi"}) - } - } - - if d.HasChange(prefix + "cinder") { - oldIn, newIn := d.GetChange(prefix + "cinder") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/cinder", - Value: expandCinderVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/cinder", - Value: expandCinderVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/cinder"}) - } - } - - if d.HasChange(prefix + "ceph_fs") { - oldIn, newIn := d.GetChange(prefix + "ceph_fs") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/cephfs", - Value: expandCephFSVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/cephfs", - Value: expandCephFSVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/cephfs"}) - } - } - - if d.HasChange(prefix + "fc") { - oldIn, newIn := d.GetChange(prefix + "fc") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/fc", - Value: expandFCVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/fc", - Value: expandFCVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/fc"}) - } - } - - if d.HasChange(prefix + "flocker") { - oldIn, newIn := d.GetChange(prefix + "flocker") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/flocker", - Value: expandFlockerVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/flocker", - Value: expandFlockerVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/flocker"}) - } - } - - if d.HasChange(prefix + "flex_volume") { - oldIn, newIn := d.GetChange(prefix + "flex_volume") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/flexVolume", - Value: expandFlexVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/flexVolume", - Value: expandFlexVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/flexVolume"}) - } - } - - if d.HasChange(prefix + "azure_file") { - oldIn, newIn := d.GetChange(prefix + "azure_file") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/azureFile", - Value: expandAzureFileVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/azureFile", - Value: expandAzureFileVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/azureFile"}) - } - } - - if d.HasChange(prefix + "vsphere_volume") { - oldIn, newIn := d.GetChange(prefix + "vsphere_volume") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/vsphereVolume", - Value: expandVsphereVirtualDiskVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/vsphereVolume", - Value: expandVsphereVirtualDiskVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/vsphereVolume"}) - } - } - - if d.HasChange(prefix + "quobyte") { - oldIn, newIn := d.GetChange(prefix + "quobyte") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/quobyte", - Value: expandQuobyteVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/quobyte", - Value: expandQuobyteVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/quobyte"}) - } - } - - if d.HasChange(prefix + "azure_disk") { - oldIn, newIn := d.GetChange(prefix + "azure_disk") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/azureDisk", - Value: expandAzureDiskVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/azureDisk", - Value: expandAzureDiskVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/azureDisk"}) - } - } - - if d.HasChange(prefix + "photon_persistent_disk") { - oldIn, newIn := d.GetChange(prefix + "photon_persistent_disk") - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/photonPersistentDisk", - Value: expandPhotonPersistentDiskVolumeSource(newV), - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/photonPersistentDisk", - Value: expandPhotonPersistentDiskVolumeSource(newV), - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: pathPrefix + "/photonPersistentDisk"}) - } - } - - if d.HasChange(prefix + "csi") { - path := pathPrefix + "/csi" - oldIn, newIn := d.GetChange(path) - oldV, oldOk := oldIn.([]interface{}) - newV, newOk := newIn.([]interface{}) - value := expandCSIPersistentDiskVolumeSource(newV) - - if newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: path, - Value: value, - }) - } else { - ops = append(ops, &AddOperation{ - Path: path, - Value: value, - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{Path: path}) - } - } - - return ops -} - -func flattenVolumeNodeAffinity(in *v1.VolumeNodeAffinity) []interface{} { - att := make(map[string]interface{}) - nodeSelector := map[string]interface{}{ - "node_selector_term": flattenNodeSelectorTerms(in.Required.NodeSelectorTerms), - } - att["required"] = []interface{}{nodeSelector} - return []interface{}{att} -} - -func expandVolumeNodeAffinity(l []interface{}) *v1.VolumeNodeAffinity { - if len(l) == 0 || l[0] == nil { - return &v1.VolumeNodeAffinity{} - } - in := l[0].(map[string]interface{}) - nodeSelectorList := in["required"].([]interface{}) - - if len(nodeSelectorList) == 0 || nodeSelectorList[0] == nil { - return &v1.VolumeNodeAffinity{} - } - nodeSelector := nodeSelectorList[0].(map[string]interface{}) - - if len(nodeSelector) == 0 || nodeSelectorList[0] == nil { - return &v1.VolumeNodeAffinity{} - } - obj := &v1.VolumeNodeAffinity{ - Required: &v1.NodeSelector{ - NodeSelectorTerms: expandNodeSelectorTerms(nodeSelector["node_selector_term"].([]interface{})), - }, - } - return obj -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_pod_disruption_budget.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_pod_disruption_budget.go deleted file mode 100644 index 2dd264a70da..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_pod_disruption_budget.go +++ /dev/null @@ -1,101 +0,0 @@ -package kubernetes - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/policy/v1beta1" - "k8s.io/apimachinery/pkg/util/intstr" -) - -func expandPodDisruptionBudgetSpec(in []interface{}) (*api.PodDisruptionBudgetSpec, error) { - spec := &api.PodDisruptionBudgetSpec{} - if len(in) == 0 || in[0] == nil { - return nil, fmt.Errorf("failed to expand PodDisruptionBudget.Spec: null or empty input") - } - m := in[0].(map[string]interface{}) - if v, ok := m["max_unavailable"].(string); ok && len(v) > 0 { - val := intstr.Parse(v) - spec.MaxUnavailable = &val - } - if v, ok := m["min_available"].(string); ok && len(v) > 0 { - val := intstr.Parse(v) - spec.MinAvailable = &val - } - if v, ok := m["selector"].([]interface{}); ok && len(v) > 0 { - spec.Selector = expandLabelSelector(v) - } - - return spec, nil -} - -func flattenPodDisruptionBudgetSpec(spec api.PodDisruptionBudgetSpec) []interface{} { - m := make(map[string]interface{}, 0) - if spec.MaxUnavailable != nil { - m["max_unavailable"] = spec.MaxUnavailable.String() - } - if spec.MinAvailable != nil { - m["min_available"] = spec.MinAvailable.String() - } - if spec.Selector != nil { - m["selector"] = flattenLabelSelector(spec.Selector) - } - - return []interface{}{m} -} - -// Currently unused, but will be useful for Kubernetes 1.15 when patching is allowed. -func patchPodDisruptionBudgetSpec(prefix string, pathPrefix string, d *schema.ResourceData) (*[]PatchOperation, error) { - ops := make([]PatchOperation, 0) - - if d.HasChange(prefix + "max_unavailable") { - old, new := d.GetChange(prefix + "max_unavailable") - oldV, oldOk := old.(string) - if newV, newOk := new.(string); newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/maxUnavailable", - Value: newV, - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/maxUnavailable", - Value: newV, - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{ - Path: pathPrefix + "/maxUnavailable", - }) - } - } - if d.HasChange(prefix + "min_available") { - old, new := d.GetChange(prefix + "min_available") - oldV, oldOk := old.(string) - if newV, newOk := new.(string); newOk && len(newV) > 0 { - if oldOk && len(oldV) > 0 { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/minAvailable", - Value: newV, - }) - } else { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "/minAvailable", - Value: newV, - }) - } - } else if oldOk && len(oldV) > 0 { - ops = append(ops, &RemoveOperation{ - Path: pathPrefix + "/minAvailable", - }) - } - } - if d.HasChange(prefix + "selector") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/selector", - Value: expandLabelSelector(d.Get(prefix + "selector").([]interface{})), - }) - } - - return &ops, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_pod_security_policy_spec.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_pod_security_policy_spec.go deleted file mode 100644 index e2cd200e42f..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_pod_security_policy_spec.go +++ /dev/null @@ -1,658 +0,0 @@ -package kubernetes - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - - v1 "k8s.io/api/core/v1" - v1beta1 "k8s.io/api/policy/v1beta1" -) - -func flattenPodSecurityPolicySpec(in v1beta1.PodSecurityPolicySpec) []interface{} { - spec := make(map[string]interface{}) - - if in.AllowPrivilegeEscalation != nil { - spec["allow_privilege_escalation"] = in.AllowPrivilegeEscalation - } - - if len(in.AllowedCapabilities) > 0 { - spec["allowed_capabilities"] = flattenCapability(in.AllowedCapabilities) - } - - if len(in.AllowedFlexVolumes) > 0 { - spec["allowed_flex_volumes"] = flattenAllowedFlexVolumes(in.AllowedFlexVolumes) - } - - if len(in.AllowedHostPaths) > 0 { - spec["allowed_host_paths"] = flattenAllowedHostPaths(in.AllowedHostPaths) - } - - if len(in.AllowedProcMountTypes) > 0 { - spec["allowed_proc_mount_types"] = flattenAllowedProcMountTypes(in.AllowedProcMountTypes) - } - - if len(in.AllowedUnsafeSysctls) > 0 { - spec["allowed_unsafe_sysctls"] = flattenListOfStrings(in.AllowedUnsafeSysctls) - } - - if len(in.DefaultAddCapabilities) > 0 { - spec["default_add_capabilities"] = flattenCapability(in.DefaultAddCapabilities) - } - - if in.DefaultAllowPrivilegeEscalation != nil { - spec["default_allow_privilege_escalation"] = in.DefaultAllowPrivilegeEscalation - } - - if len(in.ForbiddenSysctls) > 0 { - spec["forbidden_sysctls"] = flattenListOfStrings(in.ForbiddenSysctls) - } - - spec["fs_group"] = flattenFSGroup(in.FSGroup) - spec["host_ipc"] = in.HostIPC - spec["host_network"] = in.HostNetwork - spec["host_pid"] = in.HostPID - - if len(in.HostPorts) > 0 { - spec["host_ports"] = flattenHostPortRangeSlice(in.HostPorts) - } - - spec["privileged"] = in.Privileged - spec["read_only_root_filesystem"] = in.ReadOnlyRootFilesystem - - if len(in.RequiredDropCapabilities) > 0 { - spec["required_drop_capabilities"] = flattenCapability(in.RequiredDropCapabilities) - } - - spec["run_as_user"] = flattenRunAsUser(in.RunAsUser) - - if in.RunAsGroup != nil { - spec["run_as_group"] = flattenRunAsGroup(*in.RunAsGroup) - } - - spec["se_linux"] = flattenSELinuxStrategy(in.SELinux) - spec["supplemental_groups"] = flattenSupplementalGroups(in.SupplementalGroups) - spec["volumes"] = flattenFSTypes(in.Volumes) - - return []interface{}{spec} -} - -func flattenAllowedFlexVolumes(in []v1beta1.AllowedFlexVolume) []interface{} { - result := make([]interface{}, len(in), len(in)) - - for k, v := range in { - result[k] = map[string]interface{}{ - "driver": v.Driver, - } - } - - return result -} - -func flattenAllowedHostPaths(in []v1beta1.AllowedHostPath) []interface{} { - result := make([]interface{}, len(in), len(in)) - - for k, v := range in { - result[k] = map[string]interface{}{ - "path_prefix": v.PathPrefix, - "read_only": v.ReadOnly, - } - } - - return result -} - -func flattenListOfStrings(in []string) []interface{} { - result := make([]interface{}, len(in), len(in)) - - for k, v := range in { - result[k] = v - } - - return result -} - -func flattenAllowedProcMountTypes(in []v1.ProcMountType) []interface{} { - result := make([]interface{}, len(in), len(in)) - - for k, v := range in { - result[k] = fmt.Sprintf("%v", v) - } - - return result -} - -func flattenFSGroup(in v1beta1.FSGroupStrategyOptions) []interface{} { - result := map[string]interface{}{ - "rule": in.Rule, - "range": flattenIDRangeSlice(in.Ranges), - } - - return []interface{}{result} -} - -func flattenIDRangeSlice(in []v1beta1.IDRange) []interface{} { - result := make([]interface{}, len(in), len(in)) - - for k, v := range in { - result[k] = map[string]interface{}{ - "min": int(v.Min), - "max": int(v.Max), - } - } - - return result -} - -func flattenHostPortRangeSlice(in []v1beta1.HostPortRange) []interface{} { - result := make([]interface{}, len(in), len(in)) - - for k, v := range in { - result[k] = map[string]interface{}{ - "min": int(v.Min), - "max": int(v.Max), - } - } - - return result -} - -func flattenRunAsUser(in v1beta1.RunAsUserStrategyOptions) []interface{} { - result := map[string]interface{}{ - "rule": fmt.Sprintf("%v", in.Rule), - "range": flattenIDRangeSlice(in.Ranges), - } - - return []interface{}{result} -} - -func flattenRunAsGroup(in v1beta1.RunAsGroupStrategyOptions) []interface{} { - result := map[string]interface{}{ - "rule": fmt.Sprintf("%v", in.Rule), - "range": flattenIDRangeSlice(in.Ranges), - } - - return []interface{}{result} -} - -func flattenSELinuxStrategy(in v1beta1.SELinuxStrategyOptions) []interface{} { - result := map[string]interface{}{ - "rule": fmt.Sprintf("%v", in.Rule), - } - - if in.SELinuxOptions != nil { - result["se_linux_options"] = flattenSeLinuxOptions(in.SELinuxOptions) - } - - return []interface{}{result} -} - -func flattenSupplementalGroups(in v1beta1.SupplementalGroupsStrategyOptions) []interface{} { - result := map[string]interface{}{ - "rule": fmt.Sprintf("%v", in.Rule), - "range": flattenIDRangeSlice(in.Ranges), - } - - return []interface{}{result} -} - -func flattenFSTypes(in []v1beta1.FSType) []interface{} { - result := make([]interface{}, len(in), len(in)) - - for k, v := range in { - result[k] = fmt.Sprintf("%v", v) - } - - return result -} - -func expandPodSecurityPolicySpec(in []interface{}) (v1beta1.PodSecurityPolicySpec, error) { - spec := v1beta1.PodSecurityPolicySpec{} - if len(in) == 0 || in[0] == nil { - return spec, fmt.Errorf("failed to expand PodSecurityPolicy.Spec: null or empty input") - } - - m, ok := in[0].(map[string]interface{}) - if !ok { - return spec, fmt.Errorf("failed to expand PodSecurityPolicy.Spec: malformed input") - } - - if v, ok := m["allow_privilege_escalation"].(bool); ok { - spec.AllowPrivilegeEscalation = ptrToBool(v) - } - - if v, ok := m["allowed_capabilities"].([]interface{}); ok && len(v) > 0 { - spec.AllowedCapabilities = expandCapabilitySlice(v) - } - - if v, ok := m["allowed_flex_volumes"].([]interface{}); ok && len(v) > 0 { - spec.AllowedFlexVolumes = expandAllowedFlexVolumeSlice(v) - } - - if v, ok := m["allowed_host_paths"].([]interface{}); ok && len(v) > 0 { - spec.AllowedHostPaths = expandAllowedHostPathSlice(v) - } - - if v, ok := m["allowed_proc_mount_types"].([]interface{}); ok && len(v) > 0 { - spec.AllowedProcMountTypes = expandAllowedProcMountTypes(v) - } - - if v, ok := m["allowed_unsafe_sysctls"].([]interface{}); ok && len(v) > 0 { - spec.AllowedUnsafeSysctls = expandStringSlice(v) - } - - if v, ok := m["default_add_capabilities"].([]interface{}); ok && len(v) > 0 { - spec.DefaultAddCapabilities = expandCapabilitySlice(v) - } - - if v, ok := m["default_allow_privilege_escalation"].(bool); ok { - spec.DefaultAllowPrivilegeEscalation = ptrToBool(v) - } - - if v, ok := m["forbidden_sysctls"].([]interface{}); ok && len(v) > 0 { - spec.ForbiddenSysctls = expandStringSlice(v) - } - - if v, ok := m["fs_group"].([]interface{}); ok && len(v) > 0 { - spec.FSGroup = expandFSGroup(v) - } - - if v, ok := m["host_ipc"].(bool); ok { - spec.HostIPC = v - } - - if v, ok := m["host_network"].(bool); ok { - spec.HostNetwork = v - } - - if v, ok := m["host_pid"].(bool); ok { - spec.HostPID = v - } - - if v, ok := m["host_ports"].([]interface{}); ok && len(v) > 0 { - spec.HostPorts = expandHostPortRangeSlice(v) - } - - if v, ok := m["privileged"].(bool); ok { - spec.Privileged = v - } - - if v, ok := m["read_only_root_filesystem"].(bool); ok { - spec.ReadOnlyRootFilesystem = v - } - - if v, ok := m["required_drop_capabilities"].([]interface{}); ok && len(v) > 0 { - spec.RequiredDropCapabilities = expandCapabilitySlice(v) - } - - if v, ok := m["run_as_user"].([]interface{}); ok && len(v) > 0 { - spec.RunAsUser = expandRunAsUser(v) - } - - if v, ok := m["run_as_group"].([]interface{}); ok && len(v) > 0 { - spec.RunAsGroup = expandRunAsGroup(v) - } - - if v, ok := m["se_linux"].([]interface{}); ok && len(v) > 0 { - spec.SELinux = expandSELinux(v) - } - - if v, ok := m["supplemental_groups"].([]interface{}); ok && len(v) > 0 { - spec.SupplementalGroups = expandSupplementalGroup(v) - } - - if v, ok := m["volumes"].([]interface{}); ok && len(v) > 0 { - spec.Volumes = expandVolumeFSTypeSlice(v) - } - - return spec, nil -} - -func expandAllowedFlexVolumeSlice(in []interface{}) []v1beta1.AllowedFlexVolume { - result := make([]v1beta1.AllowedFlexVolume, len(in), len(in)) - for k, v := range in { - result[k] = v1beta1.AllowedFlexVolume{ - Driver: v.(string), - } - } - return result -} - -func expandAllowedHostPathSlice(in []interface{}) []v1beta1.AllowedHostPath { - result := make([]v1beta1.AllowedHostPath, len(in), len(in)) - for k, v := range in { - if m, ok := v.(map[string]interface{}); ok { - hp := v1beta1.AllowedHostPath{ - PathPrefix: m["path_prefix"].(string), - } - - if ro, ok := m["read_only"].(bool); ok { - hp.ReadOnly = ro - } - - result[k] = hp - } - } - return result -} - -func expandAllowedProcMountTypes(in []interface{}) []v1.ProcMountType { - result := make([]v1.ProcMountType, len(in), len(in)) - - for k, v := range in { - result[k] = v1.ProcMountType(v.(string)) - } - - return result -} - -func expandFSGroup(in []interface{}) v1beta1.FSGroupStrategyOptions { - result := v1beta1.FSGroupStrategyOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["rule"].(string); ok { - result.Rule = v1beta1.FSGroupStrategyType(v) - } - - if v, ok := m["range"].([]interface{}); ok && len(v) > 0 { - result.Ranges = expandIDRangeSlice(v) - } - - return result -} - -func expandIDRangeSlice(in []interface{}) []v1beta1.IDRange { - result := make([]v1beta1.IDRange, len(in), len(in)) - - for k, v := range in { - if m, ok := v.(map[string]interface{}); ok { - result[k] = v1beta1.IDRange{ - Min: int64(m["min"].(int)), - Max: int64(m["max"].(int)), - } - } - } - - return result -} - -func expandHostPortRangeSlice(in []interface{}) []v1beta1.HostPortRange { - result := make([]v1beta1.HostPortRange, len(in), len(in)) - - for k, v := range in { - if m, ok := v.(map[string]interface{}); ok { - result[k] = v1beta1.HostPortRange{ - Min: int32(m["min"].(int)), - Max: int32(m["max"].(int)), - } - } - } - - return result -} - -func expandRunAsUser(in []interface{}) v1beta1.RunAsUserStrategyOptions { - result := v1beta1.RunAsUserStrategyOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["rule"].(string); ok { - result.Rule = v1beta1.RunAsUserStrategy(v) - } - - if v, ok := m["range"].([]interface{}); ok && len(v) > 0 { - result.Ranges = expandIDRangeSlice(v) - } - - return result -} - -func expandRunAsGroup(in []interface{}) *v1beta1.RunAsGroupStrategyOptions { - result := v1beta1.RunAsGroupStrategyOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["rule"].(string); ok { - result.Rule = v1beta1.RunAsGroupStrategy(v) - } - - if v, ok := m["range"].([]interface{}); ok && len(v) > 0 { - result.Ranges = expandIDRangeSlice(v) - } - - return &result -} - -func expandSELinux(in []interface{}) v1beta1.SELinuxStrategyOptions { - result := v1beta1.SELinuxStrategyOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["rule"].(string); ok { - result.Rule = v1beta1.SELinuxStrategy(v) - } - - if v, ok := m["se_linux_options"].([]interface{}); ok && len(v) > 0 { - result.SELinuxOptions = expandSELinuxOptions(v) - } - - return result -} - -func expandSELinuxOptions(in []interface{}) *v1.SELinuxOptions { - result := v1.SELinuxOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["level"].(string); ok { - result.Level = v - } - - if v, ok := m["user"].(string); ok { - result.User = v - } - - if v, ok := m["role"].(string); ok { - result.Role = v - } - - if v, ok := m["type"].(string); ok { - result.Type = v - } - - return &result -} - -func expandSupplementalGroup(in []interface{}) v1beta1.SupplementalGroupsStrategyOptions { - result := v1beta1.SupplementalGroupsStrategyOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["rule"].(string); ok { - result.Rule = v1beta1.SupplementalGroupsStrategyType(v) - } - - if v, ok := m["range"].([]interface{}); ok && len(v) > 0 { - result.Ranges = expandIDRangeSlice(v) - } - - return result -} - -func expandVolumeFSTypeSlice(in []interface{}) []v1beta1.FSType { - result := make([]v1beta1.FSType, len(in), len(in)) - for k, v := range in { - if s, ok := v.(string); ok { - result[k] = v1beta1.FSType(s) - } - } - - return result -} - -// Patchers - -func patchPodSecurityPolicySpec(keyPrefix string, pathPrefix string, d *schema.ResourceData) (*PatchOperations, error) { - ops := make(PatchOperations, 0, 0) - - if d.HasChange(keyPrefix + "allow_privilege_escalation") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowPrivilegeEscalation", - Value: d.Get(keyPrefix + "allow_privilege_escalation").(bool), - }) - } - - if d.HasChange(keyPrefix + "allowed_capabilities") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowedCapabilities", - Value: d.Get(keyPrefix + "allowed_capabilities").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "allowed_flex_volumes") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowedFlexVolumes", - Value: d.Get(keyPrefix + "allowed_flex_volumes").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "allowed_host_paths") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowedHostPaths", - Value: d.Get(keyPrefix + "allowed_host_paths").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "allowed_proc_mount_types") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowedProcMountTypes", - Value: d.Get(keyPrefix + "allowed_proc_mount_types").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "allowed_unsafe_sysctls") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowedUnsafeSysctls", - Value: d.Get(keyPrefix + "allowed_unsafe_sysctls").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "default_add_capabilities") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/defaultAddCapabilities", - Value: d.Get(keyPrefix + "default_add_capabilities").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "default_allow_privilege_escalation") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/defaultAllowPrivilegeEscalation", - Value: d.Get(keyPrefix + "default_allow_privilege_escalation").(bool), - }) - } - - if d.HasChange(keyPrefix + "forbidden_sysctls") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/forbiddenSysctls", - Value: d.Get(keyPrefix + "forbidden_sysctls").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "fs_group") { - fsGroup := expandFSGroup(d.Get(keyPrefix + "fs_group").([]interface{})) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/fsGroup", - Value: fsGroup, - }) - } - - if d.HasChange(keyPrefix + "host_ipc") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/hostIPC", - Value: d.Get(keyPrefix + "host_ipc").(bool), - }) - } - - if d.HasChange(keyPrefix + "host_network") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/hostNetwork", - Value: d.Get(keyPrefix + "host_network").(bool), - }) - } - - if d.HasChange(keyPrefix + "host_pid") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/hostPID", - Value: d.Get(keyPrefix + "host_pid").(bool), - }) - } - - if d.HasChange(keyPrefix + "host_ports") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/hostPorts", - Value: d.Get(keyPrefix + "host_ports").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "privileged") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/privileged", - Value: d.Get(keyPrefix + "privileged").(bool), - }) - } - - if d.HasChange(keyPrefix + "readonly_root_filesystem") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/readOnlyRootFilesystem", - Value: d.Get(keyPrefix + "readonly_root_filesystem").(bool), - }) - } - - if d.HasChange(keyPrefix + "required_drop_capabilities") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/requiredDropCapabilities", - Value: d.Get(keyPrefix + "required_drop_capabilities").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "run_as_group") { - runAsGroup := expandRunAsGroup(d.Get(keyPrefix + "run_as_group").([]interface{})) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/runAsGroup", - Value: runAsGroup, - }) - } - - if d.HasChange(keyPrefix + "run_as_user") { - runAsUser := expandRunAsUser(d.Get(keyPrefix + "run_as_user").([]interface{})) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/runAsUser", - Value: runAsUser, - }) - } - - if d.HasChange(keyPrefix + "se_linux") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/seLinux", - Value: d.Get(keyPrefix + "se_linux").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "supplemental_groups") { - supplementalGroups := expandSupplementalGroup(d.Get(keyPrefix + "supplemental_groups").([]interface{})) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/supplementalGroups", - Value: supplementalGroups, - }) - } - - if d.HasChange(keyPrefix + "volumes") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/volumes", - Value: d.Get(keyPrefix + "volumes").([]interface{}), - }) - } - - return &ops, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_service_spec.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_service_spec.go deleted file mode 100644 index 069b394889b..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_service_spec.go +++ /dev/null @@ -1,246 +0,0 @@ -package kubernetes - -import ( - gversion "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/apimachinery/pkg/version" -) - -// Flatteners - -func flattenServicePort(in []v1.ServicePort) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, n := range in { - m := make(map[string]interface{}) - m["name"] = n.Name - m["protocol"] = string(n.Protocol) - m["port"] = int(n.Port) - m["target_port"] = n.TargetPort.String() - m["node_port"] = int(n.NodePort) - - att[i] = m - } - return att -} - -func flattenServiceSpec(in v1.ServiceSpec) []interface{} { - att := make(map[string]interface{}) - if len(in.Ports) > 0 { - att["port"] = flattenServicePort(in.Ports) - } - if len(in.Selector) > 0 { - att["selector"] = in.Selector - } - if in.ClusterIP != "" { - att["cluster_ip"] = in.ClusterIP - } - if in.Type != "" { - att["type"] = string(in.Type) - } - if len(in.ExternalIPs) > 0 { - att["external_ips"] = newStringSet(schema.HashString, in.ExternalIPs) - } - if in.SessionAffinity != "" { - att["session_affinity"] = string(in.SessionAffinity) - } - if in.LoadBalancerIP != "" { - att["load_balancer_ip"] = in.LoadBalancerIP - } - if len(in.LoadBalancerSourceRanges) > 0 { - att["load_balancer_source_ranges"] = newStringSet(schema.HashString, in.LoadBalancerSourceRanges) - } - if in.ExternalName != "" { - att["external_name"] = in.ExternalName - } - att["publish_not_ready_addresses"] = in.PublishNotReadyAddresses - - if in.ExternalTrafficPolicy != "" { - att["external_traffic_policy"] = string(in.ExternalTrafficPolicy) - } - - att["health_check_node_port"] = int(in.HealthCheckNodePort) - - return []interface{}{att} -} - -func flattenLoadBalancerIngress(in []v1.LoadBalancerIngress) []interface{} { - out := make([]interface{}, len(in), len(in)) - for i, ingress := range in { - att := make(map[string]interface{}) - - att["ip"] = ingress.IP - att["hostname"] = ingress.Hostname - - out[i] = att - } - return out -} - -// Expanders - -func expandServicePort(l []interface{}) []v1.ServicePort { - if len(l) == 0 || l[0] == nil { - return []v1.ServicePort{} - } - obj := make([]v1.ServicePort, len(l), len(l)) - for i, n := range l { - cfg := n.(map[string]interface{}) - obj[i] = v1.ServicePort{ - Port: int32(cfg["port"].(int)), - TargetPort: intstr.Parse(cfg["target_port"].(string)), - } - if v, ok := cfg["name"].(string); ok { - obj[i].Name = v - } - if v, ok := cfg["protocol"].(string); ok { - obj[i].Protocol = v1.Protocol(v) - } - if v, ok := cfg["node_port"].(int); ok { - obj[i].NodePort = int32(v) - } - } - return obj -} - -func expandServiceSpec(l []interface{}) v1.ServiceSpec { - if len(l) == 0 || l[0] == nil { - return v1.ServiceSpec{} - } - in := l[0].(map[string]interface{}) - obj := v1.ServiceSpec{} - - if v, ok := in["port"].([]interface{}); ok && len(v) > 0 { - obj.Ports = expandServicePort(v) - } - if v, ok := in["selector"].(map[string]interface{}); ok && len(v) > 0 { - obj.Selector = expandStringMap(v) - } - if v, ok := in["cluster_ip"].(string); ok { - obj.ClusterIP = v - } - if v, ok := in["type"].(string); ok { - obj.Type = v1.ServiceType(v) - } - if v, ok := in["external_ips"].(*schema.Set); ok && v.Len() > 0 { - obj.ExternalIPs = sliceOfString(v.List()) - } - if v, ok := in["session_affinity"].(string); ok { - obj.SessionAffinity = v1.ServiceAffinity(v) - } - if v, ok := in["load_balancer_ip"].(string); ok { - obj.LoadBalancerIP = v - } - if v, ok := in["load_balancer_source_ranges"].(*schema.Set); ok && v.Len() > 0 { - obj.LoadBalancerSourceRanges = sliceOfString(v.List()) - } - if v, ok := in["external_name"].(string); ok { - obj.ExternalName = v - } - if v, ok := in["publish_not_ready_addresses"].(bool); ok { - obj.PublishNotReadyAddresses = v - } - if v, ok := in["external_traffic_policy"].(string); ok { - obj.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyType(v) - } - if v, ok := in["health_check_node_port"].(int); ok { - obj.HealthCheckNodePort = int32(v) - } - - return obj -} - -// Patch Ops - -func patchServiceSpec(keyPrefix, pathPrefix string, d *schema.ResourceData, v *version.Info) (PatchOperations, error) { - ops := make([]PatchOperation, 0, 0) - if d.HasChange(keyPrefix + "selector") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "selector", - Value: d.Get(keyPrefix + "selector").(map[string]interface{}), - }) - } - if d.HasChange(keyPrefix + "type") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "type", - Value: d.Get(keyPrefix + "type").(string), - }) - } - if d.HasChange(keyPrefix + "session_affinity") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "sessionAffinity", - Value: d.Get(keyPrefix + "session_affinity").(string), - }) - } - if d.HasChange(keyPrefix + "load_balancer_ip") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "loadBalancerIP", - Value: d.Get(keyPrefix + "load_balancer_ip").(string), - }) - } - if d.HasChange(keyPrefix + "load_balancer_source_ranges") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "loadBalancerSourceRanges", - Value: d.Get(keyPrefix + "load_balancer_source_ranges").(*schema.Set).List(), - }) - } - if d.HasChange(keyPrefix + "port") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "ports", - Value: expandServicePort(d.Get(keyPrefix + "port").([]interface{})), - }) - } - if d.HasChange(keyPrefix + "external_ips") { - k8sVersion, err := gversion.NewVersion(v.String()) - if err != nil { - return nil, err - } - v1_8_0, _ := gversion.NewVersion("1.8.0") - if k8sVersion.LessThan(v1_8_0) { - // If we haven't done this the deprecated field would have priority - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "deprecatedPublicIPs", - Value: nil, - }) - } - - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "externalIPs", - Value: d.Get(keyPrefix + "external_ips").(*schema.Set).List(), - }) - } - if d.HasChange(keyPrefix + "external_name") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "externalName", - Value: d.Get(keyPrefix + "external_name").(string), - }) - } - if d.HasChange(keyPrefix + "external_traffic_policy") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "externalTrafficPolicy", - Value: d.Get(keyPrefix + "external_traffic_policy").(string), - }) - } - if d.HasChange(keyPrefix + "publish_not_ready_addresses") { - p := pathPrefix + "publishNotReadyAddresses" - v := d.Get(keyPrefix + "publish_not_ready_addresses").(bool) - if v { - ops = append(ops, &AddOperation{ - Path: p, - Value: v, - }) - } else { - ops = append(ops, &RemoveOperation{ - Path: p, - }) - } - } - if d.HasChange(keyPrefix + "health_check_node_port") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "healthCheckNodePort", - Value: int32(d.Get(keyPrefix + "health_check_node_port").(int)), - }) - } - return ops, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_validating_webhook_configuration.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_validating_webhook_configuration.go deleted file mode 100644 index b7da4d2b735..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structure_validating_webhook_configuration.go +++ /dev/null @@ -1,120 +0,0 @@ -package kubernetes - -import ( - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" -) - -func flattenValidatingWebhook(in admissionregistrationv1.ValidatingWebhook) map[string]interface{} { - att := map[string]interface{}{} - - att["admission_review_versions"] = in.AdmissionReviewVersions - - att["client_config"] = flattenWebhookClientConfig(in.ClientConfig) - - if in.FailurePolicy != nil { - att["failure_policy"] = *in.FailurePolicy - } - - if in.MatchPolicy != nil { - att["match_policy"] = *in.MatchPolicy - } - - att["name"] = in.Name - - if in.NamespaceSelector != nil { - if in.NamespaceSelector.MatchExpressions != nil || in.NamespaceSelector.MatchLabels != nil { - att["namespace_selector"] = flattenLabelSelector(in.NamespaceSelector) - } - } - - if in.ObjectSelector != nil { - if in.ObjectSelector.MatchExpressions != nil || in.ObjectSelector.MatchLabels != nil { - att["object_selector"] = flattenLabelSelector(in.ObjectSelector) - } - } - - rules := []interface{}{} - for _, rule := range in.Rules { - rules = append(rules, flattenRuleWithOperations(rule)) - } - att["rule"] = rules - - if in.SideEffects != nil { - att["side_effects"] = *in.SideEffects - } - - if in.TimeoutSeconds != nil { - att["timeout_seconds"] = *in.TimeoutSeconds - } - - return att -} - -func expandValidatingWebhook(in map[string]interface{}) admissionregistrationv1.ValidatingWebhook { - obj := admissionregistrationv1.ValidatingWebhook{} - - if v, ok := in["admission_review_versions"].([]interface{}); ok { - obj.AdmissionReviewVersions = expandStringSlice(v) - } - - if v, ok := in["client_config"].([]interface{}); ok { - obj.ClientConfig = expandWebhookClientConfig(v) - } - - if v, ok := in["failure_policy"].(string); ok { - policy := admissionregistrationv1.FailurePolicyType(v) - obj.FailurePolicy = &policy - } - - if v, ok := in["match_policy"].(string); ok { - policy := admissionregistrationv1.MatchPolicyType(v) - obj.MatchPolicy = &policy - } - - if v, ok := in["name"].(string); ok { - obj.Name = v - } - - if v, ok := in["namespace_selector"].([]interface{}); ok && len(v) != 0 { - obj.NamespaceSelector = expandLabelSelector(v) - } - - if v, ok := in["object_selector"].([]interface{}); ok && len(v) != 0 { - obj.ObjectSelector = expandLabelSelector(v) - } - - if v, ok := in["rule"].([]interface{}); ok { - rules := []admissionregistrationv1.RuleWithOperations{} - for _, r := range v { - rules = append(rules, expandRuleWithOperations(r.(map[string]interface{}))) - } - obj.Rules = rules - } - - if v, ok := in["side_effects"].(string); ok { - sideEffects := admissionregistrationv1.SideEffectClass(v) - obj.SideEffects = &sideEffects - } - - if v, ok := in["timeout_seconds"].(int); ok { - obj.TimeoutSeconds = ptrToInt32(int32(v)) - } - - return obj -} - -func expandValidatingWebhooks(in []interface{}) []admissionregistrationv1.ValidatingWebhook { - webhooks := []admissionregistrationv1.ValidatingWebhook{} - for _, h := range in { - webhooks = append(webhooks, expandValidatingWebhook(h.(map[string]interface{}))) - } - return webhooks -} - -func flattenValidatingWebhooks(in []admissionregistrationv1.ValidatingWebhook) []interface{} { - webhooks := []interface{}{} - for _, h := range in { - webhooks = append(webhooks, flattenValidatingWebhook(h)) - } - return webhooks -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures.go deleted file mode 100644 index 2f01ca69481..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures.go +++ /dev/null @@ -1,619 +0,0 @@ -package kubernetes - -import ( - "encoding/base64" - "fmt" - "net/url" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func idParts(id string) (string, string, error) { - parts := strings.Split(id, "/") - if len(parts) != 2 { - err := fmt.Errorf("Unexpected ID format (%q), expected %q.", id, "namespace/name") - return "", "", err - } - - return parts[0], parts[1], nil -} - -func buildId(meta metav1.ObjectMeta) string { - return meta.Namespace + "/" + meta.Name -} - -func expandMetadata(in []interface{}) metav1.ObjectMeta { - meta := metav1.ObjectMeta{} - if len(in) < 1 { - return meta - } - m := in[0].(map[string]interface{}) - - if v, ok := m["annotations"].(map[string]interface{}); ok && len(v) > 0 { - meta.Annotations = expandStringMap(m["annotations"].(map[string]interface{})) - } - - if v, ok := m["labels"].(map[string]interface{}); ok && len(v) > 0 { - meta.Labels = expandStringMap(m["labels"].(map[string]interface{})) - } - - if v, ok := m["generate_name"]; ok { - meta.GenerateName = v.(string) - } - if v, ok := m["name"]; ok { - meta.Name = v.(string) - } - if v, ok := m["namespace"]; ok { - meta.Namespace = v.(string) - } - - return meta -} - -func patchMetadata(keyPrefix, pathPrefix string, d *schema.ResourceData) PatchOperations { - ops := make([]PatchOperation, 0, 0) - if d.HasChange(keyPrefix + "annotations") { - oldV, newV := d.GetChange(keyPrefix + "annotations") - diffOps := diffStringMap(pathPrefix+"annotations", oldV.(map[string]interface{}), newV.(map[string]interface{})) - ops = append(ops, diffOps...) - } - if d.HasChange(keyPrefix + "labels") { - oldV, newV := d.GetChange(keyPrefix + "labels") - diffOps := diffStringMap(pathPrefix+"labels", oldV.(map[string]interface{}), newV.(map[string]interface{})) - ops = append(ops, diffOps...) - } - return ops -} - -func expandStringMap(m map[string]interface{}) map[string]string { - result := make(map[string]string) - for k, v := range m { - result[k] = v.(string) - } - return result -} - -func expandBase64MapToByteMap(m map[string]interface{}) map[string][]byte { - result := make(map[string][]byte) - for k, v := range m { - b, err := base64.StdEncoding.DecodeString(v.(string)) - if err == nil { - result[k] = b - } - } - return result -} - -func expandStringMapToByteMap(m map[string]interface{}) map[string][]byte { - result := make(map[string][]byte) - for k, v := range m { - result[k] = []byte(v.(string)) - } - return result -} - -func expandStringSlice(s []interface{}) []string { - result := make([]string, len(s), len(s)) - for k, v := range s { - // Handle the Terraform parser bug which turns empty strings in lists to nil. - if v == nil { - result[k] = "" - } else { - result[k] = v.(string) - } - } - return result -} - -func flattenMetadata(meta metav1.ObjectMeta, d *schema.ResourceData, metaPrefix ...string) []interface{} { - m := make(map[string]interface{}) - prefix := "" - if len(metaPrefix) > 0 { - prefix = metaPrefix[0] - } - configAnnotations := d.Get(prefix + "metadata.0.annotations").(map[string]interface{}) - m["annotations"] = removeInternalKeys(meta.Annotations, configAnnotations) - if meta.GenerateName != "" { - m["generate_name"] = meta.GenerateName - } - configLabels := d.Get(prefix + "metadata.0.labels").(map[string]interface{}) - m["labels"] = removeInternalKeys(meta.Labels, configLabels) - m["name"] = meta.Name - m["resource_version"] = meta.ResourceVersion - m["self_link"] = meta.SelfLink - m["uid"] = fmt.Sprintf("%v", meta.UID) - m["generation"] = meta.Generation - - if meta.Namespace != "" { - m["namespace"] = meta.Namespace - } - - return []interface{}{m} -} - -func removeInternalKeys(m map[string]string, d map[string]interface{}) map[string]string { - for k := range m { - if isInternalKey(k) && !isKeyInMap(k, d) { - delete(m, k) - } - } - return m -} - -func isKeyInMap(key string, d map[string]interface{}) bool { - if d == nil { - return false - } - for k := range d { - if k == key { - return true - } - } - return false -} - -func isInternalKey(annotationKey string) bool { - u, err := url.Parse("//" + annotationKey) - if err == nil && strings.HasSuffix(u.Hostname(), "kubernetes.io") { - return true - } - - // Specific to DaemonSet annotations, generated & controlled by the server. - if strings.Contains(annotationKey, "deprecated.daemonset.template.generation") { - return true - } - - return false -} - -func flattenByteMapToBase64Map(m map[string][]byte) map[string]string { - result := make(map[string]string) - for k, v := range m { - result[k] = base64.StdEncoding.EncodeToString([]byte(v)) - } - return result -} - -func flattenByteMapToStringMap(m map[string][]byte) map[string]string { - result := make(map[string]string) - for k, v := range m { - result[k] = string(v) - } - return result -} - -func ptrToString(s string) *string { - return &s -} - -func ptrToBool(b bool) *bool { - return &b -} - -func ptrToInt32(i int32) *int32 { - return &i -} - -func ptrToInt64(i int64) *int64 { - return &i -} - -func sliceOfString(slice []interface{}) []string { - result := make([]string, len(slice), len(slice)) - for i, s := range slice { - result[i] = s.(string) - } - return result -} - -func base64EncodeStringMap(m map[string]interface{}) map[string]interface{} { - result := make(map[string]interface{}) - for k, v := range m { - value := v.(string) - result[k] = base64.StdEncoding.EncodeToString([]byte(value)) - } - return result -} - -func flattenResourceList(l api.ResourceList) map[string]string { - m := make(map[string]string) - for k, v := range l { - m[string(k)] = v.String() - } - return m -} - -func expandMapToResourceList(m map[string]interface{}) (*api.ResourceList, error) { - out := make(api.ResourceList) - for stringKey, origValue := range m { - key := api.ResourceName(stringKey) - var value resource.Quantity - - if v, ok := origValue.(int); ok { - q := resource.NewQuantity(int64(v), resource.DecimalExponent) - value = *q - } else if v, ok := origValue.(string); ok { - var err error - value, err = resource.ParseQuantity(v) - if err != nil { - return &out, err - } - } else { - return &out, fmt.Errorf("Unexpected value type: %#v", origValue) - } - - out[key] = value - } - return &out, nil -} - -func flattenPersistentVolumeAccessModes(in []api.PersistentVolumeAccessMode) *schema.Set { - var out = make([]interface{}, len(in), len(in)) - for i, v := range in { - out[i] = string(v) - } - return schema.NewSet(schema.HashString, out) -} - -func expandPersistentVolumeAccessModes(s []interface{}) []api.PersistentVolumeAccessMode { - out := make([]api.PersistentVolumeAccessMode, len(s), len(s)) - for i, v := range s { - out[i] = api.PersistentVolumeAccessMode(v.(string)) - } - return out -} - -func flattenResourceQuotaSpec(in api.ResourceQuotaSpec) []interface{} { - out := make([]interface{}, 1) - - m := make(map[string]interface{}, 0) - m["hard"] = flattenResourceList(in.Hard) - m["scopes"] = flattenResourceQuotaScopes(in.Scopes) - - out[0] = m - return out -} - -func expandResourceQuotaSpec(s []interface{}) (*api.ResourceQuotaSpec, error) { - out := &api.ResourceQuotaSpec{} - if len(s) < 1 { - return out, nil - } - m := s[0].(map[string]interface{}) - - if v, ok := m["hard"]; ok { - list, err := expandMapToResourceList(v.(map[string]interface{})) - if err != nil { - return out, err - } - out.Hard = *list - } - - if v, ok := m["scopes"]; ok { - out.Scopes = expandResourceQuotaScopes(v.(*schema.Set).List()) - } - - return out, nil -} - -func flattenResourceQuotaScopes(in []api.ResourceQuotaScope) *schema.Set { - out := make([]string, len(in), len(in)) - for i, scope := range in { - out[i] = string(scope) - } - return newStringSet(schema.HashString, out) -} - -func expandResourceQuotaScopes(s []interface{}) []api.ResourceQuotaScope { - out := make([]api.ResourceQuotaScope, len(s), len(s)) - for i, scope := range s { - out[i] = api.ResourceQuotaScope(scope.(string)) - } - return out -} - -func newStringSet(f schema.SchemaSetFunc, in []string) *schema.Set { - var out = make([]interface{}, len(in), len(in)) - for i, v := range in { - out[i] = v - } - return schema.NewSet(f, out) -} -func newInt64Set(f schema.SchemaSetFunc, in []int64) *schema.Set { - var out = make([]interface{}, len(in), len(in)) - for i, v := range in { - out[i] = int(v) - } - return schema.NewSet(f, out) -} - -func resourceListEquals(x, y api.ResourceList) bool { - for k, v := range x { - yValue, ok := y[k] - if !ok { - return false - } - if v.Cmp(yValue) != 0 { - return false - } - } - for k, v := range y { - xValue, ok := x[k] - if !ok { - return false - } - if v.Cmp(xValue) != 0 { - return false - } - } - return true -} - -func expandLimitRangeSpec(s []interface{}, isNew bool) (*api.LimitRangeSpec, error) { - out := &api.LimitRangeSpec{} - if len(s) < 1 || s[0] == nil { - return out, nil - } - m := s[0].(map[string]interface{}) - - if limits, ok := m["limit"].([]interface{}); ok { - newLimits := make([]api.LimitRangeItem, len(limits), len(limits)) - - for i, l := range limits { - lrItem := api.LimitRangeItem{} - limit := l.(map[string]interface{}) - - if v, ok := limit["type"]; ok { - lrItem.Type = api.LimitType(v.(string)) - } - - // defaultRequest is forbidden for Pod limits, even though it's set & returned by API - // this is how we avoid sending it back - if v, ok := limit["default_request"]; ok { - drm := v.(map[string]interface{}) - if lrItem.Type == api.LimitTypePod && len(drm) > 0 { - if isNew { - return out, fmt.Errorf("limit.%d.default_request cannot be set for Pod limit", i) - } - } else { - el, err := expandMapToResourceList(drm) - if err != nil { - return out, err - } - lrItem.DefaultRequest = *el - } - } - - if v, ok := limit["default"]; ok { - el, err := expandMapToResourceList(v.(map[string]interface{})) - if err != nil { - return out, err - } - lrItem.Default = *el - } - if v, ok := limit["max"]; ok { - el, err := expandMapToResourceList(v.(map[string]interface{})) - if err != nil { - return out, err - } - lrItem.Max = *el - } - if v, ok := limit["max_limit_request_ratio"]; ok { - el, err := expandMapToResourceList(v.(map[string]interface{})) - if err != nil { - return out, err - } - lrItem.MaxLimitRequestRatio = *el - } - if v, ok := limit["min"]; ok { - el, err := expandMapToResourceList(v.(map[string]interface{})) - if err != nil { - return out, err - } - lrItem.Min = *el - } - - newLimits[i] = lrItem - } - - out.Limits = newLimits - } - - return out, nil -} - -func flattenLimitRangeSpec(in api.LimitRangeSpec) []interface{} { - if len(in.Limits) == 0 { - return []interface{}{} - } - - out := make([]interface{}, 1) - limits := make([]interface{}, len(in.Limits), len(in.Limits)) - - for i, l := range in.Limits { - m := make(map[string]interface{}, 0) - m["default"] = flattenResourceList(l.Default) - m["default_request"] = flattenResourceList(l.DefaultRequest) - m["max"] = flattenResourceList(l.Max) - m["max_limit_request_ratio"] = flattenResourceList(l.MaxLimitRequestRatio) - m["min"] = flattenResourceList(l.Min) - m["type"] = string(l.Type) - - limits[i] = m - } - out[0] = map[string]interface{}{ - "limit": limits, - } - return out -} - -func schemaSetToStringArray(set *schema.Set) []string { - array := make([]string, 0, set.Len()) - for _, elem := range set.List() { - e := elem.(string) - array = append(array, e) - } - return array -} - -func schemaSetToInt64Array(set *schema.Set) []int64 { - array := make([]int64, 0, set.Len()) - for _, elem := range set.List() { - e := elem.(int) - array = append(array, int64(e)) - } - return array -} -func flattenLabelSelectorRequirementList(l []metav1.LabelSelectorRequirement) []interface{} { - att := make([]map[string]interface{}, len(l)) - for i, v := range l { - m := map[string]interface{}{} - m["key"] = v.Key - m["values"] = newStringSet(schema.HashString, v.Values) - m["operator"] = string(v.Operator) - att[i] = m - } - return []interface{}{att} -} - -func flattenLocalObjectReferenceArray(in []api.LocalObjectReference) []interface{} { - att := make([]interface{}, len(in)) - for i, v := range in { - m := map[string]interface{}{} - if v.Name != "" { - m["name"] = v.Name - } - att[i] = m - } - return att -} - -func expandLocalObjectReferenceArray(in []interface{}) []api.LocalObjectReference { - att := []api.LocalObjectReference{} - if len(in) < 1 { - return att - } - att = make([]api.LocalObjectReference, len(in)) - for i, c := range in { - p := c.(map[string]interface{}) - if name, ok := p["name"]; ok { - att[i].Name = name.(string) - } - } - return att -} - -func flattenServiceAccountSecrets(in []api.ObjectReference, defaultSecretName string) []interface{} { - att := make([]interface{}, 0) - for _, v := range in { - if v.Name == defaultSecretName { - continue - } - m := map[string]interface{}{} - if v.Name != "" { - m["name"] = v.Name - } - att = append(att, m) - } - return att -} - -func expandServiceAccountSecrets(in []interface{}, defaultSecretName string) []api.ObjectReference { - att := make([]api.ObjectReference, 0) - - for _, c := range in { - p := c.(map[string]interface{}) - if name, ok := p["name"]; ok { - att = append(att, api.ObjectReference{Name: name.(string)}) - } - } - if defaultSecretName != "" { - att = append(att, api.ObjectReference{Name: defaultSecretName}) - } - - return att -} - -func flattenNodeSelectorRequirementList(in []api.NodeSelectorRequirement) []map[string]interface{} { - att := make([]map[string]interface{}, len(in)) - for i, v := range in { - m := map[string]interface{}{} - m["key"] = v.Key - m["values"] = newStringSet(schema.HashString, v.Values) - m["operator"] = string(v.Operator) - att[i] = m - } - return att -} - -func expandNodeSelectorRequirementList(in []interface{}) []api.NodeSelectorRequirement { - att := []api.NodeSelectorRequirement{} - if len(in) < 1 { - return att - } - att = make([]api.NodeSelectorRequirement, len(in)) - for i, c := range in { - p := c.(map[string]interface{}) - att[i].Key = p["key"].(string) - att[i].Operator = api.NodeSelectorOperator(p["operator"].(string)) - att[i].Values = expandStringSlice(p["values"].(*schema.Set).List()) - } - return att -} - -func flattenNodeSelectorTerm(in api.NodeSelectorTerm) []interface{} { - att := make(map[string]interface{}) - if len(in.MatchExpressions) > 0 { - att["match_expressions"] = flattenNodeSelectorRequirementList(in.MatchExpressions) - } - if len(in.MatchFields) > 0 { - att["match_fields"] = flattenNodeSelectorRequirementList(in.MatchFields) - } - return []interface{}{att} -} - -func expandNodeSelectorTerm(l []interface{}) *api.NodeSelectorTerm { - if len(l) == 0 || l[0] == nil { - return &api.NodeSelectorTerm{} - } - in := l[0].(map[string]interface{}) - obj := api.NodeSelectorTerm{} - if v, ok := in["match_expressions"].([]interface{}); ok && len(v) > 0 { - obj.MatchExpressions = expandNodeSelectorRequirementList(v) - } - if v, ok := in["match_fields"].([]interface{}); ok && len(v) > 0 { - obj.MatchFields = expandNodeSelectorRequirementList(v) - } - return &obj -} - -func flattenNodeSelectorTerms(in []api.NodeSelectorTerm) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, n := range in { - att[i] = flattenNodeSelectorTerm(n)[0] - } - return att -} - -func expandNodeSelectorTerms(l []interface{}) []api.NodeSelectorTerm { - if len(l) == 0 || l[0] == nil { - return []api.NodeSelectorTerm{} - } - obj := make([]api.NodeSelectorTerm, len(l), len(l)) - for i, n := range l { - obj[i] = *expandNodeSelectorTerm([]interface{}{n}) - } - return obj -} - -func flattenPersistentVolumeMountOptions(in []string) *schema.Set { - var out = make([]interface{}, len(in), len(in)) - for i, v := range in { - out[i] = string(v) - } - return schema.NewSet(schema.HashString, out) -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_admissionregistration.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_admissionregistration.go deleted file mode 100644 index bde36a0fe00..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_admissionregistration.go +++ /dev/null @@ -1,138 +0,0 @@ -package kubernetes - -import ( - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" -) - -func flattenServiceReference(in admissionregistrationv1.ServiceReference) []interface{} { - att := map[string]interface{}{} - - att["name"] = in.Name - att["namespace"] = in.Namespace - - if in.Path != nil { - att["path"] = in.Path - } - - if in.Port != nil { - att["port"] = *in.Port - } - - return []interface{}{att} -} - -func expandServiceReference(l []interface{}) *admissionregistrationv1.ServiceReference { - obj := &admissionregistrationv1.ServiceReference{} - - if len(l) == 0 || l[0] == nil { - return obj - } - - in := l[0].(map[string]interface{}) - - if v, ok := in["name"].(string); ok { - obj.Name = v - } - - if v, ok := in["namespace"].(string); ok { - obj.Namespace = v - } - - if v, ok := in["path"].(string); ok && v != "" { - obj.Path = ptrToString(v) - } - - if v, ok := in["port"].(int); ok { - obj.Port = ptrToInt32(int32(v)) - } - - return obj -} - -func flattenWebhookClientConfig(in admissionregistrationv1.WebhookClientConfig) []interface{} { - att := map[string]interface{}{} - - if len(in.CABundle) > 0 { - att["ca_bundle"] = string(in.CABundle) - } - - if in.Service != nil { - att["service"] = flattenServiceReference(*in.Service) - } - - if in.URL != nil { - att["url"] = *in.URL - } - - return []interface{}{att} -} - -func expandWebhookClientConfig(l []interface{}) admissionregistrationv1.WebhookClientConfig { - obj := admissionregistrationv1.WebhookClientConfig{} - - if len(l) == 0 || l[0] == nil { - return obj - } - - in := l[0].(map[string]interface{}) - - if v, ok := in["ca_bundle"].(string); ok { - obj.CABundle = []byte(v) - } - - if v, ok := in["service"].([]interface{}); ok && len(v) > 0 { - obj.Service = expandServiceReference(v) - } - - if v, ok := in["url"].(string); ok && v != "" { - obj.URL = ptrToString(v) - } - - return obj -} - -func flattenRuleWithOperations(in admissionregistrationv1.RuleWithOperations) map[string]interface{} { - att := map[string]interface{}{} - - att["api_groups"] = in.APIGroups - att["api_versions"] = in.APIVersions - att["operations"] = in.Operations - att["resources"] = in.Resources - - if in.Scope != nil { - att["scope"] = *in.Scope - } - - return att -} - -func expandRuleWithOperations(in map[string]interface{}) admissionregistrationv1.RuleWithOperations { - obj := admissionregistrationv1.RuleWithOperations{} - - if v, ok := in["api_groups"].([]interface{}); ok { - obj.APIGroups = expandStringSlice(v) - } - - if v, ok := in["api_versions"].([]interface{}); ok { - obj.APIVersions = expandStringSlice(v) - } - - if v, ok := in["operations"].([]interface{}); ok { - for _, op := range v { - if op != nil { - obj.Operations = append(obj.Operations, admissionregistrationv1.OperationType(op.(string))) - } - } - } - - if v, ok := in["resources"].([]interface{}); ok { - obj.Resources = expandStringSlice(v) - } - - if v, ok := in["scope"].(string); ok { - scope := admissionregistrationv1.ScopeType(v) - obj.Scope = &scope - } - - return obj -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_affinity.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_affinity.go deleted file mode 100644 index 7b6ab3e5ed0..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_affinity.go +++ /dev/null @@ -1,245 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "k8s.io/api/core/v1" -) - -// Flatteners - -func flattenAffinity(in *v1.Affinity) []interface{} { - att := make(map[string]interface{}) - if in.NodeAffinity != nil { - att["node_affinity"] = flattenNodeAffinity(in.NodeAffinity) - } - if in.PodAffinity != nil { - att["pod_affinity"] = flattenPodAffinity(in.PodAffinity) - } - if in.PodAntiAffinity != nil { - att["pod_anti_affinity"] = flattenPodAntiAffinity(in.PodAntiAffinity) - } - if len(att) > 0 { - return []interface{}{att} - } - return []interface{}{} -} - -func flattenNodeAffinity(in *v1.NodeAffinity) []interface{} { - att := make(map[string]interface{}) - if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { - att["required_during_scheduling_ignored_during_execution"] = flattenNodeSelector(in.RequiredDuringSchedulingIgnoredDuringExecution) - } - if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { - att["preferred_during_scheduling_ignored_during_execution"] = flattenPreferredSchedulingTerm(in.PreferredDuringSchedulingIgnoredDuringExecution) - } - if len(att) > 0 { - return []interface{}{att} - } - return []interface{}{} -} - -func flattenPodAffinity(in *v1.PodAffinity) []interface{} { - att := make(map[string]interface{}) - if len(in.RequiredDuringSchedulingIgnoredDuringExecution) > 0 { - att["required_during_scheduling_ignored_during_execution"] = flattenPodAffinityTerms(in.RequiredDuringSchedulingIgnoredDuringExecution) - } - if len(in.PreferredDuringSchedulingIgnoredDuringExecution) > 0 { - att["preferred_during_scheduling_ignored_during_execution"] = flattenWeightedPodAffinityTerms(in.PreferredDuringSchedulingIgnoredDuringExecution) - } - if len(att) > 0 { - return []interface{}{att} - } - return []interface{}{} -} - -func flattenPodAntiAffinity(in *v1.PodAntiAffinity) []interface{} { - att := make(map[string]interface{}) - if len(in.RequiredDuringSchedulingIgnoredDuringExecution) > 0 { - att["required_during_scheduling_ignored_during_execution"] = flattenPodAffinityTerms(in.RequiredDuringSchedulingIgnoredDuringExecution) - } - if len(in.PreferredDuringSchedulingIgnoredDuringExecution) > 0 { - att["preferred_during_scheduling_ignored_during_execution"] = flattenWeightedPodAffinityTerms(in.PreferredDuringSchedulingIgnoredDuringExecution) - } - if len(att) > 0 { - return []interface{}{att} - } - return []interface{}{} -} - -func flattenWeightedPodAffinityTerms(in []v1.WeightedPodAffinityTerm) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, n := range in { - m := make(map[string]interface{}) - m["weight"] = int(n.Weight) - m["pod_affinity_term"] = flattenPodAffinityTerms([]v1.PodAffinityTerm{n.PodAffinityTerm}) - att[i] = m - } - return att -} - -func flattenPodAffinityTerms(in []v1.PodAffinityTerm) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, n := range in { - m := make(map[string]interface{}) - m["namespaces"] = newStringSet(schema.HashString, n.Namespaces) - m["topology_key"] = n.TopologyKey - if n.LabelSelector != nil { - m["label_selector"] = flattenLabelSelector(n.LabelSelector) - } - att[i] = m - } - return att -} - -func flattenNodeSelector(in *v1.NodeSelector) []interface{} { - att := make(map[string]interface{}) - if len(in.NodeSelectorTerms) > 0 { - att["node_selector_term"] = flattenNodeSelectorTerms(in.NodeSelectorTerms) - } - if len(att) > 0 { - return []interface{}{att} - } - return []interface{}{} -} - -func flattenPreferredSchedulingTerm(in []v1.PreferredSchedulingTerm) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, n := range in { - m := make(map[string]interface{}) - m["weight"] = int(n.Weight) - m["preference"] = flattenNodeSelectorTerm(n.Preference) - att[i] = m - } - return att -} - -// Expanders - -func expandAffinity(a []interface{}) (*v1.Affinity, error) { - if len(a) == 0 || a[0] == nil { - return &v1.Affinity{}, nil - } - in := a[0].(map[string]interface{}) - obj := v1.Affinity{} - if v, ok := in["node_affinity"].([]interface{}); ok && len(v) > 0 { - obj.NodeAffinity = expandNodeAffinity(v) - } - if v, ok := in["pod_affinity"].([]interface{}); ok && len(v) > 0 { - obj.PodAffinity = expandPodAffinity(v) - } - if v, ok := in["pod_anti_affinity"].([]interface{}); ok && len(v) > 0 { - obj.PodAntiAffinity = expandPodAntiAffinity(v) - } - return &obj, nil -} - -func expandNodeAffinity(a []interface{}) *v1.NodeAffinity { - if len(a) == 0 || a[0] == nil { - return &v1.NodeAffinity{} - } - in := a[0].(map[string]interface{}) - obj := v1.NodeAffinity{} - if v, ok := in["required_during_scheduling_ignored_during_execution"].([]interface{}); ok && len(v) > 0 { - obj.RequiredDuringSchedulingIgnoredDuringExecution = expandNodeSelector(v) - } - if v, ok := in["preferred_during_scheduling_ignored_during_execution"].([]interface{}); ok && len(v) > 0 { - obj.PreferredDuringSchedulingIgnoredDuringExecution = expandPreferredSchedulingTerms(v) - } - return &obj -} - -func expandPodAffinity(a []interface{}) *v1.PodAffinity { - if len(a) == 0 || a[0] == nil { - return &v1.PodAffinity{} - } - in := a[0].(map[string]interface{}) - obj := v1.PodAffinity{} - if v, ok := in["required_during_scheduling_ignored_during_execution"].([]interface{}); ok && len(v) > 0 { - obj.RequiredDuringSchedulingIgnoredDuringExecution = expandPodAffinityTerms(v) - } - if v, ok := in["preferred_during_scheduling_ignored_during_execution"].([]interface{}); ok && len(v) > 0 { - obj.PreferredDuringSchedulingIgnoredDuringExecution = expandWeightedPodAffinityTerms(v) - } - return &obj -} - -func expandPodAntiAffinity(a []interface{}) *v1.PodAntiAffinity { - if len(a) == 0 || a[0] == nil { - return &v1.PodAntiAffinity{} - } - in := a[0].(map[string]interface{}) - obj := v1.PodAntiAffinity{} - if v, ok := in["required_during_scheduling_ignored_during_execution"].([]interface{}); ok && len(v) > 0 { - obj.RequiredDuringSchedulingIgnoredDuringExecution = expandPodAffinityTerms(v) - } - if v, ok := in["preferred_during_scheduling_ignored_during_execution"].([]interface{}); ok && len(v) > 0 { - obj.PreferredDuringSchedulingIgnoredDuringExecution = expandWeightedPodAffinityTerms(v) - } - return &obj -} - -func expandPreferredSchedulingTerms(t []interface{}) []v1.PreferredSchedulingTerm { - if len(t) == 0 || t[0] == nil { - return []v1.PreferredSchedulingTerm{} - } - obj := make([]v1.PreferredSchedulingTerm, len(t), len(t)) - for i, n := range t { - in := n.(map[string]interface{}) - if v, ok := in["weight"].(int); ok { - obj[i].Weight = int32(v) - } - if v, ok := in["preference"].([]interface{}); ok && len(v) > 0 { - obj[i].Preference = *expandNodeSelectorTerm(v) - } - } - return obj -} - -func expandNodeSelector(s []interface{}) *v1.NodeSelector { - if len(s) == 0 || s[0] == nil { - return &v1.NodeSelector{} - } - in := s[0].(map[string]interface{}) - obj := v1.NodeSelector{} - if v, ok := in["node_selector_term"].([]interface{}); ok && len(v) > 0 { - obj.NodeSelectorTerms = expandNodeSelectorTerms(v) - } - return &obj -} - -func expandPodAffinityTerms(t []interface{}) []v1.PodAffinityTerm { - if len(t) == 0 || t[0] == nil { - return []v1.PodAffinityTerm{} - } - obj := make([]v1.PodAffinityTerm, len(t), len(t)) - for i, n := range t { - in := n.(map[string]interface{}) - if v, ok := in["label_selector"].([]interface{}); ok && len(v) > 0 { - obj[i].LabelSelector = expandLabelSelector(v) - } - if v, ok := in["namespaces"].(*schema.Set); ok { - obj[i].Namespaces = sliceOfString(v.List()) - } - if v, ok := in["topology_key"].(string); ok { - obj[i].TopologyKey = v - } - } - return obj -} - -func expandWeightedPodAffinityTerms(t []interface{}) []v1.WeightedPodAffinityTerm { - if len(t) == 0 || t[0] == nil { - return []v1.WeightedPodAffinityTerm{} - } - obj := make([]v1.WeightedPodAffinityTerm, len(t), len(t)) - for i, n := range t { - in := n.(map[string]interface{}) - if v, ok := in["weight"].(int); ok { - obj[i].Weight = int32(v) - } - if v, ok := in["pod_affinity_term"].([]interface{}); ok && len(v) > 0 { - obj[i].PodAffinityTerm = expandPodAffinityTerms(v)[0] - } - } - return obj -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_certificate_signing_request.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_certificate_signing_request.go deleted file mode 100644 index 295001c74d4..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_certificate_signing_request.go +++ /dev/null @@ -1,27 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "k8s.io/api/certificates/v1beta1" -) - -func expandCertificateSigningRequestSpec(csr []interface{}) (*v1beta1.CertificateSigningRequestSpec, error) { - obj := &v1beta1.CertificateSigningRequestSpec{} - if len(csr) == 0 || csr[0] == nil { - return obj, nil - } - in := csr[0].(map[string]interface{}) - obj.Request = []byte(in["request"].(string)) - if v, ok := in["usages"].(*schema.Set); ok && v.Len() > 0 { - obj.Usages = expandCertificateSigningRequestUsages(v.List()) - } - return obj, nil -} - -func expandCertificateSigningRequestUsages(s []interface{}) []v1beta1.KeyUsage { - out := make([]v1beta1.KeyUsage, len(s), len(s)) - for i, v := range s { - out[i] = v1beta1.KeyUsage(v.(string)) - } - return out -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_container.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_container.go deleted file mode 100644 index 27489f889ae..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_container.go +++ /dev/null @@ -1,998 +0,0 @@ -package kubernetes - -import ( - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/util/intstr" -) - -func flattenCapability(in []v1.Capability) []string { - att := make([]string, len(in), len(in)) - for i, v := range in { - att[i] = string(v) - } - return att -} - -func flattenContainerSecurityContext(in *v1.SecurityContext) []interface{} { - att := make(map[string]interface{}) - - if in.AllowPrivilegeEscalation != nil { - att["allow_privilege_escalation"] = *in.AllowPrivilegeEscalation - } - if in.Capabilities != nil { - att["capabilities"] = flattenSecurityCapabilities(in.Capabilities) - } - if in.Privileged != nil { - att["privileged"] = *in.Privileged - } - if in.ReadOnlyRootFilesystem != nil { - att["read_only_root_filesystem"] = *in.ReadOnlyRootFilesystem - } - if in.RunAsGroup != nil { - att["run_as_group"] = *in.RunAsGroup - } - if in.RunAsNonRoot != nil { - att["run_as_non_root"] = *in.RunAsNonRoot - } - if in.RunAsUser != nil { - att["run_as_user"] = *in.RunAsUser - } - if in.SELinuxOptions != nil { - att["se_linux_options"] = flattenSeLinuxOptions(in.SELinuxOptions) - } - return []interface{}{att} - -} - -func flattenSecurityCapabilities(in *v1.Capabilities) []interface{} { - att := make(map[string]interface{}) - - if in.Add != nil { - att["add"] = flattenCapability(in.Add) - } - if in.Drop != nil { - att["drop"] = flattenCapability(in.Drop) - } - - return []interface{}{att} -} - -func flattenHandler(in *v1.Handler) []interface{} { - att := make(map[string]interface{}) - - if in.Exec != nil { - att["exec"] = flattenExec(in.Exec) - } - if in.HTTPGet != nil { - att["http_get"] = flattenHTTPGet(in.HTTPGet) - } - if in.TCPSocket != nil { - att["tcp_socket"] = flattenTCPSocket(in.TCPSocket) - } - - return []interface{}{att} -} - -func flattenHTTPHeader(in []v1.HTTPHeader) []interface{} { - att := make([]interface{}, len(in)) - for i, v := range in { - m := map[string]interface{}{} - - if v.Name != "" { - m["name"] = v.Name - } - - if v.Value != "" { - m["value"] = v.Value - } - att[i] = m - } - return att -} - -func flattenHTTPGet(in *v1.HTTPGetAction) []interface{} { - att := make(map[string]interface{}) - - if in.Host != "" { - att["host"] = in.Host - } - if in.Path != "" { - att["path"] = in.Path - } - att["port"] = in.Port.String() - att["scheme"] = in.Scheme - if len(in.HTTPHeaders) > 0 { - att["http_header"] = flattenHTTPHeader(in.HTTPHeaders) - } - - return []interface{}{att} -} - -func flattenTCPSocket(in *v1.TCPSocketAction) []interface{} { - att := make(map[string]interface{}) - att["port"] = in.Port.String() - return []interface{}{att} -} - -func flattenExec(in *v1.ExecAction) []interface{} { - att := make(map[string]interface{}) - if len(in.Command) > 0 { - att["command"] = in.Command - } - return []interface{}{att} -} - -func flattenLifeCycle(in *v1.Lifecycle) []interface{} { - att := make(map[string]interface{}) - - if in.PostStart != nil { - att["post_start"] = flattenHandler(in.PostStart) - } - if in.PreStop != nil { - att["pre_stop"] = flattenHandler(in.PreStop) - } - - return []interface{}{att} -} - -func flattenProbe(in *v1.Probe) []interface{} { - att := make(map[string]interface{}) - - att["failure_threshold"] = in.FailureThreshold - att["initial_delay_seconds"] = in.InitialDelaySeconds - att["period_seconds"] = in.PeriodSeconds - att["success_threshold"] = in.SuccessThreshold - att["timeout_seconds"] = in.TimeoutSeconds - - if in.Exec != nil { - att["exec"] = flattenExec(in.Exec) - } - if in.HTTPGet != nil { - att["http_get"] = flattenHTTPGet(in.HTTPGet) - } - if in.TCPSocket != nil { - att["tcp_socket"] = flattenTCPSocket(in.TCPSocket) - } - - return []interface{}{att} -} - -func flattenConfigMapRef(in *v1.ConfigMapEnvSource) []interface{} { - att := make(map[string]interface{}) - - if in.Name != "" { - att["name"] = in.Name - } - if in.Optional != nil { - att["optional"] = *in.Optional - } - return []interface{}{att} -} - -func flattenConfigMapKeyRef(in *v1.ConfigMapKeySelector) []interface{} { - att := make(map[string]interface{}) - - if in.Key != "" { - att["key"] = in.Key - } - if in.Name != "" { - att["name"] = in.Name - } - if in.Optional != nil { - att["optional"] = *in.Optional - } - return []interface{}{att} -} - -func flattenObjectFieldSelector(in *v1.ObjectFieldSelector) []interface{} { - att := make(map[string]interface{}) - - if in.APIVersion != "" { - att["api_version"] = in.APIVersion - } - if in.FieldPath != "" { - att["field_path"] = in.FieldPath - } - return []interface{}{att} -} - -func flattenResourceFieldSelector(in *v1.ResourceFieldSelector) []interface{} { - att := make(map[string]interface{}) - - if in.ContainerName != "" { - att["container_name"] = in.ContainerName - } - if in.Resource != "" { - att["resource"] = in.Resource - } - return []interface{}{att} -} - -func flattenSecretRef(in *v1.SecretEnvSource) []interface{} { - att := make(map[string]interface{}) - - if in.Name != "" { - att["name"] = in.Name - } - if in.Optional != nil { - att["optional"] = *in.Optional - } - return []interface{}{att} -} - -func flattenSecretKeyRef(in *v1.SecretKeySelector) []interface{} { - att := make(map[string]interface{}) - - if in.Key != "" { - att["key"] = in.Key - } - if in.Name != "" { - att["name"] = in.Name - } - if in.Optional != nil { - att["optional"] = *in.Optional - } - return []interface{}{att} -} - -func flattenValueFrom(in *v1.EnvVarSource) []interface{} { - att := make(map[string]interface{}) - - if in.ConfigMapKeyRef != nil { - att["config_map_key_ref"] = flattenConfigMapKeyRef(in.ConfigMapKeyRef) - } - if in.ResourceFieldRef != nil { - att["resource_field_ref"] = flattenResourceFieldSelector(in.ResourceFieldRef) - } - if in.SecretKeyRef != nil { - att["secret_key_ref"] = flattenSecretKeyRef(in.SecretKeyRef) - } - if in.FieldRef != nil { - att["field_ref"] = flattenObjectFieldSelector(in.FieldRef) - } - return []interface{}{att} -} - -func flattenContainerVolumeMounts(in []v1.VolumeMount) ([]interface{}, error) { - att := make([]interface{}, len(in)) - for i, v := range in { - m := map[string]interface{}{} - m["read_only"] = v.ReadOnly - - if v.MountPath != "" { - m["mount_path"] = v.MountPath - - } - if v.Name != "" { - m["name"] = v.Name - - } - if v.SubPath != "" { - m["sub_path"] = v.SubPath - } - if v.MountPropagation != nil { - m["mount_propagation"] = string(*v.MountPropagation) - } - att[i] = m - } - return att, nil -} - -func flattenContainerEnvs(in []v1.EnvVar) []interface{} { - att := make([]interface{}, len(in)) - for i, v := range in { - m := map[string]interface{}{} - if v.Name != "" { - m["name"] = v.Name - } - if v.Value != "" { - m["value"] = v.Value - } - if v.ValueFrom != nil { - m["value_from"] = flattenValueFrom(v.ValueFrom) - } - - att[i] = m - } - return att -} - -func flattenContainerEnvFroms(in []v1.EnvFromSource) []interface{} { - att := make([]interface{}, len(in)) - for i, v := range in { - m := map[string]interface{}{} - if v.ConfigMapRef != nil { - m["config_map_ref"] = flattenConfigMapRef(v.ConfigMapRef) - } - if v.Prefix != "" { - m["prefix"] = v.Prefix - } - if v.SecretRef != nil { - m["secret_ref"] = flattenSecretRef(v.SecretRef) - } - - att[i] = m - } - return att -} - -func flattenContainerPorts(in []v1.ContainerPort) []interface{} { - att := make([]interface{}, len(in)) - for i, v := range in { - m := map[string]interface{}{} - m["container_port"] = v.ContainerPort - if v.HostIP != "" { - m["host_ip"] = v.HostIP - } - m["host_port"] = v.HostPort - if v.Name != "" { - m["name"] = v.Name - } - if v.Protocol != "" { - m["protocol"] = v.Protocol - } - att[i] = m - } - return att -} - -func flattenContainerResourceRequirements(in v1.ResourceRequirements) ([]interface{}, error) { - att := make(map[string]interface{}) - if len(in.Limits) > 0 { - att["limits"] = []interface{}{flattenResourceList(in.Limits)} - } - if len(in.Requests) > 0 { - att["requests"] = []interface{}{flattenResourceList(in.Requests)} - } - return []interface{}{att}, nil -} - -func flattenContainers(in []v1.Container) ([]interface{}, error) { - att := make([]interface{}, len(in)) - for i, v := range in { - c := make(map[string]interface{}) - c["image"] = v.Image - c["name"] = v.Name - if len(v.Command) > 0 { - c["command"] = v.Command - } - if len(v.Args) > 0 { - c["args"] = v.Args - } - - c["image_pull_policy"] = v.ImagePullPolicy - c["termination_message_path"] = v.TerminationMessagePath - c["termination_message_policy"] = v.TerminationMessagePolicy - c["stdin"] = v.Stdin - c["stdin_once"] = v.StdinOnce - c["tty"] = v.TTY - c["working_dir"] = v.WorkingDir - res, err := flattenContainerResourceRequirements(v.Resources) - if err != nil { - return nil, err - } - - c["resources"] = res - if v.LivenessProbe != nil { - c["liveness_probe"] = flattenProbe(v.LivenessProbe) - } - if v.ReadinessProbe != nil { - c["readiness_probe"] = flattenProbe(v.ReadinessProbe) - } - if v.StartupProbe != nil { - c["startup_probe"] = flattenProbe(v.StartupProbe) - } - if v.Lifecycle != nil { - c["lifecycle"] = flattenLifeCycle(v.Lifecycle) - } - - if v.SecurityContext != nil { - c["security_context"] = flattenContainerSecurityContext(v.SecurityContext) - } - if len(v.Ports) > 0 { - c["port"] = flattenContainerPorts(v.Ports) - } - if len(v.Env) > 0 { - c["env"] = flattenContainerEnvs(v.Env) - } - if len(v.EnvFrom) > 0 { - c["env_from"] = flattenContainerEnvFroms(v.EnvFrom) - } - - if len(v.VolumeMounts) > 0 { - volumeMounts, err := flattenContainerVolumeMounts(v.VolumeMounts) - if err != nil { - return nil, err - } - c["volume_mount"] = volumeMounts - } - att[i] = c - } - return att, nil -} - -func expandContainers(ctrs []interface{}) ([]v1.Container, error) { - if len(ctrs) == 0 { - return []v1.Container{}, nil - } - cs := make([]v1.Container, len(ctrs)) - for i, c := range ctrs { - ctr := c.(map[string]interface{}) - - if image, ok := ctr["image"]; ok { - cs[i].Image = image.(string) - } - if name, ok := ctr["name"]; ok { - cs[i].Name = name.(string) - } - if command, ok := ctr["command"].([]interface{}); ok { - cs[i].Command = expandStringSlice(command) - } - if args, ok := ctr["args"].([]interface{}); ok { - cs[i].Args = expandStringSlice(args) - } - - if v, ok := ctr["resources"].([]interface{}); ok && len(v) > 0 { - - var err error - crr, err := expandContainerResourceRequirements(v) - if err != nil { - return cs, err - } - cs[i].Resources = *crr - } - - if v, ok := ctr["port"].([]interface{}); ok && len(v) > 0 { - cp, err := expandContainerPort(v) - if err != nil { - return cs, err - } - for _, p := range cp { - cs[i].Ports = append(cs[i].Ports, *p) - } - } - if v, ok := ctr["env"].([]interface{}); ok && len(v) > 0 { - var err error - cs[i].Env, err = expandContainerEnv(v) - if err != nil { - return cs, err - } - } - if v, ok := ctr["env_from"].([]interface{}); ok && len(v) > 0 { - var err error - cs[i].EnvFrom, err = expandContainerEnvFrom(v) - if err != nil { - return cs, err - } - } - - if policy, ok := ctr["image_pull_policy"]; ok { - cs[i].ImagePullPolicy = v1.PullPolicy(policy.(string)) - } - - if v, ok := ctr["lifecycle"].([]interface{}); ok && len(v) > 0 { - cs[i].Lifecycle = expandLifeCycle(v) - } - - if v, ok := ctr["liveness_probe"].([]interface{}); ok && len(v) > 0 { - cs[i].LivenessProbe = expandProbe(v) - } - - if v, ok := ctr["readiness_probe"].([]interface{}); ok && len(v) > 0 { - cs[i].ReadinessProbe = expandProbe(v) - } - if v, ok := ctr["startup_probe"].([]interface{}); ok && len(v) > 0 { - cs[i].StartupProbe = expandProbe(v) - } - if v, ok := ctr["stdin"]; ok { - cs[i].Stdin = v.(bool) - } - if v, ok := ctr["stdin_once"]; ok { - cs[i].StdinOnce = v.(bool) - } - if v, ok := ctr["termination_message_path"]; ok { - cs[i].TerminationMessagePath = v.(string) - } - if v, ok := ctr["termination_message_policy"]; ok { - cs[i].TerminationMessagePolicy = v1.TerminationMessagePolicy(v.(string)) - } - if v, ok := ctr["tty"]; ok { - cs[i].TTY = v.(bool) - } - if v, ok := ctr["security_context"].([]interface{}); ok && len(v) > 0 { - cs[i].SecurityContext = expandContainerSecurityContext(v) - } - - if v, ok := ctr["volume_mount"].([]interface{}); ok && len(v) > 0 { - var err error - cs[i].VolumeMounts, err = expandContainerVolumeMounts(v) - if err != nil { - return cs, err - } - } - - if v, ok := ctr["working_dir"].(string); ok && v != "" { - cs[i].WorkingDir = v - } - } - return cs, nil -} - -func expandExec(l []interface{}) *v1.ExecAction { - if len(l) == 0 || l[0] == nil { - return &v1.ExecAction{} - } - in := l[0].(map[string]interface{}) - obj := v1.ExecAction{} - if v, ok := in["command"].([]interface{}); ok && len(v) > 0 { - obj.Command = expandStringSlice(v) - } - return &obj -} - -func expandHTTPHeaders(l []interface{}) []v1.HTTPHeader { - if len(l) == 0 { - return []v1.HTTPHeader{} - } - headers := make([]v1.HTTPHeader, len(l)) - for i, c := range l { - m := c.(map[string]interface{}) - if v, ok := m["name"]; ok { - headers[i].Name = v.(string) - } - if v, ok := m["value"]; ok { - headers[i].Value = v.(string) - } - } - return headers -} -func expandContainerSecurityContext(l []interface{}) *v1.SecurityContext { - if len(l) == 0 || l[0] == nil { - return &v1.SecurityContext{} - } - in := l[0].(map[string]interface{}) - obj := v1.SecurityContext{} - if v, ok := in["allow_privilege_escalation"]; ok { - obj.AllowPrivilegeEscalation = ptrToBool(v.(bool)) - } - if v, ok := in["capabilities"].([]interface{}); ok && len(v) > 0 { - obj.Capabilities = expandSecurityCapabilities(v) - } - if v, ok := in["privileged"]; ok { - obj.Privileged = ptrToBool(v.(bool)) - } - if v, ok := in["read_only_root_filesystem"]; ok { - obj.ReadOnlyRootFilesystem = ptrToBool(v.(bool)) - } - if v, ok := in["run_as_group"]; ok { - obj.RunAsGroup = ptrToInt64(int64(v.(int))) - } - if v, ok := in["run_as_non_root"]; ok { - obj.RunAsNonRoot = ptrToBool(v.(bool)) - } - if v, ok := in["run_as_user"]; ok { - obj.RunAsUser = ptrToInt64(int64(v.(int))) - } - if v, ok := in["se_linux_options"].([]interface{}); ok && len(v) > 0 { - obj.SELinuxOptions = expandSeLinuxOptions(v) - } - - return &obj -} - -func expandCapabilitySlice(s []interface{}) []v1.Capability { - result := make([]v1.Capability, len(s), len(s)) - for k, v := range s { - result[k] = v1.Capability(v.(string)) - } - return result -} - -func expandSecurityCapabilities(l []interface{}) *v1.Capabilities { - if len(l) == 0 || l[0] == nil { - return &v1.Capabilities{} - } - in := l[0].(map[string]interface{}) - obj := v1.Capabilities{} - if v, ok := in["add"].([]interface{}); ok { - obj.Add = expandCapabilitySlice(v) - } - if v, ok := in["drop"].([]interface{}); ok { - obj.Drop = expandCapabilitySlice(v) - } - return &obj -} - -func expandTCPSocket(l []interface{}) *v1.TCPSocketAction { - if len(l) == 0 || l[0] == nil { - return &v1.TCPSocketAction{} - } - in := l[0].(map[string]interface{}) - obj := v1.TCPSocketAction{} - if v, ok := in["port"].(string); ok && len(v) > 0 { - obj.Port = intstr.Parse(v) - } - return &obj -} - -func expandHTTPGet(l []interface{}) *v1.HTTPGetAction { - if len(l) == 0 || l[0] == nil { - return &v1.HTTPGetAction{} - } - in := l[0].(map[string]interface{}) - obj := v1.HTTPGetAction{} - if v, ok := in["host"].(string); ok && len(v) > 0 { - obj.Host = v - } - if v, ok := in["path"].(string); ok && len(v) > 0 { - obj.Path = v - } - if v, ok := in["scheme"].(string); ok && len(v) > 0 { - obj.Scheme = v1.URIScheme(v) - } - - if v, ok := in["port"].(string); ok && len(v) > 0 { - obj.Port = intstr.Parse(v) - } - - if v, ok := in["http_header"].([]interface{}); ok && len(v) > 0 { - obj.HTTPHeaders = expandHTTPHeaders(v) - } - return &obj -} - -func expandProbe(l []interface{}) *v1.Probe { - if len(l) == 0 || l[0] == nil { - return &v1.Probe{} - } - in := l[0].(map[string]interface{}) - obj := v1.Probe{} - if v, ok := in["exec"].([]interface{}); ok && len(v) > 0 { - obj.Exec = expandExec(v) - } - if v, ok := in["http_get"].([]interface{}); ok && len(v) > 0 { - obj.HTTPGet = expandHTTPGet(v) - } - if v, ok := in["tcp_socket"].([]interface{}); ok && len(v) > 0 { - obj.TCPSocket = expandTCPSocket(v) - } - if v, ok := in["failure_threshold"].(int); ok { - obj.FailureThreshold = int32(v) - } - if v, ok := in["initial_delay_seconds"].(int); ok { - obj.InitialDelaySeconds = int32(v) - } - if v, ok := in["period_seconds"].(int); ok { - obj.PeriodSeconds = int32(v) - } - if v, ok := in["success_threshold"].(int); ok { - obj.SuccessThreshold = int32(v) - } - if v, ok := in["timeout_seconds"].(int); ok { - obj.TimeoutSeconds = int32(v) - } - - return &obj -} - -func expandHandlers(l []interface{}) *v1.Handler { - if len(l) == 0 || l[0] == nil { - return &v1.Handler{} - } - in := l[0].(map[string]interface{}) - obj := v1.Handler{} - if v, ok := in["exec"].([]interface{}); ok && len(v) > 0 { - obj.Exec = expandExec(v) - } - if v, ok := in["http_get"].([]interface{}); ok && len(v) > 0 { - obj.HTTPGet = expandHTTPGet(v) - } - if v, ok := in["tcp_socket"].([]interface{}); ok && len(v) > 0 { - obj.TCPSocket = expandTCPSocket(v) - } - return &obj - -} -func expandLifeCycle(l []interface{}) *v1.Lifecycle { - if len(l) == 0 || l[0] == nil { - return &v1.Lifecycle{} - } - in := l[0].(map[string]interface{}) - obj := &v1.Lifecycle{} - if v, ok := in["post_start"].([]interface{}); ok && len(v) > 0 { - obj.PostStart = expandHandlers(v) - } - if v, ok := in["pre_stop"].([]interface{}); ok && len(v) > 0 { - obj.PreStop = expandHandlers(v) - } - return obj -} - -func expandContainerVolumeMounts(in []interface{}) ([]v1.VolumeMount, error) { - if len(in) == 0 { - return []v1.VolumeMount{}, nil - } - vmp := make([]v1.VolumeMount, len(in)) - for i, c := range in { - p := c.(map[string]interface{}) - if mountPath, ok := p["mount_path"]; ok { - vmp[i].MountPath = mountPath.(string) - } - if name, ok := p["name"]; ok { - vmp[i].Name = name.(string) - } - if readOnly, ok := p["read_only"]; ok { - vmp[i].ReadOnly = readOnly.(bool) - } - if subPath, ok := p["sub_path"]; ok { - vmp[i].SubPath = subPath.(string) - } - if mountPropagation, ok := p["mount_propagation"]; ok { - mp := v1.MountPropagationMode(mountPropagation.(string)) - vmp[i].MountPropagation = &mp - } - } - return vmp, nil -} - -func expandContainerEnv(in []interface{}) ([]v1.EnvVar, error) { - if len(in) == 0 { - return []v1.EnvVar{}, nil - } - envs := make([]v1.EnvVar, len(in)) - for i, c := range in { - p := c.(map[string]interface{}) - if name, ok := p["name"]; ok { - envs[i].Name = name.(string) - } - if value, ok := p["value"]; ok { - envs[i].Value = value.(string) - } - if v, ok := p["value_from"].([]interface{}); ok && len(v) > 0 { - var err error - envs[i].ValueFrom, err = expandEnvValueFrom(v) - if err != nil { - return envs, err - } - } - } - return envs, nil -} - -func expandContainerEnvFrom(in []interface{}) ([]v1.EnvFromSource, error) { - if len(in) == 0 { - return []v1.EnvFromSource{}, nil - } - envFroms := make([]v1.EnvFromSource, len(in)) - for i, c := range in { - p := c.(map[string]interface{}) - if v, ok := p["config_map_ref"].([]interface{}); ok && len(v) > 0 { - var err error - envFroms[i].ConfigMapRef, err = expandConfigMapRef(v) - if err != nil { - return envFroms, err - } - } - if value, ok := p["prefix"]; ok { - envFroms[i].Prefix = value.(string) - } - if v, ok := p["secret_ref"].([]interface{}); ok && len(v) > 0 { - var err error - envFroms[i].SecretRef, err = expandSecretRef(v) - if err != nil { - return envFroms, err - } - } - } - return envFroms, nil -} - -func expandContainerPort(in []interface{}) ([]*v1.ContainerPort, error) { - ports := make([]*v1.ContainerPort, len(in)) - if len(in) == 0 { - return ports, nil - } - for i, c := range in { - p := c.(map[string]interface{}) - ports[i] = &v1.ContainerPort{} - if containerPort, ok := p["container_port"]; ok { - ports[i].ContainerPort = int32(containerPort.(int)) - } - if hostIP, ok := p["host_ip"]; ok { - ports[i].HostIP = hostIP.(string) - } - if hostPort, ok := p["host_port"]; ok { - ports[i].HostPort = int32(hostPort.(int)) - } - if name, ok := p["name"]; ok { - ports[i].Name = name.(string) - } - if protocol, ok := p["protocol"]; ok { - ports[i].Protocol = v1.Protocol(protocol.(string)) - } - } - return ports, nil -} - -func expandConfigMapKeyRef(r []interface{}) (*v1.ConfigMapKeySelector, error) { - if len(r) == 0 || r[0] == nil { - return &v1.ConfigMapKeySelector{}, nil - } - in := r[0].(map[string]interface{}) - obj := &v1.ConfigMapKeySelector{} - - if v, ok := in["key"].(string); ok { - obj.Key = v - } - if v, ok := in["name"].(string); ok { - obj.Name = v - } - if v, ok := in["optional"]; ok { - obj.Optional = ptrToBool(v.(bool)) - } - return obj, nil - -} -func expandFieldRef(r []interface{}) (*v1.ObjectFieldSelector, error) { - if len(r) == 0 || r[0] == nil { - return &v1.ObjectFieldSelector{}, nil - } - in := r[0].(map[string]interface{}) - obj := &v1.ObjectFieldSelector{} - - if v, ok := in["api_version"].(string); ok { - obj.APIVersion = v - } - if v, ok := in["field_path"].(string); ok { - obj.FieldPath = v - } - return obj, nil -} -func expandResourceFieldRef(r []interface{}) (*v1.ResourceFieldSelector, error) { - if len(r) == 0 || r[0] == nil { - return &v1.ResourceFieldSelector{}, nil - } - in := r[0].(map[string]interface{}) - obj := &v1.ResourceFieldSelector{} - - if v, ok := in["container_name"].(string); ok { - obj.ContainerName = v - } - if v, ok := in["resource"].(string); ok { - obj.Resource = v - } - return obj, nil -} - -func expandSecretRef(r []interface{}) (*v1.SecretEnvSource, error) { - if len(r) == 0 || r[0] == nil { - return &v1.SecretEnvSource{}, nil - } - in := r[0].(map[string]interface{}) - obj := &v1.SecretEnvSource{} - - if v, ok := in["name"].(string); ok { - obj.Name = v - } - if v, ok := in["optional"]; ok { - obj.Optional = ptrToBool(v.(bool)) - } - - return obj, nil -} - -func expandSecretKeyRef(r []interface{}) (*v1.SecretKeySelector, error) { - if len(r) == 0 || r[0] == nil { - return &v1.SecretKeySelector{}, nil - } - in := r[0].(map[string]interface{}) - obj := &v1.SecretKeySelector{} - - if v, ok := in["key"].(string); ok { - obj.Key = v - } - if v, ok := in["name"].(string); ok { - obj.Name = v - } - if v, ok := in["optional"]; ok { - obj.Optional = ptrToBool(v.(bool)) - } - return obj, nil -} - -func expandEnvValueFrom(r []interface{}) (*v1.EnvVarSource, error) { - if len(r) == 0 || r[0] == nil { - return &v1.EnvVarSource{}, nil - } - in := r[0].(map[string]interface{}) - obj := &v1.EnvVarSource{} - - var err error - if v, ok := in["config_map_key_ref"].([]interface{}); ok && len(v) > 0 { - obj.ConfigMapKeyRef, err = expandConfigMapKeyRef(v) - if err != nil { - return obj, err - } - } - if v, ok := in["field_ref"].([]interface{}); ok && len(v) > 0 { - obj.FieldRef, err = expandFieldRef(v) - if err != nil { - return obj, err - } - } - if v, ok := in["secret_key_ref"].([]interface{}); ok && len(v) > 0 { - obj.SecretKeyRef, err = expandSecretKeyRef(v) - if err != nil { - return obj, err - } - } - if v, ok := in["resource_field_ref"].([]interface{}); ok && len(v) > 0 { - obj.ResourceFieldRef, err = expandResourceFieldRef(v) - if err != nil { - return obj, err - } - } - return obj, nil - -} - -func expandConfigMapRef(r []interface{}) (*v1.ConfigMapEnvSource, error) { - if len(r) == 0 || r[0] == nil { - return &v1.ConfigMapEnvSource{}, nil - } - in := r[0].(map[string]interface{}) - obj := &v1.ConfigMapEnvSource{} - - if v, ok := in["name"].(string); ok { - obj.Name = v - } - if v, ok := in["optional"]; ok { - obj.Optional = ptrToBool(v.(bool)) - } - - return obj, nil -} - -func expandContainerResourceRequirements(l []interface{}) (*v1.ResourceRequirements, error) { - obj := &v1.ResourceRequirements{} - if len(l) == 0 || l[0] == nil { - return obj, nil - } - in := l[0].(map[string]interface{}) - - fn := func(in []interface{}) (*v1.ResourceList, error) { - for _, c := range in { - p := c.(map[string]interface{}) - if p["cpu"] == "" { - delete(p, "cpu") - } - if p["memory"] == "" { - delete(p, "memory") - } - rl, err := expandMapToResourceList(p) - if err != nil { - return rl, err - } - return rl, nil - } - return nil, nil - } - - if v, ok := in["limits"].([]interface{}); ok && len(v) > 0 { - rl, err := fn(v) - if err != nil { - return obj, err - } - obj.Limits = *rl - } - - if v, ok := in["requests"].([]interface{}); ok && len(v) > 0 { - rq, err := fn(v) - if err != nil { - return obj, err - } - obj.Requests = *rq - } - - return obj, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_daemonset.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_daemonset.go deleted file mode 100644 index 10634eb2d16..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_daemonset.go +++ /dev/null @@ -1,113 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - appsv1 "k8s.io/api/apps/v1" - "k8s.io/apimachinery/pkg/util/intstr" -) - -func flattenDaemonSetSpec(in appsv1.DaemonSetSpec, d *schema.ResourceData) ([]interface{}, error) { - att := make(map[string]interface{}) - att["min_ready_seconds"] = in.MinReadySeconds - - att["strategy"] = flattenDaemonSetStrategy(in.UpdateStrategy) - - if in.RevisionHistoryLimit != nil { - att["revision_history_limit"] = *in.RevisionHistoryLimit - } - - if in.Selector != nil { - att["selector"] = flattenLabelSelector(in.Selector) - } - - podSpec, err := flattenPodSpec(in.Template.Spec) - if err != nil { - return nil, err - } - template := make(map[string]interface{}) - template["spec"] = podSpec - template["metadata"] = flattenMetadata(in.Template.ObjectMeta, d, "spec.0.template.0.") - att["template"] = []interface{}{template} - - return []interface{}{att}, nil -} - -func flattenDaemonSetStrategy(in appsv1.DaemonSetUpdateStrategy) []interface{} { - att := make(map[string]interface{}) - if in.Type != "" { - att["type"] = in.Type - } - if in.RollingUpdate != nil { - att["rolling_update"] = flattenDaemonSetStrategyRollingUpdate(in.RollingUpdate) - } - return []interface{}{att} -} - -func flattenDaemonSetStrategyRollingUpdate(in *appsv1.RollingUpdateDaemonSet) []interface{} { - att := make(map[string]interface{}) - if in.MaxUnavailable != nil { - att["max_unavailable"] = in.MaxUnavailable.String() - } - return []interface{}{att} -} - -func expandDaemonSetSpec(daemonset []interface{}) (appsv1.DaemonSetSpec, error) { - obj := appsv1.DaemonSetSpec{} - - if len(daemonset) == 0 || daemonset[0] == nil { - return obj, nil - } - - in := daemonset[0].(map[string]interface{}) - - obj.MinReadySeconds = int32(in["min_ready_seconds"].(int)) - obj.RevisionHistoryLimit = ptrToInt32(int32(in["revision_history_limit"].(int))) - - if v, ok := in["selector"].([]interface{}); ok && len(v) > 0 { - obj.Selector = expandLabelSelector(v) - } - - if v, ok := in["strategy"].([]interface{}); ok && len(v) > 0 { - obj.UpdateStrategy = expandDaemonSetStrategy(v) - } - - template, err := expandPodTemplate(in["template"].([]interface{})) - if err != nil { - return obj, err - } - obj.Template = *template - - return obj, nil -} - -func expandDaemonSetStrategy(p []interface{}) appsv1.DaemonSetUpdateStrategy { - obj := appsv1.DaemonSetUpdateStrategy{} - - if len(p) == 0 || p[0] == nil { - obj.Type = appsv1.RollingUpdateDaemonSetStrategyType - return obj - } - in := p[0].(map[string]interface{}) - - if v, ok := in["type"].(string); ok { - obj.Type = appsv1.DaemonSetUpdateStrategyType(v) - } - if v, ok := in["rolling_update"].([]interface{}); ok && len(v) > 0 { - obj.RollingUpdate = expandRollingUpdateDaemonSet(v) - } - return obj -} - -func expandRollingUpdateDaemonSet(p []interface{}) *appsv1.RollingUpdateDaemonSet { - obj := appsv1.RollingUpdateDaemonSet{} - if len(p) == 0 || p[0] == nil { - return nil - } - in := p[0].(map[string]interface{}) - - if v, ok := in["max_unavailable"].(string); ok { - val := intstr.Parse(v) - obj.MaxUnavailable = &val - } - return &obj -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_deployment.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_deployment.go deleted file mode 100644 index 9387f4d020a..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_deployment.go +++ /dev/null @@ -1,151 +0,0 @@ -package kubernetes - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/util/intstr" -) - -func flattenDeploymentSpec(in appsv1.DeploymentSpec, d *schema.ResourceData) ([]interface{}, error) { - att := make(map[string]interface{}) - att["min_ready_seconds"] = in.MinReadySeconds - - if in.Replicas != nil { - att["replicas"] = *in.Replicas - } - - if in.ProgressDeadlineSeconds != nil { - att["progress_deadline_seconds"] = *in.ProgressDeadlineSeconds - } - - if in.RevisionHistoryLimit != nil { - att["revision_history_limit"] = *in.RevisionHistoryLimit - } - - if in.Selector != nil { - att["selector"] = flattenLabelSelector(in.Selector) - } - - att["strategy"] = flattenDeploymentStrategy(in.Strategy) - - podSpec, err := flattenPodSpec(in.Template.Spec) - if err != nil { - return nil, err - } - template := make(map[string]interface{}) - template["spec"] = podSpec - template["metadata"] = flattenMetadata(in.Template.ObjectMeta, d, "spec.0.template.0.") - att["template"] = []interface{}{template} - - return []interface{}{att}, nil -} - -func flattenDeploymentStrategy(in appsv1.DeploymentStrategy) []interface{} { - att := make(map[string]interface{}) - if in.Type != "" { - att["type"] = in.Type - } - if in.RollingUpdate != nil { - att["rolling_update"] = flattenDeploymentStrategyRollingUpdate(in.RollingUpdate) - } - return []interface{}{att} -} - -func flattenDeploymentStrategyRollingUpdate(in *appsv1.RollingUpdateDeployment) []interface{} { - att := make(map[string]interface{}) - if in.MaxUnavailable != nil { - att["max_unavailable"] = in.MaxUnavailable.String() - } - if in.MaxSurge != nil { - att["max_surge"] = in.MaxSurge.String() - } - return []interface{}{att} -} - -func expandDeploymentSpec(deployment []interface{}) (*appsv1.DeploymentSpec, error) { - obj := &appsv1.DeploymentSpec{} - - if len(deployment) == 0 || deployment[0] == nil { - return obj, nil - } - - in := deployment[0].(map[string]interface{}) - - obj.MinReadySeconds = int32(in["min_ready_seconds"].(int)) - obj.Paused = in["paused"].(bool) - obj.ProgressDeadlineSeconds = ptrToInt32(int32(in["progress_deadline_seconds"].(int))) - obj.Replicas = ptrToInt32(int32(in["replicas"].(int))) - obj.RevisionHistoryLimit = ptrToInt32(int32(in["revision_history_limit"].(int))) - - if v, ok := in["selector"].([]interface{}); ok && len(v) > 0 { - obj.Selector = expandLabelSelector(v) - } - - if v, ok := in["strategy"].([]interface{}); ok && len(v) > 0 { - obj.Strategy = expandDeploymentStrategy(v) - } - - template, err := expandPodTemplate(in["template"].([]interface{})) - if err != nil { - return obj, err - } - obj.Template = *template - - return obj, nil -} - -func expandPodTemplate(l []interface{}) (*corev1.PodTemplateSpec, error) { - obj := &corev1.PodTemplateSpec{} - if len(l) == 0 || l[0] == nil { - return obj, nil - } - in := l[0].(map[string]interface{}) - - obj.ObjectMeta = expandMetadata(in["metadata"].([]interface{})) - - if v, ok := in["spec"].([]interface{}); ok && len(v) > 0 { - podSpec, err := expandPodSpec(in["spec"].([]interface{})) - if err != nil { - return obj, err - } - obj.Spec = *podSpec - } - return obj, nil -} - -func expandDeploymentStrategy(l []interface{}) appsv1.DeploymentStrategy { - obj := appsv1.DeploymentStrategy{} - - if len(l) == 0 || l[0] == nil { - obj.Type = appsv1.RollingUpdateDeploymentStrategyType - return obj - } - in := l[0].(map[string]interface{}) - - if v, ok := in["type"].(string); ok { - obj.Type = appsv1.DeploymentStrategyType(v) - } - if v, ok := in["rolling_update"].([]interface{}); ok && len(v) > 0 { - obj.RollingUpdate = expandRollingUpdateDeployment(v) - } - return obj -} - -func expandRollingUpdateDeployment(l []interface{}) *appsv1.RollingUpdateDeployment { - obj := appsv1.RollingUpdateDeployment{} - if len(l) == 0 || l[0] == nil { - return nil - } - in := l[0].(map[string]interface{}) - - if v, ok := in["max_surge"].(string); ok { - val := intstr.Parse(v) - obj.MaxSurge = &val - } - if v, ok := in["max_unavailable"].(string); ok { - val := intstr.Parse(v) - obj.MaxUnavailable = &val - } - return &obj -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_pod.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_pod.go deleted file mode 100644 index e6e1ba1b20b..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_pod.go +++ /dev/null @@ -1,1381 +0,0 @@ -package kubernetes - -import ( - "fmt" - "log" - "strconv" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" -) - -// Flatteners - -func flattenPodSpec(in v1.PodSpec) ([]interface{}, error) { - att := make(map[string]interface{}) - if in.ActiveDeadlineSeconds != nil { - att["active_deadline_seconds"] = *in.ActiveDeadlineSeconds - } - - if in.Affinity != nil { - att["affinity"] = flattenAffinity(in.Affinity) - } - - if in.AutomountServiceAccountToken != nil { - att["automount_service_account_token"] = *in.AutomountServiceAccountToken - } - - containers, err := flattenContainers(in.Containers) - if err != nil { - return nil, err - } - att["container"] = containers - - gates, err := flattenReadinessGates(in.ReadinessGates) - if err != nil { - return nil, err - } - att["readiness_gate"] = gates - - initContainers, err := flattenContainers(in.InitContainers) - if err != nil { - return nil, err - } - att["init_container"] = initContainers - - att["dns_policy"] = in.DNSPolicy - if in.DNSConfig != nil { - v, err := flattenPodDNSConfig(in.DNSConfig) - if err != nil { - return []interface{}{att}, err - } - att["dns_config"] = v - } - - if in.EnableServiceLinks != nil { - att["enable_service_links"] = *in.EnableServiceLinks - } else { - att["enable_service_links"] = true - } - - att["host_aliases"] = flattenHostaliases(in.HostAliases) - - att["host_ipc"] = in.HostIPC - att["host_network"] = in.HostNetwork - att["host_pid"] = in.HostPID - - if in.Hostname != "" { - att["hostname"] = in.Hostname - } - att["image_pull_secrets"] = flattenLocalObjectReferenceArray(in.ImagePullSecrets) - - if in.NodeName != "" { - att["node_name"] = in.NodeName - } - if len(in.NodeSelector) > 0 { - att["node_selector"] = in.NodeSelector - } - if in.PriorityClassName != "" { - att["priority_class_name"] = in.PriorityClassName - } - if in.RestartPolicy != "" { - att["restart_policy"] = in.RestartPolicy - } - - if in.SecurityContext != nil { - att["security_context"] = flattenPodSecurityContext(in.SecurityContext) - } - if in.ServiceAccountName != "" { - att["service_account_name"] = in.ServiceAccountName - } - if in.ShareProcessNamespace != nil { - att["share_process_namespace"] = *in.ShareProcessNamespace - } - - if in.Subdomain != "" { - att["subdomain"] = in.Subdomain - } - - if in.TerminationGracePeriodSeconds != nil { - att["termination_grace_period_seconds"] = *in.TerminationGracePeriodSeconds - } - - if len(in.Tolerations) > 0 { - att["toleration"] = flattenTolerations(in.Tolerations) - } - - if len(in.Volumes) > 0 { - v, err := flattenVolumes(in.Volumes) - if err != nil { - return []interface{}{att}, err - } - att["volume"] = v - } - return []interface{}{att}, nil -} - -func flattenPodDNSConfig(in *v1.PodDNSConfig) ([]interface{}, error) { - att := make(map[string]interface{}) - - if len(in.Nameservers) > 0 { - att["nameservers"] = in.Nameservers - } - if len(in.Searches) > 0 { - att["searches"] = in.Searches - } - if len(in.Options) > 0 { - v, err := flattenPodDNSConfigOptions(in.Options) - if err != nil { - return []interface{}{att}, err - } - att["option"] = v - } - - if len(att) > 0 { - return []interface{}{att}, nil - } - return []interface{}{}, nil -} - -func flattenPodDNSConfigOptions(options []v1.PodDNSConfigOption) ([]interface{}, error) { - att := make([]interface{}, len(options)) - for i, v := range options { - obj := map[string]interface{}{} - - if v.Name != "" { - obj["name"] = v.Name - } - if v.Value != nil { - obj["value"] = *v.Value - } - att[i] = obj - } - return att, nil -} - -func flattenPodSecurityContext(in *v1.PodSecurityContext) []interface{} { - att := make(map[string]interface{}) - - if in.FSGroup != nil { - att["fs_group"] = *in.FSGroup - } - if in.RunAsGroup != nil { - att["run_as_group"] = *in.RunAsGroup - } - if in.RunAsNonRoot != nil { - att["run_as_non_root"] = *in.RunAsNonRoot - } - if in.RunAsUser != nil { - att["run_as_user"] = *in.RunAsUser - } - if len(in.SupplementalGroups) > 0 { - att["supplemental_groups"] = newInt64Set(schema.HashSchema(&schema.Schema{ - Type: schema.TypeInt, - }), in.SupplementalGroups) - } - if in.SELinuxOptions != nil { - att["se_linux_options"] = flattenSeLinuxOptions(in.SELinuxOptions) - } - if in.Sysctls != nil { - att["sysctl"] = flattenSysctls(in.Sysctls) - } - - if len(att) > 0 { - return []interface{}{att} - } - return []interface{}{} -} - -func flattenSeLinuxOptions(in *v1.SELinuxOptions) []interface{} { - att := make(map[string]interface{}) - if in.User != "" { - att["user"] = in.User - } - if in.Role != "" { - att["role"] = in.Role - } - if in.User != "" { - att["type"] = in.Type - } - if in.Level != "" { - att["level"] = in.Level - } - return []interface{}{att} -} - -func flattenSysctls(sysctls []v1.Sysctl) []interface{} { - att := []interface{}{} - for _, v := range sysctls { - obj := map[string]interface{}{} - - if v.Name != "" { - obj["name"] = v.Name - } - if v.Value != "" { - obj["value"] = v.Value - } - att = append(att, obj) - } - return att -} - -func flattenTolerations(tolerations []v1.Toleration) []interface{} { - att := []interface{}{} - for _, v := range tolerations { - // The API Server may automatically add several Tolerations to pods, strip these to avoid TF diff. - if strings.Contains(v.Key, "node.kubernetes.io/") { - log.Printf("[INFO] ignoring toleration with key: %s", v.Key) - continue - } - obj := map[string]interface{}{} - - if v.Effect != "" { - obj["effect"] = string(v.Effect) - } - if v.Key != "" { - obj["key"] = v.Key - } - if v.Operator != "" { - obj["operator"] = string(v.Operator) - } - if v.TolerationSeconds != nil { - obj["toleration_seconds"] = strconv.FormatInt(*v.TolerationSeconds, 10) - } - if v.Value != "" { - obj["value"] = v.Value - } - att = append(att, obj) - } - return att -} - -func flattenVolumes(volumes []v1.Volume) ([]interface{}, error) { - att := make([]interface{}, len(volumes)) - for i, v := range volumes { - obj := map[string]interface{}{} - - if v.Name != "" { - obj["name"] = v.Name - } - if v.ConfigMap != nil { - obj["config_map"] = flattenConfigMapVolumeSource(v.ConfigMap) - } - if v.GitRepo != nil { - obj["git_repo"] = flattenGitRepoVolumeSource(v.GitRepo) - } - if v.EmptyDir != nil { - obj["empty_dir"] = flattenEmptyDirVolumeSource(v.EmptyDir) - } - if v.DownwardAPI != nil { - obj["downward_api"] = flattenDownwardAPIVolumeSource(v.DownwardAPI) - } - if v.PersistentVolumeClaim != nil { - obj["persistent_volume_claim"] = flattenPersistentVolumeClaimVolumeSource(v.PersistentVolumeClaim) - } - if v.Secret != nil { - obj["secret"] = flattenSecretVolumeSource(v.Secret) - } - if v.Projected != nil { - obj["projected"] = flattenProjectedVolumeSource(v.Projected) - } - if v.GCEPersistentDisk != nil { - obj["gce_persistent_disk"] = flattenGCEPersistentDiskVolumeSource(v.GCEPersistentDisk) - } - if v.AWSElasticBlockStore != nil { - obj["aws_elastic_block_store"] = flattenAWSElasticBlockStoreVolumeSource(v.AWSElasticBlockStore) - } - if v.HostPath != nil { - obj["host_path"] = flattenHostPathVolumeSource(v.HostPath) - } - if v.Glusterfs != nil { - obj["glusterfs"] = flattenGlusterfsVolumeSource(v.Glusterfs) - } - if v.NFS != nil { - obj["nfs"] = flattenNFSVolumeSource(v.NFS) - } - if v.RBD != nil { - obj["rbd"] = flattenRBDVolumeSource(v.RBD) - } - if v.ISCSI != nil { - obj["iscsi"] = flattenISCSIVolumeSource(v.ISCSI) - } - if v.Cinder != nil { - obj["cinder"] = flattenCinderVolumeSource(v.Cinder) - } - if v.CephFS != nil { - obj["ceph_fs"] = flattenCephFSVolumeSource(v.CephFS) - } - if v.FC != nil { - obj["fc"] = flattenFCVolumeSource(v.FC) - } - if v.Flocker != nil { - obj["flocker"] = flattenFlockerVolumeSource(v.Flocker) - } - if v.FlexVolume != nil { - obj["flex_volume"] = flattenFlexVolumeSource(v.FlexVolume) - } - if v.AzureFile != nil { - obj["azure_file"] = flattenAzureFileVolumeSource(v.AzureFile) - } - if v.VsphereVolume != nil { - obj["vsphere_volume"] = flattenVsphereVirtualDiskVolumeSource(v.VsphereVolume) - } - if v.Quobyte != nil { - obj["quobyte"] = flattenQuobyteVolumeSource(v.Quobyte) - } - if v.AzureDisk != nil { - obj["azure_disk"] = flattenAzureDiskVolumeSource(v.AzureDisk) - } - if v.PhotonPersistentDisk != nil { - obj["photon_persistent_disk"] = flattenPhotonPersistentDiskVolumeSource(v.PhotonPersistentDisk) - } - att[i] = obj - } - return att, nil -} - -func flattenPersistentVolumeClaimVolumeSource(in *v1.PersistentVolumeClaimVolumeSource) []interface{} { - att := make(map[string]interface{}) - if in.ClaimName != "" { - att["claim_name"] = in.ClaimName - } - if in.ReadOnly { - att["read_only"] = in.ReadOnly - } - - return []interface{}{att} -} -func flattenGitRepoVolumeSource(in *v1.GitRepoVolumeSource) []interface{} { - att := make(map[string]interface{}) - if in.Directory != "" { - att["directory"] = in.Directory - } - - att["repository"] = in.Repository - - if in.Revision != "" { - att["revision"] = in.Revision - } - return []interface{}{att} -} - -func flattenDownwardAPIVolumeSource(in *v1.DownwardAPIVolumeSource) []interface{} { - att := make(map[string]interface{}) - if in.DefaultMode != nil { - att["default_mode"] = "0" + strconv.FormatInt(int64(*in.DefaultMode), 8) - } - if len(in.Items) > 0 { - att["items"] = flattenDownwardAPIVolumeFile(in.Items) - } - return []interface{}{att} -} - -func flattenDownwardAPIVolumeFile(in []v1.DownwardAPIVolumeFile) []interface{} { - att := make([]interface{}, len(in)) - for i, v := range in { - m := map[string]interface{}{} - if v.FieldRef != nil { - m["field_ref"] = flattenObjectFieldSelector(v.FieldRef) - } - if v.Mode != nil { - m["mode"] = "0" + strconv.FormatInt(int64(*v.Mode), 8) - } - if v.Path != "" { - m["path"] = v.Path - } - if v.ResourceFieldRef != nil { - m["resource_field_ref"] = flattenResourceFieldSelector(v.ResourceFieldRef) - } - att[i] = m - } - return att -} - -func flattenConfigMapVolumeSource(in *v1.ConfigMapVolumeSource) []interface{} { - att := make(map[string]interface{}) - if in.DefaultMode != nil { - att["default_mode"] = "0" + strconv.FormatInt(int64(*in.DefaultMode), 8) - } - att["name"] = in.Name - if len(in.Items) > 0 { - items := make([]interface{}, len(in.Items)) - for i, v := range in.Items { - m := map[string]interface{}{} - if v.Key != "" { - m["key"] = v.Key - } - if v.Mode != nil { - m["mode"] = "0" + strconv.FormatInt(int64(*v.Mode), 8) - } - if v.Path != "" { - m["path"] = v.Path - } - items[i] = m - } - att["items"] = items - } - if in.Optional != nil { - att["optional"] = *in.Optional - } - return []interface{}{att} -} - -func flattenEmptyDirVolumeSource(in *v1.EmptyDirVolumeSource) []interface{} { - att := make(map[string]interface{}) - att["medium"] = string(in.Medium) - if in.SizeLimit != nil { - att["size_limit"] = in.SizeLimit.String() - } - return []interface{}{att} -} - -func flattenSecretVolumeSource(in *v1.SecretVolumeSource) []interface{} { - att := make(map[string]interface{}) - if in.DefaultMode != nil { - att["default_mode"] = "0" + strconv.FormatInt(int64(*in.DefaultMode), 8) - } - if in.SecretName != "" { - att["secret_name"] = in.SecretName - } - if len(in.Items) > 0 { - items := make([]interface{}, len(in.Items)) - for i, v := range in.Items { - m := map[string]interface{}{} - m["key"] = v.Key - if v.Mode != nil { - m["mode"] = "0" + strconv.FormatInt(int64(*v.Mode), 8) - } - m["path"] = v.Path - items[i] = m - } - att["items"] = items - } - if in.Optional != nil { - att["optional"] = *in.Optional - } - return []interface{}{att} -} - -func flattenProjectedVolumeSource(in *v1.ProjectedVolumeSource) []interface{} { - att := make(map[string]interface{}) - if in.DefaultMode != nil { - att["default_mode"] = "0" + strconv.FormatInt(int64(*in.DefaultMode), 8) - } - if len(in.Sources) > 0 { - sources := make([]interface{}, 0, len(in.Sources)) - for _, src := range in.Sources { - s := make(map[string]interface{}) - if src.Secret != nil { - s["secret"] = flattenSecretProjection(src.Secret) - } - if src.ConfigMap != nil { - s["config_map"] = flattenConfigMapProjection(src.ConfigMap) - } - if src.DownwardAPI != nil { - s["downward_api"] = flattenDownwardAPIProjection(src.DownwardAPI) - } - if src.ServiceAccountToken != nil { - s["service_account_token"] = flattenServiceAccountTokenProjection(src.ServiceAccountToken) - } - sources = append(sources, s) - } - att["sources"] = sources - } - return []interface{}{att} -} - -func flattenSecretProjection(in *v1.SecretProjection) []interface{} { - att := make(map[string]interface{}) - if in.Name != "" { - att["name"] = in.Name - } - if len(in.Items) > 0 { - items := make([]interface{}, len(in.Items)) - for i, v := range in.Items { - m := map[string]interface{}{} - m["key"] = v.Key - if v.Mode != nil { - m["mode"] = "0" + strconv.FormatInt(int64(*v.Mode), 8) - } - m["path"] = v.Path - items[i] = m - } - att["items"] = items - } - if in.Optional != nil { - att["optional"] = *in.Optional - } - return []interface{}{att} -} - -func flattenConfigMapProjection(in *v1.ConfigMapProjection) []interface{} { - att := make(map[string]interface{}) - att["name"] = in.Name - if len(in.Items) > 0 { - items := make([]interface{}, len(in.Items)) - for i, v := range in.Items { - m := map[string]interface{}{} - if v.Key != "" { - m["key"] = v.Key - } - if v.Mode != nil { - m["mode"] = "0" + strconv.FormatInt(int64(*v.Mode), 8) - } - if v.Path != "" { - m["path"] = v.Path - } - items[i] = m - } - att["items"] = items - } - return []interface{}{att} -} - -func flattenDownwardAPIProjection(in *v1.DownwardAPIProjection) []interface{} { - att := make(map[string]interface{}) - if len(in.Items) > 0 { - att["items"] = flattenDownwardAPIVolumeFile(in.Items) - } - return []interface{}{att} -} - -func flattenServiceAccountTokenProjection(in *v1.ServiceAccountTokenProjection) []interface{} { - att := make(map[string]interface{}) - if in.Audience != "" { - att["audience"] = in.Audience - } - if in.ExpirationSeconds != nil { - att["expiration_seconds"] = in.ExpirationSeconds - } - if in.Path != "" { - att["path"] = in.Path - } - return []interface{}{att} -} - -func flattenReadinessGates(in []v1.PodReadinessGate) ([]interface{}, error) { - att := make([]interface{}, len(in)) - for i, v := range in { - c := make(map[string]interface{}) - c["condition_type"] = v.ConditionType - att[i] = c - } - return att, nil -} - -// Expanders - -func expandPodSpec(p []interface{}) (*v1.PodSpec, error) { - obj := &v1.PodSpec{} - if len(p) == 0 || p[0] == nil { - return obj, nil - } - in := p[0].(map[string]interface{}) - - if v, ok := in["active_deadline_seconds"].(int); ok && v > 0 { - obj.ActiveDeadlineSeconds = ptrToInt64(int64(v)) - } - - if v, ok := in["affinity"].([]interface{}); ok && len(v) > 0 { - a, err := expandAffinity(v) - if err != nil { - return obj, err - } - obj.Affinity = a - } - - if v, ok := in["automount_service_account_token"].(bool); ok { - obj.AutomountServiceAccountToken = ptrToBool(v) - } - - if v, ok := in["container"].([]interface{}); ok && len(v) > 0 { - cs, err := expandContainers(v) - if err != nil { - return obj, err - } - obj.Containers = cs - } - - if v, ok := in["readiness_gate"].([]interface{}); ok && len(v) > 0 { - cs, err := expandReadinessGates(v) - if err != nil { - return obj, err - } - obj.ReadinessGates = cs - } - - if v, ok := in["init_container"].([]interface{}); ok && len(v) > 0 { - cs, err := expandContainers(v) - if err != nil { - return obj, err - } - obj.InitContainers = cs - } - - if v, ok := in["dns_policy"].(string); ok { - obj.DNSPolicy = v1.DNSPolicy(v) - } - - if v, ok := in["dns_config"].([]interface{}); ok && len(v) > 0 { - dnsConfig, err := expandPodDNSConfig(v) - if err != nil { - return obj, nil - } - obj.DNSConfig = dnsConfig - } - - if v, ok := in["enable_service_links"].(bool); ok { - obj.EnableServiceLinks = ptrToBool(v) - } - - if v, ok := in["host_aliases"].([]interface{}); ok && len(v) > 0 { - hs, err := expandHostaliases(v) - if err != nil { - return obj, err - } - obj.HostAliases = hs - } - - if v, ok := in["host_ipc"]; ok { - obj.HostIPC = v.(bool) - } - - if v, ok := in["host_network"]; ok { - obj.HostNetwork = v.(bool) - } - - if v, ok := in["host_pid"]; ok { - obj.HostPID = v.(bool) - } - - if v, ok := in["hostname"]; ok { - obj.Hostname = v.(string) - } - - if v, ok := in["image_pull_secrets"].([]interface{}); ok { - cs := expandLocalObjectReferenceArray(v) - obj.ImagePullSecrets = cs - } - - if v, ok := in["node_name"]; ok { - obj.NodeName = v.(string) - } - - if v, ok := in["node_selector"].(map[string]interface{}); ok { - nodeSelectors := make(map[string]string) - for k, v := range v { - if val, ok := v.(string); ok { - nodeSelectors[k] = val - } - } - obj.NodeSelector = nodeSelectors - } - - if v, ok := in["priority_class_name"].(string); ok { - obj.PriorityClassName = v - } - - if v, ok := in["restart_policy"].(string); ok { - obj.RestartPolicy = v1.RestartPolicy(v) - } - - if v, ok := in["security_context"].([]interface{}); ok && len(v) > 0 { - obj.SecurityContext = expandPodSecurityContext(v) - } - - if v, ok := in["service_account_name"].(string); ok { - obj.ServiceAccountName = v - } - - if v, ok := in["share_process_namespace"]; ok { - obj.ShareProcessNamespace = ptrToBool(v.(bool)) - } - - if v, ok := in["subdomain"].(string); ok { - obj.Subdomain = v - } - - if v, ok := in["termination_grace_period_seconds"].(int); ok { - obj.TerminationGracePeriodSeconds = ptrToInt64(int64(v)) - } - - if v, ok := in["toleration"].([]interface{}); ok && len(v) > 0 { - ts, err := expandTolerations(v) - if err != nil { - return obj, err - } - for _, t := range ts { - obj.Tolerations = append(obj.Tolerations, *t) - } - } - - if v, ok := in["volume"].([]interface{}); ok && len(v) > 0 { - cs, err := expandVolumes(v) - if err != nil { - return obj, err - } - obj.Volumes = cs - } - return obj, nil -} - -func expandPodDNSConfig(l []interface{}) (*v1.PodDNSConfig, error) { - if len(l) == 0 || l[0] == nil { - return &v1.PodDNSConfig{}, nil - } - in := l[0].(map[string]interface{}) - obj := &v1.PodDNSConfig{} - if v, ok := in["nameservers"].([]interface{}); ok { - obj.Nameservers = expandStringSlice(v) - } - if v, ok := in["searches"].([]interface{}); ok { - obj.Searches = expandStringSlice(v) - } - if v, ok := in["option"].([]interface{}); ok { - opts, err := expandDNSConfigOptions(v) - if err != nil { - return obj, err - } - obj.Options = opts - } - return obj, nil -} - -func expandDNSConfigOptions(options []interface{}) ([]v1.PodDNSConfigOption, error) { - if len(options) == 0 { - return []v1.PodDNSConfigOption{}, nil - } - opts := make([]v1.PodDNSConfigOption, len(options)) - for i, c := range options { - in := c.(map[string]interface{}) - opt := v1.PodDNSConfigOption{} - if v, ok := in["name"].(string); ok { - opt.Name = v - } - if v, ok := in["value"].(string); ok { - opt.Value = ptrToString(v) - } - opts[i] = opt - } - - return opts, nil -} - -func expandPodSecurityContext(l []interface{}) *v1.PodSecurityContext { - if len(l) == 0 || l[0] == nil { - return &v1.PodSecurityContext{} - } - in := l[0].(map[string]interface{}) - obj := &v1.PodSecurityContext{} - if v, ok := in["fs_group"].(int); ok { - obj.FSGroup = ptrToInt64(int64(v)) - } - if v, ok := in["run_as_group"].(int); ok { - obj.RunAsGroup = ptrToInt64(int64(v)) - } - if v, ok := in["run_as_non_root"].(bool); ok { - obj.RunAsNonRoot = ptrToBool(v) - } - if v, ok := in["run_as_user"].(int); ok { - obj.RunAsUser = ptrToInt64(int64(v)) - } - if v, ok := in["se_linux_options"].([]interface{}); ok && len(v) > 0 { - obj.SELinuxOptions = expandSeLinuxOptions(v) - } - if v, ok := in["supplemental_groups"].(*schema.Set); ok { - obj.SupplementalGroups = schemaSetToInt64Array(v) - } - if v, ok := in["sysctl"].([]interface{}); ok && len(v) > 0 { - obj.Sysctls = expandSysctls(v) - } - - return obj -} - -func expandSysctls(l []interface{}) []v1.Sysctl { - if len(l) == 0 { - return []v1.Sysctl{} - } - sysctls := make([]v1.Sysctl, len(l)) - for i, c := range l { - p := c.(map[string]interface{}) - if v, ok := p["name"].(string); ok { - sysctls[i].Name = v - } - if v, ok := p["value"].(string); ok { - sysctls[i].Value = v - } - - } - return sysctls -} - -func expandSeLinuxOptions(l []interface{}) *v1.SELinuxOptions { - if len(l) == 0 || l[0] == nil { - return &v1.SELinuxOptions{} - } - in := l[0].(map[string]interface{}) - obj := &v1.SELinuxOptions{} - if v, ok := in["level"]; ok { - obj.Level = v.(string) - } - if v, ok := in["role"]; ok { - obj.Role = v.(string) - } - if v, ok := in["type"]; ok { - obj.Type = v.(string) - } - if v, ok := in["user"]; ok { - obj.User = v.(string) - } - return obj -} - -func expandKeyPath(in []interface{}) []v1.KeyToPath { - if len(in) == 0 { - return []v1.KeyToPath{} - } - keyPaths := make([]v1.KeyToPath, len(in)) - for i, c := range in { - p := c.(map[string]interface{}) - if v, ok := p["key"].(string); ok { - keyPaths[i].Key = v - } - if v, ok := p["mode"].(string); ok { - m, err := strconv.ParseInt(v, 8, 32) - if err == nil { - keyPaths[i].Mode = ptrToInt32(int32(m)) - } - } - if v, ok := p["path"].(string); ok { - keyPaths[i].Path = v - } - - } - return keyPaths -} - -func expandDownwardAPIVolumeFile(in []interface{}) ([]v1.DownwardAPIVolumeFile, error) { - var err error - if len(in) == 0 { - return []v1.DownwardAPIVolumeFile{}, nil - } - dapivf := make([]v1.DownwardAPIVolumeFile, len(in)) - for i, c := range in { - p := c.(map[string]interface{}) - if mode, ok := p["mode"].(string); ok && len(mode) > 0 { - m, err := strconv.ParseInt(mode, 8, 32) - if err != nil { - return dapivf, fmt.Errorf("DownwardAPI volume file: failed to parse 'mode' value: %s", err) - } - dapivf[i].Mode = ptrToInt32(int32(m)) - } - if v, ok := p["path"].(string); ok { - dapivf[i].Path = v - } - if v, ok := p["field_ref"].([]interface{}); ok && len(v) > 0 { - dapivf[i].FieldRef, err = expandFieldRef(v) - if err != nil { - return dapivf, err - } - } - if v, ok := p["resource_field_ref"].([]interface{}); ok && len(v) > 0 { - dapivf[i].ResourceFieldRef, err = expandResourceFieldRef(v) - if err != nil { - return dapivf, err - } - } - } - return dapivf, nil -} - -func expandConfigMapVolumeSource(l []interface{}) (*v1.ConfigMapVolumeSource, error) { - obj := &v1.ConfigMapVolumeSource{} - if len(l) == 0 || l[0] == nil { - return obj, nil - } - in := l[0].(map[string]interface{}) - - if mode, ok := in["default_mode"].(string); ok && len(mode) > 0 { - v, err := strconv.ParseInt(mode, 8, 32) - if err != nil { - return obj, fmt.Errorf("ConfigMap volume: failed to parse 'default_mode' value: %s", err) - } - obj.DefaultMode = ptrToInt32(int32(v)) - } - - if v, ok := in["name"].(string); ok { - obj.Name = v - } - - if opt, ok := in["optional"].(bool); ok { - obj.Optional = ptrToBool(opt) - } - if v, ok := in["items"].([]interface{}); ok && len(v) > 0 { - obj.Items = expandKeyPath(v) - } - - return obj, nil -} - -func expandDownwardAPIVolumeSource(l []interface{}) (*v1.DownwardAPIVolumeSource, error) { - obj := &v1.DownwardAPIVolumeSource{} - if len(l) == 0 || l[0] == nil { - return obj, nil - } - in := l[0].(map[string]interface{}) - - if mode, ok := in["default_mode"].(string); ok && len(mode) > 0 { - v, err := strconv.ParseInt(mode, 8, 32) - if err != nil { - return obj, fmt.Errorf("Downward API volume: failed to parse 'default_mode' value: %s", err) - } - obj.DefaultMode = ptrToInt32(int32(v)) - } - - if v, ok := in["items"].([]interface{}); ok && len(v) > 0 { - var err error - obj.Items, err = expandDownwardAPIVolumeFile(v) - if err != nil { - return obj, err - } - } - return obj, nil -} - -func expandGitRepoVolumeSource(l []interface{}) *v1.GitRepoVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.GitRepoVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.GitRepoVolumeSource{} - - if v, ok := in["directory"].(string); ok { - obj.Directory = v - } - - if v, ok := in["repository"].(string); ok { - obj.Repository = v - } - if v, ok := in["revision"].(string); ok { - obj.Revision = v - } - return obj -} - -func expandEmptyDirVolumeSource(l []interface{}) (*v1.EmptyDirVolumeSource, error) { - if len(l) == 0 || l[0] == nil { - return &v1.EmptyDirVolumeSource{}, nil - } - in := l[0].(map[string]interface{}) - obj := &v1.EmptyDirVolumeSource{ - Medium: v1.StorageMedium(in["medium"].(string)), - } - - if v, ok := in["size_limit"].(string); ok && v != "" { - s, err := resource.ParseQuantity(v) - if err != nil { - return nil, fmt.Errorf("failed to parse size_limit: %w", err) - } - obj.SizeLimit = &s - } - - return obj, nil -} - -func expandPersistentVolumeClaimVolumeSource(l []interface{}) *v1.PersistentVolumeClaimVolumeSource { - if len(l) == 0 || l[0] == nil { - return &v1.PersistentVolumeClaimVolumeSource{} - } - in := l[0].(map[string]interface{}) - obj := &v1.PersistentVolumeClaimVolumeSource{ - ClaimName: in["claim_name"].(string), - ReadOnly: in["read_only"].(bool), - } - return obj -} - -func expandSecretVolumeSource(l []interface{}) (*v1.SecretVolumeSource, error) { - obj := &v1.SecretVolumeSource{} - if len(l) == 0 || l[0] == nil { - return obj, nil - } - in := l[0].(map[string]interface{}) - - if mode, ok := in["default_mode"].(string); ok && len(mode) > 0 { - v, err := strconv.ParseInt(mode, 8, 32) - if err != nil { - return obj, fmt.Errorf("Secret volume: failed to parse 'default_mode' value: %s", err) - } - obj.DefaultMode = ptrToInt32(int32(v)) - } - - if secret, ok := in["secret_name"].(string); ok { - obj.SecretName = secret - } - - if opt, ok := in["optional"].(bool); ok { - obj.Optional = ptrToBool(opt) - } - if v, ok := in["items"].([]interface{}); ok && len(v) > 0 { - obj.Items = expandKeyPath(v) - } - - return obj, nil -} - -func expandProjectedVolumeSource(l []interface{}) (*v1.ProjectedVolumeSource, error) { - obj := &v1.ProjectedVolumeSource{} - if len(l) == 0 || l[0] == nil { - return obj, nil - } - in := l[0].(map[string]interface{}) - - if mode, ok := in["default_mode"].(string); ok && len(mode) > 0 { - v, err := strconv.ParseInt(mode, 8, 32) - if err != nil { - return obj, fmt.Errorf("Projected volume: failed to parse 'default_mode' value: %s", err) - } - obj.DefaultMode = ptrToInt32(int32(v)) - } - if v, ok := in["sources"].([]interface{}); ok && len(v) > 0 { - srcs, err := expandProjectedSources(v) - if err != nil { - return obj, fmt.Errorf("Projected volume: failed to parse 'sources' value: %s", err) - } - - obj.Sources = srcs - } - - return obj, nil -} - -func expandProjectedSources(sources []interface{}) ([]v1.VolumeProjection, error) { - if len(sources) == 0 || sources[0] == nil { - return []v1.VolumeProjection{}, nil - } - srcs := make([]v1.VolumeProjection, 0, len(sources)) - for _, src := range sources { - in, ok := src.(map[string]interface{}) - if !ok { - continue - } - if v, ok := in["secret"].([]interface{}); ok { - srcs = append(srcs, expandProjectedSecrets(v)...) - } - if v, ok := in["config_map"].([]interface{}); ok { - srcs = append(srcs, expandProjectedConfigMaps(v)...) - } - if v, ok := in["downward_api"].([]interface{}); ok { - values, err := expandProjectedDownwardAPIs(v) - if err != nil { - return nil, err - } - srcs = append(srcs, values...) - } - if v, ok := in["service_account_token"].([]interface{}); ok { - values, err := expandProjectedServiceAccountTokens(v) - if err != nil { - return nil, err - } - srcs = append(srcs, values...) - } - } - - return srcs, nil -} - -func expandProjectedSecrets(secrets []interface{}) []v1.VolumeProjection { - out := make([]v1.VolumeProjection, 0, len(secrets)) - for _, in := range secrets { - if v, ok := in.(map[string]interface{}); ok { - out = append(out, v1.VolumeProjection{Secret: expandProjectedSecret(v)}) - } - } - return out -} - -func expandProjectedSecret(secret map[string]interface{}) *v1.SecretProjection { - s := &v1.SecretProjection{} - if value, ok := secret["name"].(string); ok { - s.Name = value - } - if values, ok := secret["items"].([]interface{}); ok { - s.Items = expandKeyPath(values) - } - if value, ok := secret["optional"].(bool); ok { - s.Optional = ptrToBool(value) - } - return s -} - -func expandProjectedConfigMaps(configMaps []interface{}) []v1.VolumeProjection { - out := make([]v1.VolumeProjection, 0, len(configMaps)) - for _, in := range configMaps { - if v, ok := in.(map[string]interface{}); ok { - var vol v1.VolumeProjection - vol.ConfigMap = expandProjectedConfigMap(v) - out = append(out, vol) - } - } - return out -} - -func expandProjectedConfigMap(configMap map[string]interface{}) *v1.ConfigMapProjection { - s := &v1.ConfigMapProjection{} - if value, ok := configMap["name"].(string); ok { - s.Name = value - } - if values, ok := configMap["items"].([]interface{}); ok { - s.Items = expandKeyPath(values) - } - if value, ok := configMap["optional"].(bool); ok { - s.Optional = ptrToBool(value) - } - return s -} - -func expandProjectedDownwardAPIs(downwardAPIs []interface{}) ([]v1.VolumeProjection, error) { - out := make([]v1.VolumeProjection, 0, len(downwardAPIs)) - for i, in := range downwardAPIs { - if v, ok := in.(map[string]interface{}); ok { - downwardAPI, err := expandProjectedDownwardAPI(v) - if err != nil { - return nil, fmt.Errorf("expanding downward API #%d: %v", i+1, err) - } - out = append(out, v1.VolumeProjection{ - DownwardAPI: downwardAPI, - }) - } - } - return out, nil -} - -func expandProjectedDownwardAPI(downwardAPI map[string]interface{}) (*v1.DownwardAPIProjection, error) { - s := &v1.DownwardAPIProjection{} - if values, ok := downwardAPI["items"].([]interface{}); ok { - v, err := expandDownwardAPIVolumeFile(values) - if err != nil { - return nil, err - } - s.Items = v - } - return s, nil -} - -func expandProjectedServiceAccountTokens(sats []interface{}) ([]v1.VolumeProjection, error) { - out := make([]v1.VolumeProjection, 0, len(sats)) - for i, in := range sats { - if v, ok := in.(map[string]interface{}); ok { - sat, err := expandProjectedServiceAccountToken(v) - if err != nil { - return nil, fmt.Errorf("expanding service account token #%d: %v", i+1, err) - } - out = append(out, v1.VolumeProjection{ - ServiceAccountToken: sat, - }) - } - } - return out, nil -} - -func expandProjectedServiceAccountToken(sat map[string]interface{}) (*v1.ServiceAccountTokenProjection, error) { - s := &v1.ServiceAccountTokenProjection{} - if value, ok := sat["audience"].(string); ok { - s.Audience = value - } - if value, ok := sat["expiration_seconds"].(int); ok { - s.ExpirationSeconds = ptrToInt64(int64(value)) - } - if value, ok := sat["path"].(string); ok { - s.Path = value - } - return s, nil -} - -func expandTolerations(tolerations []interface{}) ([]*v1.Toleration, error) { - if len(tolerations) == 0 { - return []*v1.Toleration{}, nil - } - ts := make([]*v1.Toleration, len(tolerations)) - for i, t := range tolerations { - m := t.(map[string]interface{}) - ts[i] = &v1.Toleration{} - - if value, ok := m["effect"].(string); ok { - ts[i].Effect = v1.TaintEffect(value) - } - if value, ok := m["key"].(string); ok { - ts[i].Key = value - } - if value, ok := m["operator"].(string); ok { - ts[i].Operator = v1.TolerationOperator(value) - } - if value, ok := m["toleration_seconds"].(string); ok && value != "" { - seconds, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return nil, fmt.Errorf("invalid toleration_seconds must be int or \"\", got \"%s\"", value) - } - ts[i].TolerationSeconds = ptrToInt64(seconds) - } - if value, ok := m["value"]; ok { - ts[i].Value = value.(string) - } - } - return ts, nil -} - -func expandVolumes(volumes []interface{}) ([]v1.Volume, error) { - if len(volumes) == 0 { - return []v1.Volume{}, nil - } - vl := make([]v1.Volume, len(volumes)) - for i, c := range volumes { - m := c.(map[string]interface{}) - - if value, ok := m["name"]; ok { - vl[i].Name = value.(string) - } - - if value, ok := m["config_map"].([]interface{}); ok && len(value) > 0 { - cfm, err := expandConfigMapVolumeSource(value) - vl[i].ConfigMap = cfm - if err != nil { - return vl, err - } - } - if value, ok := m["git_repo"].([]interface{}); ok && len(value) > 0 { - vl[i].GitRepo = expandGitRepoVolumeSource(value) - } - - if value, ok := m["empty_dir"].([]interface{}); ok && len(value) > 0 { - var err error - vl[i].EmptyDir, err = expandEmptyDirVolumeSource(value) - if err != nil { - return vl, err - } - } - if value, ok := m["downward_api"].([]interface{}); ok && len(value) > 0 { - var err error - vl[i].DownwardAPI, err = expandDownwardAPIVolumeSource(value) - if err != nil { - return vl, err - } - } - - if value, ok := m["persistent_volume_claim"].([]interface{}); ok && len(value) > 0 { - vl[i].PersistentVolumeClaim = expandPersistentVolumeClaimVolumeSource(value) - } - if value, ok := m["secret"].([]interface{}); ok && len(value) > 0 { - sc, err := expandSecretVolumeSource(value) - if err != nil { - return vl, err - } - vl[i].Secret = sc - } - if value, ok := m["projected"].([]interface{}); ok && len(value) > 0 { - pj, err := expandProjectedVolumeSource(value) - if err != nil { - return vl, err - } - vl[i].Projected = pj - } - if v, ok := m["gce_persistent_disk"].([]interface{}); ok && len(v) > 0 { - vl[i].GCEPersistentDisk = expandGCEPersistentDiskVolumeSource(v) - } - if v, ok := m["aws_elastic_block_store"].([]interface{}); ok && len(v) > 0 { - vl[i].AWSElasticBlockStore = expandAWSElasticBlockStoreVolumeSource(v) - } - if v, ok := m["host_path"].([]interface{}); ok && len(v) > 0 { - vl[i].HostPath = expandHostPathVolumeSource(v) - } - if v, ok := m["glusterfs"].([]interface{}); ok && len(v) > 0 { - vl[i].Glusterfs = expandGlusterfsVolumeSource(v) - } - if v, ok := m["nfs"].([]interface{}); ok && len(v) > 0 { - vl[i].NFS = expandNFSVolumeSource(v) - } - if v, ok := m["rbd"].([]interface{}); ok && len(v) > 0 { - vl[i].RBD = expandRBDVolumeSource(v) - } - if v, ok := m["iscsi"].([]interface{}); ok && len(v) > 0 { - vl[i].ISCSI = expandISCSIVolumeSource(v) - } - if v, ok := m["cinder"].([]interface{}); ok && len(v) > 0 { - vl[i].Cinder = expandCinderVolumeSource(v) - } - if v, ok := m["ceph_fs"].([]interface{}); ok && len(v) > 0 { - vl[i].CephFS = expandCephFSVolumeSource(v) - } - if v, ok := m["fc"].([]interface{}); ok && len(v) > 0 { - vl[i].FC = expandFCVolumeSource(v) - } - if v, ok := m["flocker"].([]interface{}); ok && len(v) > 0 { - vl[i].Flocker = expandFlockerVolumeSource(v) - } - if v, ok := m["flex_volume"].([]interface{}); ok && len(v) > 0 { - vl[i].FlexVolume = expandFlexVolumeSource(v) - } - if v, ok := m["azure_file"].([]interface{}); ok && len(v) > 0 { - vl[i].AzureFile = expandAzureFileVolumeSource(v) - } - if v, ok := m["vsphere_volume"].([]interface{}); ok && len(v) > 0 { - vl[i].VsphereVolume = expandVsphereVirtualDiskVolumeSource(v) - } - if v, ok := m["quobyte"].([]interface{}); ok && len(v) > 0 { - vl[i].Quobyte = expandQuobyteVolumeSource(v) - } - if v, ok := m["azure_disk"].([]interface{}); ok && len(v) > 0 { - vl[i].AzureDisk = expandAzureDiskVolumeSource(v) - } - if v, ok := m["photon_persistent_disk"].([]interface{}); ok && len(v) > 0 { - vl[i].PhotonPersistentDisk = expandPhotonPersistentDiskVolumeSource(v) - } - } - return vl, nil -} - -func expandReadinessGates(gates []interface{}) ([]v1.PodReadinessGate, error) { - if len(gates) == 0 || gates[0] == nil { - return []v1.PodReadinessGate{}, nil - } - cs := make([]v1.PodReadinessGate, len(gates)) - for i, c := range gates { - gate := c.(map[string]interface{}) - - if v, ok := gate["condition_type"]; ok { - conType := v1.PodConditionType(v.(string)) - cs[i].ConditionType = conType - } - } - return cs, nil -} - -func patchPodSpec(pathPrefix, prefix string, d *schema.ResourceData) (PatchOperations, error) { - ops := make([]PatchOperation, 0) - - if d.HasChange(prefix + "active_deadline_seconds") { - v := d.Get(prefix + "active_deadline_seconds").(int) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/activeDeadlineSeconds", - Value: v, - }) - } - - if d.HasChange(prefix + "container") { - containers := d.Get(prefix + "container").([]interface{}) - value, _ := expandContainers(containers) - - for i, v := range value { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/containers/" + strconv.Itoa(i) + "/image", - Value: v.Image, - }) - - } - - } - return ops, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_rbac.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_rbac.go deleted file mode 100644 index e9cd2d5e95a..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_rbac.go +++ /dev/null @@ -1,234 +0,0 @@ -package kubernetes - -import ( - "strconv" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - api "k8s.io/api/rbac/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func expandRBACRoleRef(in []interface{}) api.RoleRef { - if len(in) == 0 || in[0] == nil { - return api.RoleRef{} - } - ref := api.RoleRef{} - m := in[0].(map[string]interface{}) - if v, ok := m["api_group"]; ok { - ref.APIGroup = v.(string) - } - if v, ok := m["kind"].(string); ok { - ref.Kind = string(v) - } - if v, ok := m["name"]; ok { - ref.Name = v.(string) - } - - return ref -} - -func expandRBACSubjects(in []interface{}) []api.Subject { - if len(in) == 0 || in[0] == nil { - return []api.Subject{} - } - subjects := make([]api.Subject, 0, len(in)) - for i := range in { - subject := api.Subject{} - m := in[i].(map[string]interface{}) - if v, ok := m["api_group"]; ok { - subject.APIGroup = v.(string) - } - if v, ok := m["kind"].(string); ok { - subject.Kind = string(v) - } - if v, ok := m["name"]; ok { - subject.Name = v.(string) - } - if v, ok := m["namespace"]; ok { - subject.Namespace = v.(string) - } - subjects = append(subjects, subject) - } - return subjects -} - -func expandClusterRoleRules(in []interface{}) []api.PolicyRule { - if len(in) == 0 { - return []api.PolicyRule{} - } - rules := make([]api.PolicyRule, len(in)) - for i, rule := range in { - r := api.PolicyRule{} - ruleCfg := rule.(map[string]interface{}) - if v, ok := ruleCfg["api_groups"]; ok { - r.APIGroups = expandStringSlice(v.([]interface{})) - } - if v, ok := ruleCfg["non_resource_urls"]; ok { - r.NonResourceURLs = expandStringSlice(v.([]interface{})) - } - if v, ok := ruleCfg["resource_names"]; ok { - r.ResourceNames = expandStringSlice(v.([]interface{})) - } - if v, ok := ruleCfg["resources"]; ok { - r.Resources = expandStringSlice(v.([]interface{})) - } - if v, ok := ruleCfg["verbs"]; ok { - r.Verbs = expandStringSlice(v.([]interface{})) - } - rules[i] = r - } - return rules -} - -func expandClusterRoleAggregationRule(in []interface{}) *api.AggregationRule { - if len(in) == 0 || in[0] == nil { - return &api.AggregationRule{} - } - ref := &api.AggregationRule{} - m := in[0].(map[string]interface{}) - - if v, ok := m["cluster_role_selectors"].([]interface{}); ok && len(v) > 0 { - crs := make([]metav1.LabelSelector, 0) - crs = append(crs, *expandLabelSelector(v)) - ref.ClusterRoleSelectors = crs - } - - return ref -} - -func flattenRBACRoleRef(in api.RoleRef) []interface{} { - att := make(map[string]interface{}) - - if in.APIGroup != "" { - att["api_group"] = in.APIGroup - } - att["kind"] = in.Kind - att["name"] = in.Name - return []interface{}{att} -} - -func flattenRBACSubjects(in []api.Subject) []interface{} { - att := make([]interface{}, 0, len(in)) - for _, n := range in { - m := make(map[string]interface{}) - if n.APIGroup != "" { - m["api_group"] = n.APIGroup - } - m["kind"] = n.Kind - m["name"] = n.Name - if n.Namespace != "" { - m["namespace"] = n.Namespace - } - att = append(att, m) - } - return att -} - -func flattenClusterRoleRules(in []api.PolicyRule) []interface{} { - att := make([]interface{}, len(in), len(in)) - for i, n := range in { - m := make(map[string]interface{}) - m["api_groups"] = n.APIGroups - m["non_resource_urls"] = n.NonResourceURLs - m["resource_names"] = n.ResourceNames - m["resources"] = n.Resources - m["verbs"] = n.Verbs - att[i] = m - } - return att -} - -func flattenClusterRoleAggregationRule(in *api.AggregationRule) []interface{} { - att := make(map[string]interface{}) - - if len(in.ClusterRoleSelectors) > 0 { - for _, crs := range in.ClusterRoleSelectors { - att["cluster_role_selectors"] = flattenLabelSelector(&crs) - } - } - - return []interface{}{att} -} - -// Patch Ops -func patchRbacSubject(d *schema.ResourceData) PatchOperations { - o, n := d.GetChange("subject") - oldsubjects := expandRBACSubjects(o.([]interface{})) - newsubjects := expandRBACSubjects(n.([]interface{})) - ops := make([]PatchOperation, 0, len(newsubjects)+len(oldsubjects)) - - common := len(newsubjects) - if common > len(oldsubjects) { - common = len(oldsubjects) - } - if len(oldsubjects) > len(newsubjects) { - for i := len(newsubjects); i < len(oldsubjects); i++ { - ops = append(ops, &RemoveOperation{ - Path: "/subjects/" + strconv.Itoa(len(oldsubjects)-i), - }) - } - } - for i, v := range newsubjects[:common] { - ops = append(ops, &ReplaceOperation{ - Path: "/subjects/" + strconv.Itoa(i), - Value: v, - }) - } - if len(newsubjects) > len(oldsubjects) { - for i, v := range newsubjects[common:] { - ops = append(ops, &AddOperation{ - Path: "/subjects/" + strconv.Itoa(common+i), - Value: v, - }) - } - } - return ops -} - -func patchRbacRule(d *schema.ResourceData) PatchOperations { - o, n := d.GetChange("rule") - oldrules := expandClusterRoleRules(o.([]interface{})) - newrules := expandClusterRoleRules(n.([]interface{})) - ops := make([]PatchOperation, 0, len(newrules)+len(oldrules)) - - common := len(newrules) - if common > len(oldrules) { - common = len(oldrules) - } - if len(oldrules) > len(newrules) { - for i := len(newrules); i < len(oldrules); i++ { - ops = append(ops, &RemoveOperation{ - Path: "/rules/" + strconv.Itoa(len(oldrules)-i), - }) - } - } - for i, v := range newrules[:common] { - ops = append(ops, &ReplaceOperation{ - Path: "/rules/" + strconv.Itoa(i), - Value: v, - }) - } - if len(newrules) > len(oldrules) { - for i, v := range newrules[common:] { - ops = append(ops, &AddOperation{ - Path: "/rules/" + strconv.Itoa(common+i), - Value: v, - }) - } - } - return ops -} - -func patchRbacAggregationRule(d *schema.ResourceData) PatchOperations { - _, n := d.GetChange("aggregation_rule") - //oldrules := expandClusterRoleRules(o.([]interface{})) - newAggRule := expandClusterRoleAggregationRule(n.([]interface{})) - ops := make([]PatchOperation, 0) - - ops = append(ops, &ReplaceOperation{ - Path: "/aggregationRule", - Value: newAggRule, - }) - - return ops -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_replication_controller.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_replication_controller.go deleted file mode 100644 index 8888cf3f908..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_replication_controller.go +++ /dev/null @@ -1,101 +0,0 @@ -package kubernetes - -import ( - "errors" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "k8s.io/api/core/v1" -) - -func flattenReplicationControllerSpec(in v1.ReplicationControllerSpec, d *schema.ResourceData, useDeprecatedSpecFields bool) ([]interface{}, error) { - att := make(map[string]interface{}) - att["min_ready_seconds"] = in.MinReadySeconds - - if in.Replicas != nil { - att["replicas"] = *in.Replicas - } - - if in.Selector != nil { - att["selector"] = in.Selector - } - - if in.Template != nil { - podSpec, err := flattenPodSpec(in.Template.Spec) - if err != nil { - return nil, err - } - template := make(map[string]interface{}) - - if useDeprecatedSpecFields { - // Use deprecated fields - for k, v := range podSpec[0].(map[string]interface{}) { - template[k] = v - } - } else { - // Use new fields - template["spec"] = podSpec - template["metadata"] = flattenMetadata(in.Template.ObjectMeta, d) - } - - att["template"] = []interface{}{template} - } - - return []interface{}{att}, nil -} - -func expandReplicationControllerSpec(rc []interface{}, useDeprecatedSpecFields bool) (*v1.ReplicationControllerSpec, error) { - obj := &v1.ReplicationControllerSpec{} - if len(rc) == 0 || rc[0] == nil { - return obj, nil - } - in := rc[0].(map[string]interface{}) - obj.MinReadySeconds = int32(in["min_ready_seconds"].(int)) - obj.Replicas = ptrToInt32(int32(in["replicas"].(int))) - obj.Selector = expandStringMap(in["selector"].(map[string]interface{})) - - template, err := expandReplicationControllerTemplate(in["template"].([]interface{}), obj.Selector, useDeprecatedSpecFields) - if err != nil { - return obj, err - } - - obj.Template = template - - return obj, nil -} - -func expandReplicationControllerTemplate(rct []interface{}, selector map[string]string, useDeprecatedSpecFields bool) (*v1.PodTemplateSpec, error) { - obj := &v1.PodTemplateSpec{} - - if useDeprecatedSpecFields { - // Add labels from selector to ensure proper selection of pods by the replication controller for deprecated use case - obj.ObjectMeta.Labels = selector - - // Get pod spec from deprecated fields - podSpecDeprecated, err := expandPodSpec(rct) - if err != nil { - return obj, err - } - obj.Spec = *podSpecDeprecated - } else { - in := rct[0].(map[string]interface{}) - metadata := in["metadata"].([]interface{}) - - // Return an error if new spec fields are used but no metadata is defined to preserve the Required property of the metadata field - // cf. https://www.terraform.io/docs/extend/best-practices/deprecations.html#renaming-a-required-attribute - if len(metadata) < 1 { - return obj, errors.New("`spec.template.metadata` is Required when new 'spec.template.spec' fields are used.") - } - - // Get user defined metadata - obj.ObjectMeta = expandMetadata(metadata) - - // Get pod spec from new fields - podSpec, err := expandPodSpec(in["spec"].([]interface{})) - if err != nil { - return obj, err - } - obj.Spec = *podSpec - } - - return obj, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_stateful_set.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_stateful_set.go deleted file mode 100644 index 0b2ba3459f5..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/structures_stateful_set.go +++ /dev/null @@ -1,335 +0,0 @@ -package kubernetes - -import ( - "errors" - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - v1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// Expanders - -func expandStatefulSetSpec(s []interface{}) (*v1.StatefulSetSpec, error) { - obj := &v1.StatefulSetSpec{} - if len(s) == 0 || s[0] == nil { - return obj, nil - } - in := s[0].(map[string]interface{}) - - if v, ok := in["pod_management_policy"].(string); ok { - obj.PodManagementPolicy = v1.PodManagementPolicyType(v) - } - - if v, ok := in["replicas"].(int); ok && v >= 0 { - obj.Replicas = ptrToInt32(int32(v)) - } - - if v, ok := in["revision_history_limit"].(int); ok { - obj.RevisionHistoryLimit = ptrToInt32(int32(v)) - } - - if v, ok := in["selector"].([]interface{}); ok && len(v) > 0 { - obj.Selector = expandLabelSelector(v) - } - - if v, ok := in["service_name"].(string); ok { - obj.ServiceName = v - } - - if v, ok := in["update_strategy"].([]interface{}); ok { - us, err := expandStatefulSetSpecUpdateStrategy(v) - if err != nil { - return obj, err - } - obj.UpdateStrategy = *us - } - - template, err := expandPodTemplate(in["template"].([]interface{})) - if err != nil { - return obj, err - } - obj.Template = *template - - if v, ok := in["volume_claim_template"].([]interface{}); ok { - obj.VolumeClaimTemplates = []corev1.PersistentVolumeClaim{} - if len(v) == 0 || v[0] == nil { - return obj, nil - } - for _, pvc := range v { - p, err := expandPersistentVolumeClaim(pvc.(map[string]interface{})) - if err != nil { - return obj, err - } - obj.VolumeClaimTemplates = append(obj.VolumeClaimTemplates, *p) - } - } - return obj, nil -} -func expandStatefulSetSpecUpdateStrategy(s []interface{}) (*v1.StatefulSetUpdateStrategy, error) { - ust := &v1.StatefulSetUpdateStrategy{} - if len(s) == 0 { - return ust, nil - } - us, ok := s[0].(map[string]interface{}) - if !ok { - return ust, errors.New("failed to expand 'spec.update_strategy'") - } - t, ok := us["type"].(string) - if !ok { - return ust, errors.New("failed to expand 'spec.update_strategy.type'") - } - ust.Type = v1.StatefulSetUpdateStrategyType(t) - ru, ok := us["rolling_update"].([]interface{}) - if !ok { - return ust, errors.New("failed to unroll 'spec.update_strategy.rolling_update'") - } - if len(ru) > 0 { - u := v1.RollingUpdateStatefulSetStrategy{} - r, ok := ru[0].(map[string]interface{}) - if !ok { - return ust, errors.New("failed to expand 'spec.update_strategy.rolling_update'") - } - p, ok := r["partition"].(int) - if !ok { - return ust, errors.New("failed to expand 'spec.update_strategy.rolling_update.partition'") - } - u.Partition = ptrToInt32(int32(p)) - ust.RollingUpdate = &u - } - log.Printf("[DEBUG] Expanded StatefulSet.Spec.UpdateStrategy: %#v", ust) - return ust, nil -} - -func expandStatefulSetSelectors(s []interface{}) (*metav1.LabelSelector, error) { - obj := &metav1.LabelSelector{} - if len(s) == 0 || s[0] == nil { - return obj, nil - } - in := s[0].(map[string]interface{}) - log.Printf("[DEBUG] StatefulSet Selector: %#v", in) - if v, ok := in["match_labels"].(map[string]interface{}); ok { - log.Printf("[DEBUG] StatefulSet Selector MatchLabels: %#v", v) - ml := make(map[string]string) - for k, l := range v { - ml[k] = l.(string) - log.Printf("[DEBUG] StatefulSet Selector MatchLabel: %#v -> %#v", k, v) - } - obj.MatchLabels = ml - } - if v, ok := in["match_expressions"].([]interface{}); ok { - log.Printf("[DEBUG] StatefulSet Selector MatchExpressions: %#v", v) - me, err := expandMatchExpressions(v) - if err != nil { - return obj, err - } - obj.MatchExpressions = me - } - return obj, nil -} - -func expandMatchExpressions(in []interface{}) ([]metav1.LabelSelectorRequirement, error) { - if len(in) == 0 { - return []metav1.LabelSelectorRequirement{}, nil - } - obj := make([]metav1.LabelSelectorRequirement, len(in)) - for i, c := range in { - p := c.(map[string]interface{}) - if v, ok := p["key"].(string); ok { - obj[i].Key = v - } - if v, ok := p["operator"].(metav1.LabelSelectorOperator); ok { - obj[i].Operator = v - } - if v, ok := p["values"].(*schema.Set); ok { - obj[i].Values = schemaSetToStringArray(v) - } - } - return obj, nil -} - -// Flattners - -func flattenStatefulSetSpec(spec v1.StatefulSetSpec, d *schema.ResourceData) ([]interface{}, error) { - att := make(map[string]interface{}) - - if spec.PodManagementPolicy != "" { - att["pod_management_policy"] = spec.PodManagementPolicy - } - if spec.Replicas != nil { - att["replicas"] = *spec.Replicas - } - if spec.RevisionHistoryLimit != nil { - att["revision_history_limit"] = *spec.RevisionHistoryLimit - } - if spec.Selector != nil { - att["selector"] = flattenLabelSelector(spec.Selector) - } - if spec.ServiceName != "" { - att["service_name"] = spec.ServiceName - } - template, err := flattenPodTemplateSpec(spec.Template, d) - if err != nil { - return []interface{}{att}, err - } - att["template"] = template - att["volume_claim_template"] = flattenPersistentVolumeClaim(spec.VolumeClaimTemplates, d) - att["update_strategy"] = flattenStatefulSetSpecUpdateStrategy(spec.UpdateStrategy) - - return []interface{}{att}, nil -} - -func flattenPodTemplateSpec(t corev1.PodTemplateSpec, d *schema.ResourceData, prefix ...string) ([]interface{}, error) { - template := make(map[string]interface{}) - - metaPrefix := "spec.0.template.0." - if len(prefix) > 0 { - metaPrefix = prefix[0] - } - template["metadata"] = flattenMetadata(t.ObjectMeta, d, metaPrefix) - spec, err := flattenPodSpec(t.Spec) - if err != nil { - return []interface{}{template}, err - } - template["spec"] = spec - - return []interface{}{template}, nil -} - -func flattenPersistentVolumeClaim(in []corev1.PersistentVolumeClaim, d *schema.ResourceData) []interface{} { - pvcs := make([]interface{}, 0, len(in)) - - for i, pvc := range in { - p := make(map[string]interface{}) - p["metadata"] = flattenMetadata(pvc.ObjectMeta, d, fmt.Sprintf("spec.0.volume_claim_template.%d.", i)) - p["spec"] = flattenPersistentVolumeClaimSpec(pvc.Spec) - pvcs = append(pvcs, p) - } - return pvcs -} - -func flattenStatefulSetSpecUpdateStrategy(s v1.StatefulSetUpdateStrategy) []interface{} { - att := make(map[string]interface{}) - - att["type"] = s.Type - if s.RollingUpdate != nil { - ru := make(map[string]interface{}) - if s.RollingUpdate.Partition != nil { - ru["partition"] = *s.RollingUpdate.Partition - } - att["rolling_update"] = []interface{}{ru} - } - return []interface{}{att} -} - -// Patchers - -func patchStatefulSetSpec(d *schema.ResourceData) (PatchOperations, error) { - ops := PatchOperations{} - - if d.HasChange("spec.0.replicas") { - log.Printf("[TRACE] StatefulSet.Spec.Replicas has changes") - if v, ok := d.Get("spec.0.replicas").(int); ok { - ops = append(ops, &ReplaceOperation{ - Path: "/spec/replicas", - Value: v, - }) - } - } - - if d.HasChange("spec.0.template") { - log.Printf("[TRACE] StatefulSet.Spec.Template has changes") - template, err := expandPodTemplate(d.Get("spec.0.template").([]interface{})) - if err != nil { - return ops, err - } - ops = append(ops, &ReplaceOperation{ - Path: "/spec/template", - Value: template, - }) - } - - if d.HasChange("spec.0.update_strategy") { - log.Printf("[TRACE] StatefulSet.Spec.UpdateStrategy has changes") - u, err := patchUpdateStrategy("spec.0.update_strategy.0.", "/spec/updateStrategy/", d) - if err != nil { - return ops, err - } - ops = append(ops, u...) - } - return ops, nil -} - -func patchUpdateStrategy(keyPrefix, pathPrefix string, d *schema.ResourceData) (PatchOperations, error) { - ops := PatchOperations{} - - if d.HasChange(keyPrefix + "type") { - log.Printf("[TRACE] StatefulSet.Spec.UpdateStrategy.Type has changes") - oldV, newV := d.GetChange(keyPrefix + "type") - o := oldV.(string) - n := newV.(string) - if len(o) != 0 && len(n) == 0 { - return ops, fmt.Errorf("Spec.UpdateStrategy.Type cannot be empty") - } - if len(o) == 0 && len(n) != 0 { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "type", - Value: n, - }) - } else { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "type", - Value: n, - }) - } - } - - if d.HasChange(keyPrefix + "rolling_update") { - o, n := d.GetChange(keyPrefix + "rolling_update") - log.Printf("[TRACE] StatefulSet.Spec.UpdateStrategy.RollingUpdate has changes: %#v | %#v", o, n) - - if len(o.([]interface{})) > 0 && len(n.([]interface{})) == 0 { - ops = append(ops, &RemoveOperation{ - Path: pathPrefix + "rollingUpdate", - }) - } - - if len(o.([]interface{})) == 0 && len(n.([]interface{})) > 0 { - ops = append(ops, &AddOperation{ - Path: pathPrefix + "rollingUpdate", - Value: struct{}{}, - }) - ops = append(ops, &AddOperation{ - Path: pathPrefix + "rollingUpdate/partition", - Value: d.Get(keyPrefix + "rolling_update.0.partition").(int), - }) - } - - if len(o.([]interface{})) > 0 && len(n.([]interface{})) > 0 { - r, err := patchUpdateStrategyRollingUpdate(keyPrefix+"rolling_update.0.", pathPrefix+"rollingUpdate/", d) - if err != nil { - return ops, err - } - ops = append(ops, r...) - } - } - - return ops, nil -} - -func patchUpdateStrategyRollingUpdate(keyPrefix, pathPrefix string, d *schema.ResourceData) (PatchOperations, error) { - ops := PatchOperations{} - if d.HasChange(keyPrefix + "partition") { - log.Printf("[TRACE] StatefulSet.Spec.UpdateStrategy.RollingUpdate.Partition has changes") - if p, ok := d.Get(keyPrefix + "partition").(int); ok { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "partition", - Value: p, - }) - } - } - return ops, nil -} diff --git a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/validators.go b/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/validators.go deleted file mode 100644 index a48a3d3e4f0..00000000000 --- a/vendor/github.com/hashicorp/terraform-provider-kubernetes/kubernetes/validators.go +++ /dev/null @@ -1,292 +0,0 @@ -package kubernetes - -import ( - "encoding/base64" - "fmt" - "strconv" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "k8s.io/apimachinery/pkg/api/resource" - apiValidation "k8s.io/apimachinery/pkg/api/validation" - utilValidation "k8s.io/apimachinery/pkg/util/validation" -) - -func validateAnnotations(value interface{}, key string) (ws []string, es []error) { - m := value.(map[string]interface{}) - for k := range m { - errors := utilValidation.IsQualifiedName(strings.ToLower(k)) - if len(errors) > 0 { - for _, e := range errors { - es = append(es, fmt.Errorf("%s (%q) %s", key, k, e)) - } - } - } - return -} - -func validateBase64Encoded(v interface{}, key string) (ws []string, es []error) { - s, ok := v.(string) - if !ok { - es = []error{fmt.Errorf("%s: must be a non-nil base64-encoded string", key)} - return - } - - _, err := base64.StdEncoding.DecodeString(s) - if err != nil { - es = []error{fmt.Errorf("%s: must be a base64-encoded string", key)} - return - } - return -} - -func validateBase64EncodedMap(value interface{}, key string) (ws []string, es []error) { - m, ok := value.(map[string]interface{}) - if !ok { - es = []error{fmt.Errorf("%s: must be a map of strings to base64 encoded strings", key)} - return - } - - for k, v := range m { - _, errs := validateBase64Encoded(v, k) - for _, e := range errs { - es = append(es, fmt.Errorf("%s (%q) %s", k, v, e)) - } - } - - return -} - -func validateName(value interface{}, key string) (ws []string, es []error) { - v := value.(string) - errors := apiValidation.NameIsDNSSubdomain(v, false) - if len(errors) > 0 { - for _, err := range errors { - es = append(es, fmt.Errorf("%s %s", key, err)) - } - } - return -} - -func validateGenerateName(value interface{}, key string) (ws []string, es []error) { - v := value.(string) - - errors := apiValidation.NameIsDNSLabel(v, true) - if len(errors) > 0 { - for _, err := range errors { - es = append(es, fmt.Errorf("%s %s", key, err)) - } - } - return -} - -func validateLabels(value interface{}, key string) (ws []string, es []error) { - m := value.(map[string]interface{}) - for k, v := range m { - for _, msg := range utilValidation.IsQualifiedName(k) { - es = append(es, fmt.Errorf("%s (%q) %s", key, k, msg)) - } - val, isString := v.(string) - if !isString { - es = append(es, fmt.Errorf("%s.%s (%#v): Expected value to be string", key, k, v)) - return - } - for _, msg := range utilValidation.IsValidLabelValue(val) { - es = append(es, fmt.Errorf("%s (%q) %s", key, val, msg)) - } - } - return -} - -func validatePortNum(value interface{}, key string) (ws []string, es []error) { - errors := utilValidation.IsValidPortNum(value.(int)) - if len(errors) > 0 { - for _, err := range errors { - es = append(es, fmt.Errorf("%s %s", key, err)) - } - } - return -} - -func validatePortName(value interface{}, key string) (ws []string, es []error) { - errors := utilValidation.IsValidPortName(value.(string)) - if len(errors) > 0 { - for _, err := range errors { - es = append(es, fmt.Errorf("%s %s", key, err)) - } - } - return -} -func validatePortNumOrName(value interface{}, key string) (ws []string, es []error) { - switch value.(type) { - case string: - intVal, err := strconv.Atoi(value.(string)) - if err != nil { - return validatePortName(value, key) - } - return validatePortNum(intVal, key) - case int: - return validatePortNum(value, key) - - default: - es = append(es, fmt.Errorf("%s must be defined of type string or int on the schema", key)) - return - } -} - -func validateResourceList(value interface{}, key string) (ws []string, es []error) { - m := value.(map[string]interface{}) - for k, value := range m { - if _, ok := value.(int); ok { - continue - } - - if v, ok := value.(string); ok { - _, err := resource.ParseQuantity(v) - if err != nil { - es = append(es, fmt.Errorf("%s.%s (%q): %s", key, k, v, err)) - } - continue - } - - err := "Value can be either string or int" - es = append(es, fmt.Errorf("%s.%s (%#v): %s", key, k, value, err)) - } - return -} - -func validateResourceQuantity(value interface{}, key string) (ws []string, es []error) { - if v, ok := value.(string); ok { - _, err := resource.ParseQuantity(v) - if err != nil { - es = append(es, fmt.Errorf("%s.%s : %s", key, v, err)) - } - } - return -} - -func validateNonNegativeInteger(value interface{}, key string) (ws []string, es []error) { - v := value.(int) - if v < 0 { - es = append(es, fmt.Errorf("%s must be greater than or equal to 0", key)) - } - return -} - -func validatePositiveInteger(value interface{}, key string) (ws []string, es []error) { - v := value.(int) - if v <= 0 { - es = append(es, fmt.Errorf("%s must be greater than 0", key)) - } - return -} - -func validateTerminationGracePeriodSeconds(value interface{}, key string) (ws []string, es []error) { - v := value.(int) - if v < 0 { - es = append(es, fmt.Errorf("%s must be greater than or equal to 0", key)) - } - return -} - -func validateIntGreaterThan(minValue int) func(value interface{}, key string) (ws []string, es []error) { - return func(value interface{}, key string) (ws []string, es []error) { - v := value.(int) - if v < minValue { - es = append(es, fmt.Errorf("%s must be greater than or equal to %d", key, minValue)) - } - return - } -} - -// validateTypeStringNullableInt provides custom error messaging for TypeString ints -// Some arguments require an int value or unspecified, empty field. -func validateTypeStringNullableInt(v interface{}, k string) (ws []string, es []error) { - value, ok := v.(string) - if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) - return - } - - if value == "" { - return - } - - if _, err := strconv.ParseInt(value, 10, 64); err != nil { - es = append(es, fmt.Errorf("%s: cannot parse '%s' as int: %s", k, value, err)) - } - - return -} - -func validateModeBits(value interface{}, key string) (ws []string, es []error) { - if !strings.HasPrefix(value.(string), "0") { - es = append(es, fmt.Errorf("%s: value %s should start with '0' (octal numeral)", key, value.(string))) - } - v, err := strconv.ParseInt(value.(string), 8, 32) - if err != nil { - es = append(es, fmt.Errorf("%s :Cannot parse octal numeral (%#v): %s", key, value, err)) - } - if v < 0 || v > 0777 { - es = append(es, fmt.Errorf("%s (%#o) expects octal notation (a value between 0 and 0777)", key, v)) - } - return -} - -func validateAttributeValueDoesNotContain(searchString string) schema.SchemaValidateFunc { - return func(v interface{}, k string) (ws []string, errors []error) { - input := v.(string) - if strings.Contains(input, searchString) { - errors = append(errors, fmt.Errorf( - "%q must not contain %q", - k, searchString)) - } - return - } -} - -func validateAttributeValueIsIn(validValues []string) schema.SchemaValidateFunc { - return func(v interface{}, k string) (ws []string, errors []error) { - input := v.(string) - isValid := false - for _, s := range validValues { - if s == input { - isValid = true - break - } - } - if !isValid { - errors = append(errors, fmt.Errorf( - "%q must contain a value from %#v, got %q", - k, validValues, input)) - } - return - - } -} - -func validateTypeStringNullableIntOrPercent(v interface{}, key string) (ws []string, es []error) { - value, ok := v.(string) - if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", key)) - return - } - - if value == "" { - return - } - - if strings.HasSuffix(value, "%") { - percent, err := strconv.ParseInt(strings.TrimSuffix(value, "%"), 10, 32) - if err != nil { - es = append(es, fmt.Errorf("%s: cannot parse '%s' as percent: %s", key, value, err)) - } - if percent < 0 || percent >= 100 { - es = append(es, fmt.Errorf("%s: '%s' is not between 0%% and 100%%", key, value)) - } - } else if _, err := strconv.ParseInt(value, 10, 32); err != nil { - es = append(es, fmt.Errorf("%s: cannot parse '%s' as int or percent: %s", key, value, err)) - } - - return -} diff --git a/vendor/github.com/imdario/mergo/.travis.yml b/vendor/github.com/imdario/mergo/.travis.yml index dad29725f86..d324c43ba4d 100644 --- a/vendor/github.com/imdario/mergo/.travis.yml +++ b/vendor/github.com/imdario/mergo/.travis.yml @@ -1,4 +1,7 @@ language: go +arch: + - amd64 + - ppc64le install: - go get -t - go get golang.org/x/tools/cmd/cover diff --git a/vendor/github.com/imdario/mergo/README.md b/vendor/github.com/imdario/mergo/README.md index 876abb500a4..aa8cbd7ce6d 100644 --- a/vendor/github.com/imdario/mergo/README.md +++ b/vendor/github.com/imdario/mergo/README.md @@ -97,7 +97,7 @@ If Mergo is useful to you, consider buying me a coffee, a beer, or making a mont - [mantasmatelis/whooplist-server](https://github.com/mantasmatelis/whooplist-server) - [jnuthong/item_search](https://github.com/jnuthong/item_search) - [bukalapak/snowboard](https://github.com/bukalapak/snowboard) -- [janoszen/containerssh](https://github.com/janoszen/containerssh) +- [containerssh/containerssh](https://github.com/containerssh/containerssh) ## Install diff --git a/vendor/github.com/imdario/mergo/merge.go b/vendor/github.com/imdario/mergo/merge.go index afa84a1e298..8c2a8fcd901 100644 --- a/vendor/github.com/imdario/mergo/merge.go +++ b/vendor/github.com/imdario/mergo/merge.go @@ -95,13 +95,18 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co } } } else { - if (isReflectNil(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc) { + if dst.CanSet() && (isReflectNil(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc) { dst.Set(src) } } case reflect.Map: if dst.IsNil() && !src.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) + if dst.CanSet() { + dst.Set(reflect.MakeMap(dst.Type())) + } else { + dst = src + return + } } if src.Kind() != reflect.Map { diff --git a/vendor/github.com/jinzhu/copier/Guardfile b/vendor/github.com/jinzhu/copier/Guardfile deleted file mode 100644 index 0b860b0653c..00000000000 --- a/vendor/github.com/jinzhu/copier/Guardfile +++ /dev/null @@ -1,3 +0,0 @@ -guard 'gotest' do - watch(%r{\.go$}) -end diff --git a/vendor/github.com/jinzhu/copier/License b/vendor/github.com/jinzhu/copier/License deleted file mode 100644 index e2dc5381e17..00000000000 --- a/vendor/github.com/jinzhu/copier/License +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jinzhu - -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/jinzhu/copier/README.md b/vendor/github.com/jinzhu/copier/README.md deleted file mode 100644 index f929b467938..00000000000 --- a/vendor/github.com/jinzhu/copier/README.md +++ /dev/null @@ -1,100 +0,0 @@ -# Copier - - I am a copier, I copy everything from one to another - -[![wercker status](https://app.wercker.com/status/9d44ad2d4e6253929c8fb71359effc0b/s/master "wercker status")](https://app.wercker.com/project/byKey/9d44ad2d4e6253929c8fb71359effc0b) - -## Features - -* Copy from field to field with same name -* Copy from method to field with same name -* Copy from field to method with same name -* Copy from slice to slice -* Copy from struct to slice - -## Usage - -```go -package main - -import ( - "fmt" - "github.com/jinzhu/copier" -) - -type User struct { - Name string - Role string - Age int32 -} - -func (user *User) DoubleAge() int32 { - return 2 * user.Age -} - -type Employee struct { - Name string - Age int32 - DoubleAge int32 - EmployeId int64 - SuperRule string -} - -func (employee *Employee) Role(role string) { - employee.SuperRule = "Super " + role -} - -func main() { - var ( - user = User{Name: "Jinzhu", Age: 18, Role: "Admin"} - users = []User{{Name: "Jinzhu", Age: 18, Role: "Admin"}, {Name: "jinzhu 2", Age: 30, Role: "Dev"}} - employee = Employee{} - employees = []Employee{} - ) - - copier.Copy(&employee, &user) - - fmt.Printf("%#v \n", employee) - // Employee{ - // Name: "Jinzhu", // Copy from field - // Age: 18, // Copy from field - // DoubleAge: 36, // Copy from method - // EmployeeId: 0, // Ignored - // SuperRule: "Super Admin", // Copy to method - // } - - // Copy struct to slice - copier.Copy(&employees, &user) - - fmt.Printf("%#v \n", employees) - // []Employee{ - // {Name: "Jinzhu", Age: 18, DoubleAge: 36, EmployeId: 0, SuperRule: "Super Admin"} - // } - - // Copy slice to slice - employees = []Employee{} - copier.Copy(&employees, &users) - - fmt.Printf("%#v \n", employees) - // []Employee{ - // {Name: "Jinzhu", Age: 18, DoubleAge: 36, EmployeId: 0, SuperRule: "Super Admin"}, - // {Name: "jinzhu 2", Age: 30, DoubleAge: 60, EmployeId: 0, SuperRule: "Super Dev"}, - // } -} -``` - -## Contributing - -You can help to make the project better, check out [http://gorm.io/contribute.html](http://gorm.io/contribute.html) for things you can do. - -# Author - -**jinzhu** - -* -* -* - -## License - -Released under the [MIT License](https://github.com/jinzhu/copier/blob/master/License). diff --git a/vendor/github.com/jinzhu/copier/copier.go b/vendor/github.com/jinzhu/copier/copier.go deleted file mode 100644 index 3f339becc2a..00000000000 --- a/vendor/github.com/jinzhu/copier/copier.go +++ /dev/null @@ -1,189 +0,0 @@ -package copier - -import ( - "database/sql" - "errors" - "reflect" -) - -// Copy copy things -func Copy(toValue interface{}, fromValue interface{}) (err error) { - var ( - isSlice bool - amount = 1 - from = indirect(reflect.ValueOf(fromValue)) - to = indirect(reflect.ValueOf(toValue)) - ) - - if !to.CanAddr() { - return errors.New("copy to value is unaddressable") - } - - // Return is from value is invalid - if !from.IsValid() { - return - } - - fromType := indirectType(from.Type()) - toType := indirectType(to.Type()) - - // Just set it if possible to assign - // And need to do copy anyway if the type is struct - if fromType.Kind() != reflect.Struct && from.Type().AssignableTo(to.Type()) { - to.Set(from) - return - } - - if fromType.Kind() != reflect.Struct || toType.Kind() != reflect.Struct { - return - } - - if to.Kind() == reflect.Slice { - isSlice = true - if from.Kind() == reflect.Slice { - amount = from.Len() - } - } - - for i := 0; i < amount; i++ { - var dest, source reflect.Value - - if isSlice { - // source - if from.Kind() == reflect.Slice { - source = indirect(from.Index(i)) - } else { - source = indirect(from) - } - // dest - dest = indirect(reflect.New(toType).Elem()) - } else { - source = indirect(from) - dest = indirect(to) - } - - // check source - if source.IsValid() { - fromTypeFields := deepFields(fromType) - //fmt.Printf("%#v", fromTypeFields) - // Copy from field to field or method - for _, field := range fromTypeFields { - name := field.Name - - if fromField := source.FieldByName(name); fromField.IsValid() { - // has field - if toField := dest.FieldByName(name); toField.IsValid() { - if toField.CanSet() { - if !set(toField, fromField) { - if err := Copy(toField.Addr().Interface(), fromField.Interface()); err != nil { - return err - } - } - } - } else { - // try to set to method - var toMethod reflect.Value - if dest.CanAddr() { - toMethod = dest.Addr().MethodByName(name) - } else { - toMethod = dest.MethodByName(name) - } - - if toMethod.IsValid() && toMethod.Type().NumIn() == 1 && fromField.Type().AssignableTo(toMethod.Type().In(0)) { - toMethod.Call([]reflect.Value{fromField}) - } - } - } - } - - // Copy from method to field - for _, field := range deepFields(toType) { - name := field.Name - - var fromMethod reflect.Value - if source.CanAddr() { - fromMethod = source.Addr().MethodByName(name) - } else { - fromMethod = source.MethodByName(name) - } - - if fromMethod.IsValid() && fromMethod.Type().NumIn() == 0 && fromMethod.Type().NumOut() == 1 { - if toField := dest.FieldByName(name); toField.IsValid() && toField.CanSet() { - values := fromMethod.Call([]reflect.Value{}) - if len(values) >= 1 { - set(toField, values[0]) - } - } - } - } - } - if isSlice { - if dest.Addr().Type().AssignableTo(to.Type().Elem()) { - to.Set(reflect.Append(to, dest.Addr())) - } else if dest.Type().AssignableTo(to.Type().Elem()) { - to.Set(reflect.Append(to, dest)) - } - } - } - return -} - -func deepFields(reflectType reflect.Type) []reflect.StructField { - var fields []reflect.StructField - - if reflectType = indirectType(reflectType); reflectType.Kind() == reflect.Struct { - for i := 0; i < reflectType.NumField(); i++ { - v := reflectType.Field(i) - if v.Anonymous { - fields = append(fields, deepFields(v.Type)...) - } else { - fields = append(fields, v) - } - } - } - - return fields -} - -func indirect(reflectValue reflect.Value) reflect.Value { - for reflectValue.Kind() == reflect.Ptr { - reflectValue = reflectValue.Elem() - } - return reflectValue -} - -func indirectType(reflectType reflect.Type) reflect.Type { - for reflectType.Kind() == reflect.Ptr || reflectType.Kind() == reflect.Slice { - reflectType = reflectType.Elem() - } - return reflectType -} - -func set(to, from reflect.Value) bool { - if from.IsValid() { - if to.Kind() == reflect.Ptr { - //set `to` to nil if from is nil - if from.Kind() == reflect.Ptr && from.IsNil() { - to.Set(reflect.Zero(to.Type())) - return true - } else if to.IsNil() { - to.Set(reflect.New(to.Type().Elem())) - } - to = to.Elem() - } - - if from.Type().ConvertibleTo(to.Type()) { - to.Set(from.Convert(to.Type())) - } else if scanner, ok := to.Addr().Interface().(sql.Scanner); ok { - err := scanner.Scan(from.Interface()) - if err != nil { - return false - } - } else if from.Kind() == reflect.Ptr { - return set(to, from.Elem()) - } else { - return false - } - } - return true -} diff --git a/vendor/github.com/jinzhu/copier/wercker.yml b/vendor/github.com/jinzhu/copier/wercker.yml deleted file mode 100644 index 5e6ce981dc3..00000000000 --- a/vendor/github.com/jinzhu/copier/wercker.yml +++ /dev/null @@ -1,23 +0,0 @@ -box: golang - -build: - steps: - - setup-go-workspace - - # Gets the dependencies - - script: - name: go get - code: | - go get - - # Build the project - - script: - name: go build - code: | - go build ./... - - # Test the project - - script: - name: go test - code: | - go test ./... diff --git a/vendor/github.com/json-iterator/go/README.md b/vendor/github.com/json-iterator/go/README.md index 52b111d5f36..c589addf98c 100644 --- a/vendor/github.com/json-iterator/go/README.md +++ b/vendor/github.com/json-iterator/go/README.md @@ -8,8 +8,6 @@ A high-performance 100% compatible drop-in replacement of "encoding/json" -You can also use thrift like JSON using [thrift-iterator](https://github.com/thrift-iterator/go) - # Benchmark ![benchmark](http://jsoniter.com/benchmarks/go-benchmark.png) diff --git a/vendor/github.com/liggitt/tabwriter/.travis.yml b/vendor/github.com/liggitt/tabwriter/.travis.yml deleted file mode 100644 index 2768dc0727e..00000000000 --- a/vendor/github.com/liggitt/tabwriter/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: go - -go: - - "1.8" - - "1.9" - - "1.10" - - "1.11" - - "1.12" - - master - -script: go test -v ./... diff --git a/vendor/github.com/liggitt/tabwriter/README.md b/vendor/github.com/liggitt/tabwriter/README.md deleted file mode 100644 index e75d35672e9..00000000000 --- a/vendor/github.com/liggitt/tabwriter/README.md +++ /dev/null @@ -1,7 +0,0 @@ -This repo is a drop-in replacement for the golang [text/tabwriter](https://golang.org/pkg/text/tabwriter/) package. - -It is based on that package at [cf2c2ea8](https://github.com/golang/go/tree/cf2c2ea89d09d486bb018b1817c5874388038c3a/src/text/tabwriter) and inherits its license. - -The following additional features are supported: -* `RememberWidths` flag allows remembering maximum widths seen per column even after Flush() is called. -* `RememberedWidths() []int` and `SetRememberedWidths([]int) *Writer` allows obtaining and transferring remembered column width between writers. diff --git a/vendor/github.com/liggitt/tabwriter/tabwriter.go b/vendor/github.com/liggitt/tabwriter/tabwriter.go deleted file mode 100644 index fd3431fb03d..00000000000 --- a/vendor/github.com/liggitt/tabwriter/tabwriter.go +++ /dev/null @@ -1,637 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package tabwriter implements a write filter (tabwriter.Writer) that -// translates tabbed columns in input into properly aligned text. -// -// It is a drop-in replacement for the golang text/tabwriter package (https://golang.org/pkg/text/tabwriter), -// based on that package at https://github.com/golang/go/tree/cf2c2ea89d09d486bb018b1817c5874388038c3a -// with support for additional features. -// -// The package is using the Elastic Tabstops algorithm described at -// http://nickgravgaard.com/elastictabstops/index.html. -package tabwriter - -import ( - "io" - "unicode/utf8" -) - -// ---------------------------------------------------------------------------- -// Filter implementation - -// A cell represents a segment of text terminated by tabs or line breaks. -// The text itself is stored in a separate buffer; cell only describes the -// segment's size in bytes, its width in runes, and whether it's an htab -// ('\t') terminated cell. -// -type cell struct { - size int // cell size in bytes - width int // cell width in runes - htab bool // true if the cell is terminated by an htab ('\t') -} - -// A Writer is a filter that inserts padding around tab-delimited -// columns in its input to align them in the output. -// -// The Writer treats incoming bytes as UTF-8-encoded text consisting -// of cells terminated by horizontal ('\t') or vertical ('\v') tabs, -// and newline ('\n') or formfeed ('\f') characters; both newline and -// formfeed act as line breaks. -// -// Tab-terminated cells in contiguous lines constitute a column. The -// Writer inserts padding as needed to make all cells in a column have -// the same width, effectively aligning the columns. It assumes that -// all characters have the same width, except for tabs for which a -// tabwidth must be specified. Column cells must be tab-terminated, not -// tab-separated: non-tab terminated trailing text at the end of a line -// forms a cell but that cell is not part of an aligned column. -// For instance, in this example (where | stands for a horizontal tab): -// -// aaaa|bbb|d -// aa |b |dd -// a | -// aa |cccc|eee -// -// the b and c are in distinct columns (the b column is not contiguous -// all the way). The d and e are not in a column at all (there's no -// terminating tab, nor would the column be contiguous). -// -// The Writer assumes that all Unicode code points have the same width; -// this may not be true in some fonts or if the string contains combining -// characters. -// -// If DiscardEmptyColumns is set, empty columns that are terminated -// entirely by vertical (or "soft") tabs are discarded. Columns -// terminated by horizontal (or "hard") tabs are not affected by -// this flag. -// -// If a Writer is configured to filter HTML, HTML tags and entities -// are passed through. The widths of tags and entities are -// assumed to be zero (tags) and one (entities) for formatting purposes. -// -// A segment of text may be escaped by bracketing it with Escape -// characters. The tabwriter passes escaped text segments through -// unchanged. In particular, it does not interpret any tabs or line -// breaks within the segment. If the StripEscape flag is set, the -// Escape characters are stripped from the output; otherwise they -// are passed through as well. For the purpose of formatting, the -// width of the escaped text is always computed excluding the Escape -// characters. -// -// The formfeed character acts like a newline but it also terminates -// all columns in the current line (effectively calling Flush). Tab- -// terminated cells in the next line start new columns. Unless found -// inside an HTML tag or inside an escaped text segment, formfeed -// characters appear as newlines in the output. -// -// The Writer must buffer input internally, because proper spacing -// of one line may depend on the cells in future lines. Clients must -// call Flush when done calling Write. -// -type Writer struct { - // configuration - output io.Writer - minwidth int - tabwidth int - padding int - padbytes [8]byte - flags uint - - // current state - buf []byte // collected text excluding tabs or line breaks - pos int // buffer position up to which cell.width of incomplete cell has been computed - cell cell // current incomplete cell; cell.width is up to buf[pos] excluding ignored sections - endChar byte // terminating char of escaped sequence (Escape for escapes, '>', ';' for HTML tags/entities, or 0) - lines [][]cell // list of lines; each line is a list of cells - widths []int // list of column widths in runes - re-used during formatting - - maxwidths []int // list of max column widths in runes -} - -// addLine adds a new line. -// flushed is a hint indicating whether the underlying writer was just flushed. -// If so, the previous line is not likely to be a good indicator of the new line's cells. -func (b *Writer) addLine(flushed bool) { - // Grow slice instead of appending, - // as that gives us an opportunity - // to re-use an existing []cell. - if n := len(b.lines) + 1; n <= cap(b.lines) { - b.lines = b.lines[:n] - b.lines[n-1] = b.lines[n-1][:0] - } else { - b.lines = append(b.lines, nil) - } - - if !flushed { - // The previous line is probably a good indicator - // of how many cells the current line will have. - // If the current line's capacity is smaller than that, - // abandon it and make a new one. - if n := len(b.lines); n >= 2 { - if prev := len(b.lines[n-2]); prev > cap(b.lines[n-1]) { - b.lines[n-1] = make([]cell, 0, prev) - } - } - } -} - -// Reset the current state. -func (b *Writer) reset() { - b.buf = b.buf[:0] - b.pos = 0 - b.cell = cell{} - b.endChar = 0 - b.lines = b.lines[0:0] - b.widths = b.widths[0:0] - b.addLine(true) -} - -// Internal representation (current state): -// -// - all text written is appended to buf; tabs and line breaks are stripped away -// - at any given time there is a (possibly empty) incomplete cell at the end -// (the cell starts after a tab or line break) -// - cell.size is the number of bytes belonging to the cell so far -// - cell.width is text width in runes of that cell from the start of the cell to -// position pos; html tags and entities are excluded from this width if html -// filtering is enabled -// - the sizes and widths of processed text are kept in the lines list -// which contains a list of cells for each line -// - the widths list is a temporary list with current widths used during -// formatting; it is kept in Writer because it's re-used -// -// |<---------- size ---------->| -// | | -// |<- width ->|<- ignored ->| | -// | | | | -// [---processed---tab------------......] -// ^ ^ ^ -// | | | -// buf start of incomplete cell pos - -// Formatting can be controlled with these flags. -const ( - // Ignore html tags and treat entities (starting with '&' - // and ending in ';') as single characters (width = 1). - FilterHTML uint = 1 << iota - - // Strip Escape characters bracketing escaped text segments - // instead of passing them through unchanged with the text. - StripEscape - - // Force right-alignment of cell content. - // Default is left-alignment. - AlignRight - - // Handle empty columns as if they were not present in - // the input in the first place. - DiscardEmptyColumns - - // Always use tabs for indentation columns (i.e., padding of - // leading empty cells on the left) independent of padchar. - TabIndent - - // Print a vertical bar ('|') between columns (after formatting). - // Discarded columns appear as zero-width columns ("||"). - Debug - - // Remember maximum widths seen per column even after Flush() is called. - RememberWidths -) - -// A Writer must be initialized with a call to Init. The first parameter (output) -// specifies the filter output. The remaining parameters control the formatting: -// -// minwidth minimal cell width including any padding -// tabwidth width of tab characters (equivalent number of spaces) -// padding padding added to a cell before computing its width -// padchar ASCII char used for padding -// if padchar == '\t', the Writer will assume that the -// width of a '\t' in the formatted output is tabwidth, -// and cells are left-aligned independent of align_left -// (for correct-looking results, tabwidth must correspond -// to the tab width in the viewer displaying the result) -// flags formatting control -// -func (b *Writer) Init(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer { - if minwidth < 0 || tabwidth < 0 || padding < 0 { - panic("negative minwidth, tabwidth, or padding") - } - b.output = output - b.minwidth = minwidth - b.tabwidth = tabwidth - b.padding = padding - for i := range b.padbytes { - b.padbytes[i] = padchar - } - if padchar == '\t' { - // tab padding enforces left-alignment - flags &^= AlignRight - } - b.flags = flags - - b.reset() - - return b -} - -// debugging support (keep code around) -func (b *Writer) dump() { - pos := 0 - for i, line := range b.lines { - print("(", i, ") ") - for _, c := range line { - print("[", string(b.buf[pos:pos+c.size]), "]") - pos += c.size - } - print("\n") - } - print("\n") -} - -// local error wrapper so we can distinguish errors we want to return -// as errors from genuine panics (which we don't want to return as errors) -type osError struct { - err error -} - -func (b *Writer) write0(buf []byte) { - n, err := b.output.Write(buf) - if n != len(buf) && err == nil { - err = io.ErrShortWrite - } - if err != nil { - panic(osError{err}) - } -} - -func (b *Writer) writeN(src []byte, n int) { - for n > len(src) { - b.write0(src) - n -= len(src) - } - b.write0(src[0:n]) -} - -var ( - newline = []byte{'\n'} - tabs = []byte("\t\t\t\t\t\t\t\t") -) - -func (b *Writer) writePadding(textw, cellw int, useTabs bool) { - if b.padbytes[0] == '\t' || useTabs { - // padding is done with tabs - if b.tabwidth == 0 { - return // tabs have no width - can't do any padding - } - // make cellw the smallest multiple of b.tabwidth - cellw = (cellw + b.tabwidth - 1) / b.tabwidth * b.tabwidth - n := cellw - textw // amount of padding - if n < 0 { - panic("internal error") - } - b.writeN(tabs, (n+b.tabwidth-1)/b.tabwidth) - return - } - - // padding is done with non-tab characters - b.writeN(b.padbytes[0:], cellw-textw) -} - -var vbar = []byte{'|'} - -func (b *Writer) writeLines(pos0 int, line0, line1 int) (pos int) { - pos = pos0 - for i := line0; i < line1; i++ { - line := b.lines[i] - - // if TabIndent is set, use tabs to pad leading empty cells - useTabs := b.flags&TabIndent != 0 - - for j, c := range line { - if j > 0 && b.flags&Debug != 0 { - // indicate column break - b.write0(vbar) - } - - if c.size == 0 { - // empty cell - if j < len(b.widths) { - b.writePadding(c.width, b.widths[j], useTabs) - } - } else { - // non-empty cell - useTabs = false - if b.flags&AlignRight == 0 { // align left - b.write0(b.buf[pos : pos+c.size]) - pos += c.size - if j < len(b.widths) { - b.writePadding(c.width, b.widths[j], false) - } - } else { // align right - if j < len(b.widths) { - b.writePadding(c.width, b.widths[j], false) - } - b.write0(b.buf[pos : pos+c.size]) - pos += c.size - } - } - } - - if i+1 == len(b.lines) { - // last buffered line - we don't have a newline, so just write - // any outstanding buffered data - b.write0(b.buf[pos : pos+b.cell.size]) - pos += b.cell.size - } else { - // not the last line - write newline - b.write0(newline) - } - } - return -} - -// Format the text between line0 and line1 (excluding line1); pos -// is the buffer position corresponding to the beginning of line0. -// Returns the buffer position corresponding to the beginning of -// line1 and an error, if any. -// -func (b *Writer) format(pos0 int, line0, line1 int) (pos int) { - pos = pos0 - column := len(b.widths) - for this := line0; this < line1; this++ { - line := b.lines[this] - - if column >= len(line)-1 { - continue - } - // cell exists in this column => this line - // has more cells than the previous line - // (the last cell per line is ignored because cells are - // tab-terminated; the last cell per line describes the - // text before the newline/formfeed and does not belong - // to a column) - - // print unprinted lines until beginning of block - pos = b.writeLines(pos, line0, this) - line0 = this - - // column block begin - width := b.minwidth // minimal column width - discardable := true // true if all cells in this column are empty and "soft" - for ; this < line1; this++ { - line = b.lines[this] - if column >= len(line)-1 { - break - } - // cell exists in this column - c := line[column] - // update width - if w := c.width + b.padding; w > width { - width = w - } - // update discardable - if c.width > 0 || c.htab { - discardable = false - } - } - // column block end - - // discard empty columns if necessary - if discardable && b.flags&DiscardEmptyColumns != 0 { - width = 0 - } - - if b.flags&RememberWidths != 0 { - if len(b.maxwidths) < len(b.widths) { - b.maxwidths = append(b.maxwidths, b.widths[len(b.maxwidths):]...) - } - - switch { - case len(b.maxwidths) == len(b.widths): - b.maxwidths = append(b.maxwidths, width) - case b.maxwidths[len(b.widths)] > width: - width = b.maxwidths[len(b.widths)] - case b.maxwidths[len(b.widths)] < width: - b.maxwidths[len(b.widths)] = width - } - } - - // format and print all columns to the right of this column - // (we know the widths of this column and all columns to the left) - b.widths = append(b.widths, width) // push width - pos = b.format(pos, line0, this) - b.widths = b.widths[0 : len(b.widths)-1] // pop width - line0 = this - } - - // print unprinted lines until end - return b.writeLines(pos, line0, line1) -} - -// Append text to current cell. -func (b *Writer) append(text []byte) { - b.buf = append(b.buf, text...) - b.cell.size += len(text) -} - -// Update the cell width. -func (b *Writer) updateWidth() { - b.cell.width += utf8.RuneCount(b.buf[b.pos:]) - b.pos = len(b.buf) -} - -// To escape a text segment, bracket it with Escape characters. -// For instance, the tab in this string "Ignore this tab: \xff\t\xff" -// does not terminate a cell and constitutes a single character of -// width one for formatting purposes. -// -// The value 0xff was chosen because it cannot appear in a valid UTF-8 sequence. -// -const Escape = '\xff' - -// Start escaped mode. -func (b *Writer) startEscape(ch byte) { - switch ch { - case Escape: - b.endChar = Escape - case '<': - b.endChar = '>' - case '&': - b.endChar = ';' - } -} - -// Terminate escaped mode. If the escaped text was an HTML tag, its width -// is assumed to be zero for formatting purposes; if it was an HTML entity, -// its width is assumed to be one. In all other cases, the width is the -// unicode width of the text. -// -func (b *Writer) endEscape() { - switch b.endChar { - case Escape: - b.updateWidth() - if b.flags&StripEscape == 0 { - b.cell.width -= 2 // don't count the Escape chars - } - case '>': // tag of zero width - case ';': - b.cell.width++ // entity, count as one rune - } - b.pos = len(b.buf) - b.endChar = 0 -} - -// Terminate the current cell by adding it to the list of cells of the -// current line. Returns the number of cells in that line. -// -func (b *Writer) terminateCell(htab bool) int { - b.cell.htab = htab - line := &b.lines[len(b.lines)-1] - *line = append(*line, b.cell) - b.cell = cell{} - return len(*line) -} - -func handlePanic(err *error, op string) { - if e := recover(); e != nil { - if nerr, ok := e.(osError); ok { - *err = nerr.err - return - } - panic("tabwriter: panic during " + op) - } -} - -// RememberedWidths returns a copy of the remembered per-column maximum widths. -// Requires use of the RememberWidths flag, and is not threadsafe. -func (b *Writer) RememberedWidths() []int { - retval := make([]int, len(b.maxwidths)) - copy(retval, b.maxwidths) - return retval -} - -// SetRememberedWidths sets the remembered per-column maximum widths. -// Requires use of the RememberWidths flag, and is not threadsafe. -func (b *Writer) SetRememberedWidths(widths []int) *Writer { - b.maxwidths = make([]int, len(widths)) - copy(b.maxwidths, widths) - return b -} - -// Flush should be called after the last call to Write to ensure -// that any data buffered in the Writer is written to output. Any -// incomplete escape sequence at the end is considered -// complete for formatting purposes. -func (b *Writer) Flush() error { - return b.flush() -} - -func (b *Writer) flush() (err error) { - defer b.reset() // even in the presence of errors - defer handlePanic(&err, "Flush") - - // add current cell if not empty - if b.cell.size > 0 { - if b.endChar != 0 { - // inside escape - terminate it even if incomplete - b.endEscape() - } - b.terminateCell(false) - } - - // format contents of buffer - b.format(0, 0, len(b.lines)) - return nil -} - -var hbar = []byte("---\n") - -// Write writes buf to the writer b. -// The only errors returned are ones encountered -// while writing to the underlying output stream. -// -func (b *Writer) Write(buf []byte) (n int, err error) { - defer handlePanic(&err, "Write") - - // split text into cells - n = 0 - for i, ch := range buf { - if b.endChar == 0 { - // outside escape - switch ch { - case '\t', '\v', '\n', '\f': - // end of cell - b.append(buf[n:i]) - b.updateWidth() - n = i + 1 // ch consumed - ncells := b.terminateCell(ch == '\t') - if ch == '\n' || ch == '\f' { - // terminate line - b.addLine(ch == '\f') - if ch == '\f' || ncells == 1 { - // A '\f' always forces a flush. Otherwise, if the previous - // line has only one cell which does not have an impact on - // the formatting of the following lines (the last cell per - // line is ignored by format()), thus we can flush the - // Writer contents. - if err = b.Flush(); err != nil { - return - } - if ch == '\f' && b.flags&Debug != 0 { - // indicate section break - b.write0(hbar) - } - } - } - - case Escape: - // start of escaped sequence - b.append(buf[n:i]) - b.updateWidth() - n = i - if b.flags&StripEscape != 0 { - n++ // strip Escape - } - b.startEscape(Escape) - - case '<', '&': - // possibly an html tag/entity - if b.flags&FilterHTML != 0 { - // begin of tag/entity - b.append(buf[n:i]) - b.updateWidth() - n = i - b.startEscape(ch) - } - } - - } else { - // inside escape - if ch == b.endChar { - // end of tag/entity - j := i + 1 - if ch == Escape && b.flags&StripEscape != 0 { - j = i // strip Escape - } - b.append(buf[n:j]) - n = i + 1 // ch consumed - b.endEscape() - } - } - } - - // append leftover text - b.append(buf[n:]) - n = len(buf) - return -} - -// NewWriter allocates and initializes a new tabwriter.Writer. -// The parameters are the same as for the Init function. -// -func NewWriter(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer { - return new(Writer).Init(output, minwidth, tabwidth, padding, padchar, flags) -} diff --git a/vendor/github.com/moby/spdystream/CONTRIBUTING.md b/vendor/github.com/moby/spdystream/CONTRIBUTING.md deleted file mode 100644 index d4eddcc5396..00000000000 --- a/vendor/github.com/moby/spdystream/CONTRIBUTING.md +++ /dev/null @@ -1,13 +0,0 @@ -# Contributing to SpdyStream - -Want to hack on spdystream? Awesome! Here are instructions to get you -started. - -SpdyStream is a part of the [Docker](https://docker.io) project, and follows -the same rules and principles. If you're already familiar with the way -Docker does things, you'll feel right at home. - -Otherwise, go read -[Docker's contributions guidelines](https://github.com/dotcloud/docker/blob/master/CONTRIBUTING.md). - -Happy hacking! diff --git a/vendor/github.com/moby/spdystream/LICENSE b/vendor/github.com/moby/spdystream/LICENSE deleted file mode 100644 index d6456956733..00000000000 --- a/vendor/github.com/moby/spdystream/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/moby/spdystream/MAINTAINERS b/vendor/github.com/moby/spdystream/MAINTAINERS deleted file mode 100644 index 26e5ec828a1..00000000000 --- a/vendor/github.com/moby/spdystream/MAINTAINERS +++ /dev/null @@ -1,40 +0,0 @@ -# Spdystream maintainers file -# -# This file describes who runs the moby/spdystream project and how. -# This is a living document - if you see something out of date or missing, speak up! -# -# It is structured to be consumable by both humans and programs. -# To extract its contents programmatically, use any TOML-compliant parser. -# -# This file is compiled into the MAINTAINERS file in docker/opensource. -# -[Org] - [Org."Core maintainers"] - people = [ - "adisky", - "dims", - "dmcgowan", - ] - -[people] - -# A reference list of all people associated with the project. -# All other sections should refer to people by their canonical key -# in the people section. - - # ADD YOURSELF HERE IN ALPHABETICAL ORDER - - [people.adisky] - Name = "Aditi Sharma" - Email = "adi.sky17@gmail.com" - GitHub = "adisky" - - [people.dims] - Name = "Davanum Srinivas" - Email = "davanum@gmail.com" - GitHub = "dims" - - [people.dmcgowan] - Name = "Derek McGowan" - Email = "derek@mcg.dev" - GitHub = "dmcgowan" diff --git a/vendor/github.com/moby/spdystream/NOTICE b/vendor/github.com/moby/spdystream/NOTICE deleted file mode 100644 index b9b11c9ab7b..00000000000 --- a/vendor/github.com/moby/spdystream/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -SpdyStream -Copyright 2014-2021 Docker Inc. - -This product includes software developed at -Docker Inc. (https://www.docker.com/). diff --git a/vendor/github.com/moby/spdystream/README.md b/vendor/github.com/moby/spdystream/README.md deleted file mode 100644 index b84e9834398..00000000000 --- a/vendor/github.com/moby/spdystream/README.md +++ /dev/null @@ -1,77 +0,0 @@ -# SpdyStream - -A multiplexed stream library using spdy - -## Usage - -Client example (connecting to mirroring server without auth) - -```go -package main - -import ( - "fmt" - "github.com/moby/spdystream" - "net" - "net/http" -) - -func main() { - conn, err := net.Dial("tcp", "localhost:8080") - if err != nil { - panic(err) - } - spdyConn, err := spdystream.NewConnection(conn, false) - if err != nil { - panic(err) - } - go spdyConn.Serve(spdystream.NoOpStreamHandler) - stream, err := spdyConn.CreateStream(http.Header{}, nil, false) - if err != nil { - panic(err) - } - - stream.Wait() - - fmt.Fprint(stream, "Writing to stream") - - buf := make([]byte, 25) - stream.Read(buf) - fmt.Println(string(buf)) - - stream.Close() -} -``` - -Server example (mirroring server without auth) - -```go -package main - -import ( - "github.com/moby/spdystream" - "net" -) - -func main() { - listener, err := net.Listen("tcp", "localhost:8080") - if err != nil { - panic(err) - } - for { - conn, err := listener.Accept() - if err != nil { - panic(err) - } - spdyConn, err := spdystream.NewConnection(conn, true) - if err != nil { - panic(err) - } - go spdyConn.Serve(spdystream.MirrorStreamHandler) - } -} -``` - -## Copyright and license - -Copyright 2013-2021 Docker, inc. Released under the [Apache 2.0 license](LICENSE). diff --git a/vendor/github.com/moby/spdystream/connection.go b/vendor/github.com/moby/spdystream/connection.go deleted file mode 100644 index d906bb05ced..00000000000 --- a/vendor/github.com/moby/spdystream/connection.go +++ /dev/null @@ -1,972 +0,0 @@ -/* - Copyright 2014-2021 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. -*/ - -package spdystream - -import ( - "errors" - "fmt" - "io" - "net" - "net/http" - "sync" - "time" - - "github.com/moby/spdystream/spdy" -) - -var ( - ErrInvalidStreamId = errors.New("Invalid stream id") - ErrTimeout = errors.New("Timeout occurred") - ErrReset = errors.New("Stream reset") - ErrWriteClosedStream = errors.New("Write on closed stream") -) - -const ( - FRAME_WORKERS = 5 - QUEUE_SIZE = 50 -) - -type StreamHandler func(stream *Stream) - -type AuthHandler func(header http.Header, slot uint8, parent uint32) bool - -type idleAwareFramer struct { - f *spdy.Framer - conn *Connection - writeLock sync.Mutex - resetChan chan struct{} - setTimeoutLock sync.Mutex - setTimeoutChan chan time.Duration - timeout time.Duration -} - -func newIdleAwareFramer(framer *spdy.Framer) *idleAwareFramer { - iaf := &idleAwareFramer{ - f: framer, - resetChan: make(chan struct{}, 2), - // setTimeoutChan needs to be buffered to avoid deadlocks when calling setIdleTimeout at about - // the same time the connection is being closed - setTimeoutChan: make(chan time.Duration, 1), - } - return iaf -} - -func (i *idleAwareFramer) monitor() { - var ( - timer *time.Timer - expired <-chan time.Time - resetChan = i.resetChan - setTimeoutChan = i.setTimeoutChan - ) -Loop: - for { - select { - case timeout := <-i.setTimeoutChan: - i.timeout = timeout - if timeout == 0 { - if timer != nil { - timer.Stop() - } - } else { - if timer == nil { - timer = time.NewTimer(timeout) - expired = timer.C - } else { - timer.Reset(timeout) - } - } - case <-resetChan: - if timer != nil && i.timeout > 0 { - timer.Reset(i.timeout) - } - case <-expired: - i.conn.streamCond.L.Lock() - streams := i.conn.streams - i.conn.streams = make(map[spdy.StreamId]*Stream) - i.conn.streamCond.Broadcast() - i.conn.streamCond.L.Unlock() - go func() { - for _, stream := range streams { - stream.resetStream() - } - i.conn.Close() - }() - case <-i.conn.closeChan: - if timer != nil { - timer.Stop() - } - - // Start a goroutine to drain resetChan. This is needed because we've seen - // some unit tests with large numbers of goroutines get into a situation - // where resetChan fills up, at least 1 call to Write() is still trying to - // send to resetChan, the connection gets closed, and this case statement - // attempts to grab the write lock that Write() already has, causing a - // deadlock. - // - // See https://github.com/moby/spdystream/issues/49 for more details. - go func() { - for range resetChan { - } - }() - - go func() { - for range setTimeoutChan { - } - }() - - i.writeLock.Lock() - close(resetChan) - i.resetChan = nil - i.writeLock.Unlock() - - i.setTimeoutLock.Lock() - close(i.setTimeoutChan) - i.setTimeoutChan = nil - i.setTimeoutLock.Unlock() - - break Loop - } - } - - // Drain resetChan - for range resetChan { - } -} - -func (i *idleAwareFramer) WriteFrame(frame spdy.Frame) error { - i.writeLock.Lock() - defer i.writeLock.Unlock() - if i.resetChan == nil { - return io.EOF - } - err := i.f.WriteFrame(frame) - if err != nil { - return err - } - - i.resetChan <- struct{}{} - - return nil -} - -func (i *idleAwareFramer) ReadFrame() (spdy.Frame, error) { - frame, err := i.f.ReadFrame() - if err != nil { - return nil, err - } - - // resetChan should never be closed since it is only closed - // when the connection has closed its closeChan. This closure - // only occurs after all Reads have finished - // TODO (dmcgowan): refactor relationship into connection - i.resetChan <- struct{}{} - - return frame, nil -} - -func (i *idleAwareFramer) setIdleTimeout(timeout time.Duration) { - i.setTimeoutLock.Lock() - defer i.setTimeoutLock.Unlock() - - if i.setTimeoutChan == nil { - return - } - - i.setTimeoutChan <- timeout -} - -type Connection struct { - conn net.Conn - framer *idleAwareFramer - - closeChan chan bool - goneAway bool - lastStreamChan chan<- *Stream - goAwayTimeout time.Duration - closeTimeout time.Duration - - streamLock *sync.RWMutex - streamCond *sync.Cond - streams map[spdy.StreamId]*Stream - - nextIdLock sync.Mutex - receiveIdLock sync.Mutex - nextStreamId spdy.StreamId - receivedStreamId spdy.StreamId - - pingIdLock sync.Mutex - pingId uint32 - pingChans map[uint32]chan error - - shutdownLock sync.Mutex - shutdownChan chan error - hasShutdown bool - - // for testing https://github.com/moby/spdystream/pull/56 - dataFrameHandler func(*spdy.DataFrame) error -} - -// NewConnection creates a new spdy connection from an existing -// network connection. -func NewConnection(conn net.Conn, server bool) (*Connection, error) { - framer, framerErr := spdy.NewFramer(conn, conn) - if framerErr != nil { - return nil, framerErr - } - idleAwareFramer := newIdleAwareFramer(framer) - var sid spdy.StreamId - var rid spdy.StreamId - var pid uint32 - if server { - sid = 2 - rid = 1 - pid = 2 - } else { - sid = 1 - rid = 2 - pid = 1 - } - - streamLock := new(sync.RWMutex) - streamCond := sync.NewCond(streamLock) - - session := &Connection{ - conn: conn, - framer: idleAwareFramer, - - closeChan: make(chan bool), - goAwayTimeout: time.Duration(0), - closeTimeout: time.Duration(0), - - streamLock: streamLock, - streamCond: streamCond, - streams: make(map[spdy.StreamId]*Stream), - nextStreamId: sid, - receivedStreamId: rid, - - pingId: pid, - pingChans: make(map[uint32]chan error), - - shutdownChan: make(chan error), - } - session.dataFrameHandler = session.handleDataFrame - idleAwareFramer.conn = session - go idleAwareFramer.monitor() - - return session, nil -} - -// Ping sends a ping frame across the connection and -// returns the response time -func (s *Connection) Ping() (time.Duration, error) { - pid := s.pingId - s.pingIdLock.Lock() - if s.pingId > 0x7ffffffe { - s.pingId = s.pingId - 0x7ffffffe - } else { - s.pingId = s.pingId + 2 - } - s.pingIdLock.Unlock() - pingChan := make(chan error) - s.pingChans[pid] = pingChan - defer delete(s.pingChans, pid) - - frame := &spdy.PingFrame{Id: pid} - startTime := time.Now() - writeErr := s.framer.WriteFrame(frame) - if writeErr != nil { - return time.Duration(0), writeErr - } - select { - case <-s.closeChan: - return time.Duration(0), errors.New("connection closed") - case err, ok := <-pingChan: - if ok && err != nil { - return time.Duration(0), err - } - break - } - return time.Since(startTime), nil -} - -// Serve handles frames sent from the server, including reply frames -// which are needed to fully initiate connections. Both clients and servers -// should call Serve in a separate goroutine before creating streams. -func (s *Connection) Serve(newHandler StreamHandler) { - // use a WaitGroup to wait for all frames to be drained after receiving - // go-away. - var wg sync.WaitGroup - - // Parition queues to ensure stream frames are handled - // by the same worker, ensuring order is maintained - frameQueues := make([]*PriorityFrameQueue, FRAME_WORKERS) - for i := 0; i < FRAME_WORKERS; i++ { - frameQueues[i] = NewPriorityFrameQueue(QUEUE_SIZE) - - // Ensure frame queue is drained when connection is closed - go func(frameQueue *PriorityFrameQueue) { - <-s.closeChan - frameQueue.Drain() - }(frameQueues[i]) - - wg.Add(1) - go func(frameQueue *PriorityFrameQueue) { - // let the WaitGroup know this worker is done - defer wg.Done() - - s.frameHandler(frameQueue, newHandler) - }(frameQueues[i]) - } - - var ( - partitionRoundRobin int - goAwayFrame *spdy.GoAwayFrame - ) -Loop: - for { - readFrame, err := s.framer.ReadFrame() - if err != nil { - if err != io.EOF { - debugMessage("frame read error: %s", err) - } else { - debugMessage("(%p) EOF received", s) - } - break - } - var priority uint8 - var partition int - switch frame := readFrame.(type) { - case *spdy.SynStreamFrame: - if s.checkStreamFrame(frame) { - priority = frame.Priority - partition = int(frame.StreamId % FRAME_WORKERS) - debugMessage("(%p) Add stream frame: %d ", s, frame.StreamId) - s.addStreamFrame(frame) - } else { - debugMessage("(%p) Rejected stream frame: %d ", s, frame.StreamId) - continue - } - case *spdy.SynReplyFrame: - priority = s.getStreamPriority(frame.StreamId) - partition = int(frame.StreamId % FRAME_WORKERS) - case *spdy.DataFrame: - priority = s.getStreamPriority(frame.StreamId) - partition = int(frame.StreamId % FRAME_WORKERS) - case *spdy.RstStreamFrame: - priority = s.getStreamPriority(frame.StreamId) - partition = int(frame.StreamId % FRAME_WORKERS) - case *spdy.HeadersFrame: - priority = s.getStreamPriority(frame.StreamId) - partition = int(frame.StreamId % FRAME_WORKERS) - case *spdy.PingFrame: - priority = 0 - partition = partitionRoundRobin - partitionRoundRobin = (partitionRoundRobin + 1) % FRAME_WORKERS - case *spdy.GoAwayFrame: - // hold on to the go away frame and exit the loop - goAwayFrame = frame - break Loop - default: - priority = 7 - partition = partitionRoundRobin - partitionRoundRobin = (partitionRoundRobin + 1) % FRAME_WORKERS - } - frameQueues[partition].Push(readFrame, priority) - } - close(s.closeChan) - - // wait for all frame handler workers to indicate they've drained their queues - // before handling the go away frame - wg.Wait() - - if goAwayFrame != nil { - s.handleGoAwayFrame(goAwayFrame) - } - - // now it's safe to close remote channels and empty s.streams - s.streamCond.L.Lock() - // notify streams that they're now closed, which will - // unblock any stream Read() calls - for _, stream := range s.streams { - stream.closeRemoteChannels() - } - s.streams = make(map[spdy.StreamId]*Stream) - s.streamCond.Broadcast() - s.streamCond.L.Unlock() -} - -func (s *Connection) frameHandler(frameQueue *PriorityFrameQueue, newHandler StreamHandler) { - for { - popFrame := frameQueue.Pop() - if popFrame == nil { - return - } - - var frameErr error - switch frame := popFrame.(type) { - case *spdy.SynStreamFrame: - frameErr = s.handleStreamFrame(frame, newHandler) - case *spdy.SynReplyFrame: - frameErr = s.handleReplyFrame(frame) - case *spdy.DataFrame: - frameErr = s.dataFrameHandler(frame) - case *spdy.RstStreamFrame: - frameErr = s.handleResetFrame(frame) - case *spdy.HeadersFrame: - frameErr = s.handleHeaderFrame(frame) - case *spdy.PingFrame: - frameErr = s.handlePingFrame(frame) - case *spdy.GoAwayFrame: - frameErr = s.handleGoAwayFrame(frame) - default: - frameErr = fmt.Errorf("unhandled frame type: %T", frame) - } - - if frameErr != nil { - debugMessage("frame handling error: %s", frameErr) - } - } -} - -func (s *Connection) getStreamPriority(streamId spdy.StreamId) uint8 { - stream, streamOk := s.getStream(streamId) - if !streamOk { - return 7 - } - return stream.priority -} - -func (s *Connection) addStreamFrame(frame *spdy.SynStreamFrame) { - var parent *Stream - if frame.AssociatedToStreamId != spdy.StreamId(0) { - parent, _ = s.getStream(frame.AssociatedToStreamId) - } - - stream := &Stream{ - streamId: frame.StreamId, - parent: parent, - conn: s, - startChan: make(chan error), - headers: frame.Headers, - finished: (frame.CFHeader.Flags & spdy.ControlFlagUnidirectional) != 0x00, - replyCond: sync.NewCond(new(sync.Mutex)), - dataChan: make(chan []byte), - headerChan: make(chan http.Header), - closeChan: make(chan bool), - priority: frame.Priority, - } - if frame.CFHeader.Flags&spdy.ControlFlagFin != 0x00 { - stream.closeRemoteChannels() - } - - s.addStream(stream) -} - -// checkStreamFrame checks to see if a stream frame is allowed. -// If the stream is invalid, then a reset frame with protocol error -// will be returned. -func (s *Connection) checkStreamFrame(frame *spdy.SynStreamFrame) bool { - s.receiveIdLock.Lock() - defer s.receiveIdLock.Unlock() - if s.goneAway { - return false - } - validationErr := s.validateStreamId(frame.StreamId) - if validationErr != nil { - go func() { - resetErr := s.sendResetFrame(spdy.ProtocolError, frame.StreamId) - if resetErr != nil { - debugMessage("reset error: %s", resetErr) - } - }() - return false - } - return true -} - -func (s *Connection) handleStreamFrame(frame *spdy.SynStreamFrame, newHandler StreamHandler) error { - stream, ok := s.getStream(frame.StreamId) - if !ok { - return fmt.Errorf("Missing stream: %d", frame.StreamId) - } - - newHandler(stream) - - return nil -} - -func (s *Connection) handleReplyFrame(frame *spdy.SynReplyFrame) error { - debugMessage("(%p) Reply frame received for %d", s, frame.StreamId) - stream, streamOk := s.getStream(frame.StreamId) - if !streamOk { - debugMessage("Reply frame gone away for %d", frame.StreamId) - // Stream has already gone away - return nil - } - if stream.replied { - // Stream has already received reply - return nil - } - stream.replied = true - - // TODO Check for error - if (frame.CFHeader.Flags & spdy.ControlFlagFin) != 0x00 { - s.remoteStreamFinish(stream) - } - - close(stream.startChan) - - return nil -} - -func (s *Connection) handleResetFrame(frame *spdy.RstStreamFrame) error { - stream, streamOk := s.getStream(frame.StreamId) - if !streamOk { - // Stream has already been removed - return nil - } - s.removeStream(stream) - stream.closeRemoteChannels() - - if !stream.replied { - stream.replied = true - stream.startChan <- ErrReset - close(stream.startChan) - } - - stream.finishLock.Lock() - stream.finished = true - stream.finishLock.Unlock() - - return nil -} - -func (s *Connection) handleHeaderFrame(frame *spdy.HeadersFrame) error { - stream, streamOk := s.getStream(frame.StreamId) - if !streamOk { - // Stream has already gone away - return nil - } - if !stream.replied { - // No reply received...Protocol error? - return nil - } - - // TODO limit headers while not blocking (use buffered chan or goroutine?) - select { - case <-stream.closeChan: - return nil - case stream.headerChan <- frame.Headers: - } - - if (frame.CFHeader.Flags & spdy.ControlFlagFin) != 0x00 { - s.remoteStreamFinish(stream) - } - - return nil -} - -func (s *Connection) handleDataFrame(frame *spdy.DataFrame) error { - debugMessage("(%p) Data frame received for %d", s, frame.StreamId) - stream, streamOk := s.getStream(frame.StreamId) - if !streamOk { - debugMessage("(%p) Data frame gone away for %d", s, frame.StreamId) - // Stream has already gone away - return nil - } - if !stream.replied { - debugMessage("(%p) Data frame not replied %d", s, frame.StreamId) - // No reply received...Protocol error? - return nil - } - - debugMessage("(%p) (%d) Data frame handling", stream, stream.streamId) - if len(frame.Data) > 0 { - stream.dataLock.RLock() - select { - case <-stream.closeChan: - debugMessage("(%p) (%d) Data frame not sent (stream shut down)", stream, stream.streamId) - case stream.dataChan <- frame.Data: - debugMessage("(%p) (%d) Data frame sent", stream, stream.streamId) - } - stream.dataLock.RUnlock() - } - if (frame.Flags & spdy.DataFlagFin) != 0x00 { - s.remoteStreamFinish(stream) - } - return nil -} - -func (s *Connection) handlePingFrame(frame *spdy.PingFrame) error { - if s.pingId&0x01 != frame.Id&0x01 { - return s.framer.WriteFrame(frame) - } - pingChan, pingOk := s.pingChans[frame.Id] - if pingOk { - close(pingChan) - } - return nil -} - -func (s *Connection) handleGoAwayFrame(frame *spdy.GoAwayFrame) error { - debugMessage("(%p) Go away received", s) - s.receiveIdLock.Lock() - if s.goneAway { - s.receiveIdLock.Unlock() - return nil - } - s.goneAway = true - s.receiveIdLock.Unlock() - - if s.lastStreamChan != nil { - stream, _ := s.getStream(frame.LastGoodStreamId) - go func() { - s.lastStreamChan <- stream - }() - } - - // Do not block frame handler waiting for closure - go s.shutdown(s.goAwayTimeout) - - return nil -} - -func (s *Connection) remoteStreamFinish(stream *Stream) { - stream.closeRemoteChannels() - - stream.finishLock.Lock() - if stream.finished { - // Stream is fully closed, cleanup - s.removeStream(stream) - } - stream.finishLock.Unlock() -} - -// CreateStream creates a new spdy stream using the parameters for -// creating the stream frame. The stream frame will be sent upon -// calling this function, however this function does not wait for -// the reply frame. If waiting for the reply is desired, use -// the stream Wait or WaitTimeout function on the stream returned -// by this function. -func (s *Connection) CreateStream(headers http.Header, parent *Stream, fin bool) (*Stream, error) { - // MUST synchronize stream creation (all the way to writing the frame) - // as stream IDs **MUST** increase monotonically. - s.nextIdLock.Lock() - defer s.nextIdLock.Unlock() - - streamId := s.getNextStreamId() - if streamId == 0 { - return nil, fmt.Errorf("Unable to get new stream id") - } - - stream := &Stream{ - streamId: streamId, - parent: parent, - conn: s, - startChan: make(chan error), - headers: headers, - dataChan: make(chan []byte), - headerChan: make(chan http.Header), - closeChan: make(chan bool), - } - - debugMessage("(%p) (%p) Create stream", s, stream) - - s.addStream(stream) - - return stream, s.sendStream(stream, fin) -} - -func (s *Connection) shutdown(closeTimeout time.Duration) { - // TODO Ensure this isn't called multiple times - s.shutdownLock.Lock() - if s.hasShutdown { - s.shutdownLock.Unlock() - return - } - s.hasShutdown = true - s.shutdownLock.Unlock() - - var timeout <-chan time.Time - if closeTimeout > time.Duration(0) { - timeout = time.After(closeTimeout) - } - streamsClosed := make(chan bool) - - go func() { - s.streamCond.L.Lock() - for len(s.streams) > 0 { - debugMessage("Streams opened: %d, %#v", len(s.streams), s.streams) - s.streamCond.Wait() - } - s.streamCond.L.Unlock() - close(streamsClosed) - }() - - var err error - select { - case <-streamsClosed: - // No active streams, close should be safe - err = s.conn.Close() - case <-timeout: - // Force ungraceful close - err = s.conn.Close() - // Wait for cleanup to clear active streams - <-streamsClosed - } - - if err != nil { - duration := 10 * time.Minute - time.AfterFunc(duration, func() { - select { - case err, ok := <-s.shutdownChan: - if ok { - debugMessage("Unhandled close error after %s: %s", duration, err) - } - default: - } - }) - s.shutdownChan <- err - } - close(s.shutdownChan) -} - -// Closes spdy connection by sending GoAway frame and initiating shutdown -func (s *Connection) Close() error { - s.receiveIdLock.Lock() - if s.goneAway { - s.receiveIdLock.Unlock() - return nil - } - s.goneAway = true - s.receiveIdLock.Unlock() - - var lastStreamId spdy.StreamId - if s.receivedStreamId > 2 { - lastStreamId = s.receivedStreamId - 2 - } - - goAwayFrame := &spdy.GoAwayFrame{ - LastGoodStreamId: lastStreamId, - Status: spdy.GoAwayOK, - } - - err := s.framer.WriteFrame(goAwayFrame) - go s.shutdown(s.closeTimeout) - if err != nil { - return err - } - - return nil -} - -// CloseWait closes the connection and waits for shutdown -// to finish. Note the underlying network Connection -// is not closed until the end of shutdown. -func (s *Connection) CloseWait() error { - closeErr := s.Close() - if closeErr != nil { - return closeErr - } - shutdownErr, ok := <-s.shutdownChan - if ok { - return shutdownErr - } - return nil -} - -// Wait waits for the connection to finish shutdown or for -// the wait timeout duration to expire. This needs to be -// called either after Close has been called or the GOAWAYFRAME -// has been received. If the wait timeout is 0, this function -// will block until shutdown finishes. If wait is never called -// and a shutdown error occurs, that error will be logged as an -// unhandled error. -func (s *Connection) Wait(waitTimeout time.Duration) error { - var timeout <-chan time.Time - if waitTimeout > time.Duration(0) { - timeout = time.After(waitTimeout) - } - - select { - case err, ok := <-s.shutdownChan: - if ok { - return err - } - case <-timeout: - return ErrTimeout - } - return nil -} - -// NotifyClose registers a channel to be called when the remote -// peer inidicates connection closure. The last stream to be -// received by the remote will be sent on the channel. The notify -// timeout will determine the duration between go away received -// and the connection being closed. -func (s *Connection) NotifyClose(c chan<- *Stream, timeout time.Duration) { - s.goAwayTimeout = timeout - s.lastStreamChan = c -} - -// SetCloseTimeout sets the amount of time close will wait for -// streams to finish before terminating the underlying network -// connection. Setting the timeout to 0 will cause close to -// wait forever, which is the default. -func (s *Connection) SetCloseTimeout(timeout time.Duration) { - s.closeTimeout = timeout -} - -// SetIdleTimeout sets the amount of time the connection may sit idle before -// it is forcefully terminated. -func (s *Connection) SetIdleTimeout(timeout time.Duration) { - s.framer.setIdleTimeout(timeout) -} - -func (s *Connection) sendHeaders(headers http.Header, stream *Stream, fin bool) error { - var flags spdy.ControlFlags - if fin { - flags = spdy.ControlFlagFin - } - - headerFrame := &spdy.HeadersFrame{ - StreamId: stream.streamId, - Headers: headers, - CFHeader: spdy.ControlFrameHeader{Flags: flags}, - } - - return s.framer.WriteFrame(headerFrame) -} - -func (s *Connection) sendReply(headers http.Header, stream *Stream, fin bool) error { - var flags spdy.ControlFlags - if fin { - flags = spdy.ControlFlagFin - } - - replyFrame := &spdy.SynReplyFrame{ - StreamId: stream.streamId, - Headers: headers, - CFHeader: spdy.ControlFrameHeader{Flags: flags}, - } - - return s.framer.WriteFrame(replyFrame) -} - -func (s *Connection) sendResetFrame(status spdy.RstStreamStatus, streamId spdy.StreamId) error { - resetFrame := &spdy.RstStreamFrame{ - StreamId: streamId, - Status: status, - } - - return s.framer.WriteFrame(resetFrame) -} - -func (s *Connection) sendReset(status spdy.RstStreamStatus, stream *Stream) error { - return s.sendResetFrame(status, stream.streamId) -} - -func (s *Connection) sendStream(stream *Stream, fin bool) error { - var flags spdy.ControlFlags - if fin { - flags = spdy.ControlFlagFin - stream.finished = true - } - - var parentId spdy.StreamId - if stream.parent != nil { - parentId = stream.parent.streamId - } - - streamFrame := &spdy.SynStreamFrame{ - StreamId: spdy.StreamId(stream.streamId), - AssociatedToStreamId: spdy.StreamId(parentId), - Headers: stream.headers, - CFHeader: spdy.ControlFrameHeader{Flags: flags}, - } - - return s.framer.WriteFrame(streamFrame) -} - -// getNextStreamId returns the next sequential id -// every call should produce a unique value or an error -func (s *Connection) getNextStreamId() spdy.StreamId { - sid := s.nextStreamId - if sid > 0x7fffffff { - return 0 - } - s.nextStreamId = s.nextStreamId + 2 - return sid -} - -// PeekNextStreamId returns the next sequential id and keeps the next id untouched -func (s *Connection) PeekNextStreamId() spdy.StreamId { - sid := s.nextStreamId - return sid -} - -func (s *Connection) validateStreamId(rid spdy.StreamId) error { - if rid > 0x7fffffff || rid < s.receivedStreamId { - return ErrInvalidStreamId - } - s.receivedStreamId = rid + 2 - return nil -} - -func (s *Connection) addStream(stream *Stream) { - s.streamCond.L.Lock() - s.streams[stream.streamId] = stream - debugMessage("(%p) (%p) Stream added, broadcasting: %d", s, stream, stream.streamId) - s.streamCond.Broadcast() - s.streamCond.L.Unlock() -} - -func (s *Connection) removeStream(stream *Stream) { - s.streamCond.L.Lock() - delete(s.streams, stream.streamId) - debugMessage("(%p) (%p) Stream removed, broadcasting: %d", s, stream, stream.streamId) - s.streamCond.Broadcast() - s.streamCond.L.Unlock() -} - -func (s *Connection) getStream(streamId spdy.StreamId) (stream *Stream, ok bool) { - s.streamLock.RLock() - stream, ok = s.streams[streamId] - s.streamLock.RUnlock() - return -} - -// FindStream looks up the given stream id and either waits for the -// stream to be found or returns nil if the stream id is no longer -// valid. -func (s *Connection) FindStream(streamId uint32) *Stream { - var stream *Stream - var ok bool - s.streamCond.L.Lock() - stream, ok = s.streams[spdy.StreamId(streamId)] - debugMessage("(%p) Found stream %d? %t", s, spdy.StreamId(streamId), ok) - for !ok && streamId >= uint32(s.receivedStreamId) { - s.streamCond.Wait() - stream, ok = s.streams[spdy.StreamId(streamId)] - } - s.streamCond.L.Unlock() - return stream -} - -func (s *Connection) CloseChan() <-chan bool { - return s.closeChan -} diff --git a/vendor/github.com/moby/spdystream/handlers.go b/vendor/github.com/moby/spdystream/handlers.go deleted file mode 100644 index d68f61f8121..00000000000 --- a/vendor/github.com/moby/spdystream/handlers.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - Copyright 2014-2021 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. -*/ - -package spdystream - -import ( - "io" - "net/http" -) - -// MirrorStreamHandler mirrors all streams. -func MirrorStreamHandler(stream *Stream) { - replyErr := stream.SendReply(http.Header{}, false) - if replyErr != nil { - return - } - - go func() { - io.Copy(stream, stream) - stream.Close() - }() - go func() { - for { - header, receiveErr := stream.ReceiveHeader() - if receiveErr != nil { - return - } - sendErr := stream.SendHeader(header, false) - if sendErr != nil { - return - } - } - }() -} - -// NoopStreamHandler does nothing when stream connects. -func NoOpStreamHandler(stream *Stream) { - stream.SendReply(http.Header{}, false) -} diff --git a/vendor/github.com/moby/spdystream/priority.go b/vendor/github.com/moby/spdystream/priority.go deleted file mode 100644 index d8eb3516ca3..00000000000 --- a/vendor/github.com/moby/spdystream/priority.go +++ /dev/null @@ -1,114 +0,0 @@ -/* - Copyright 2014-2021 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. -*/ - -package spdystream - -import ( - "container/heap" - "sync" - - "github.com/moby/spdystream/spdy" -) - -type prioritizedFrame struct { - frame spdy.Frame - priority uint8 - insertId uint64 -} - -type frameQueue []*prioritizedFrame - -func (fq frameQueue) Len() int { - return len(fq) -} - -func (fq frameQueue) Less(i, j int) bool { - if fq[i].priority == fq[j].priority { - return fq[i].insertId < fq[j].insertId - } - return fq[i].priority < fq[j].priority -} - -func (fq frameQueue) Swap(i, j int) { - fq[i], fq[j] = fq[j], fq[i] -} - -func (fq *frameQueue) Push(x interface{}) { - *fq = append(*fq, x.(*prioritizedFrame)) -} - -func (fq *frameQueue) Pop() interface{} { - old := *fq - n := len(old) - *fq = old[0 : n-1] - return old[n-1] -} - -type PriorityFrameQueue struct { - queue *frameQueue - c *sync.Cond - size int - nextInsertId uint64 - drain bool -} - -func NewPriorityFrameQueue(size int) *PriorityFrameQueue { - queue := make(frameQueue, 0, size) - heap.Init(&queue) - - return &PriorityFrameQueue{ - queue: &queue, - size: size, - c: sync.NewCond(&sync.Mutex{}), - } -} - -func (q *PriorityFrameQueue) Push(frame spdy.Frame, priority uint8) { - q.c.L.Lock() - defer q.c.L.Unlock() - for q.queue.Len() >= q.size { - q.c.Wait() - } - pFrame := &prioritizedFrame{ - frame: frame, - priority: priority, - insertId: q.nextInsertId, - } - q.nextInsertId = q.nextInsertId + 1 - heap.Push(q.queue, pFrame) - q.c.Signal() -} - -func (q *PriorityFrameQueue) Pop() spdy.Frame { - q.c.L.Lock() - defer q.c.L.Unlock() - for q.queue.Len() == 0 { - if q.drain { - return nil - } - q.c.Wait() - } - frame := heap.Pop(q.queue).(*prioritizedFrame).frame - q.c.Signal() - return frame -} - -func (q *PriorityFrameQueue) Drain() { - q.c.L.Lock() - defer q.c.L.Unlock() - q.drain = true - q.c.Broadcast() -} diff --git a/vendor/github.com/moby/spdystream/spdy/dictionary.go b/vendor/github.com/moby/spdystream/spdy/dictionary.go deleted file mode 100644 index 392232f1746..00000000000 --- a/vendor/github.com/moby/spdystream/spdy/dictionary.go +++ /dev/null @@ -1,203 +0,0 @@ -/* - Copyright 2014-2021 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. -*/ - -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package spdy - -// headerDictionary is the dictionary sent to the zlib compressor/decompressor. -var headerDictionary = []byte{ - 0x00, 0x00, 0x00, 0x07, 0x6f, 0x70, 0x74, 0x69, - 0x6f, 0x6e, 0x73, 0x00, 0x00, 0x00, 0x04, 0x68, - 0x65, 0x61, 0x64, 0x00, 0x00, 0x00, 0x04, 0x70, - 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, 0x70, - 0x75, 0x74, 0x00, 0x00, 0x00, 0x06, 0x64, 0x65, - 0x6c, 0x65, 0x74, 0x65, 0x00, 0x00, 0x00, 0x05, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x00, 0x00, 0x00, - 0x06, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x00, - 0x00, 0x00, 0x0e, 0x61, 0x63, 0x63, 0x65, 0x70, - 0x74, 0x2d, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, - 0x74, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63, - 0x65, 0x70, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, - 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x0f, - 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x6c, - 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00, - 0x00, 0x00, 0x0d, 0x61, 0x63, 0x63, 0x65, 0x70, - 0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x73, - 0x00, 0x00, 0x00, 0x03, 0x61, 0x67, 0x65, 0x00, - 0x00, 0x00, 0x05, 0x61, 0x6c, 0x6c, 0x6f, 0x77, - 0x00, 0x00, 0x00, 0x0d, 0x61, 0x75, 0x74, 0x68, - 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x61, 0x63, - 0x68, 0x65, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, - 0x6f, 0x6c, 0x00, 0x00, 0x00, 0x0a, 0x63, 0x6f, - 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, - 0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, - 0x65, 0x6e, 0x74, 0x2d, 0x62, 0x61, 0x73, 0x65, - 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, - 0x65, 0x6e, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, - 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, - 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, - 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, - 0x00, 0x00, 0x00, 0x0e, 0x63, 0x6f, 0x6e, 0x74, - 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67, - 0x74, 0x68, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, - 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x6f, - 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, - 0x00, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, - 0x74, 0x2d, 0x6d, 0x64, 0x35, 0x00, 0x00, 0x00, - 0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, - 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, - 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, - 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x00, 0x00, - 0x00, 0x04, 0x64, 0x61, 0x74, 0x65, 0x00, 0x00, - 0x00, 0x04, 0x65, 0x74, 0x61, 0x67, 0x00, 0x00, - 0x00, 0x06, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, - 0x00, 0x00, 0x00, 0x07, 0x65, 0x78, 0x70, 0x69, - 0x72, 0x65, 0x73, 0x00, 0x00, 0x00, 0x04, 0x66, - 0x72, 0x6f, 0x6d, 0x00, 0x00, 0x00, 0x04, 0x68, - 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x08, 0x69, - 0x66, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, - 0x00, 0x00, 0x11, 0x69, 0x66, 0x2d, 0x6d, 0x6f, - 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73, - 0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d, - 0x69, 0x66, 0x2d, 0x6e, 0x6f, 0x6e, 0x65, 0x2d, - 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00, - 0x08, 0x69, 0x66, 0x2d, 0x72, 0x61, 0x6e, 0x67, - 0x65, 0x00, 0x00, 0x00, 0x13, 0x69, 0x66, 0x2d, - 0x75, 0x6e, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, - 0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65, - 0x00, 0x00, 0x00, 0x0d, 0x6c, 0x61, 0x73, 0x74, - 0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, - 0x64, 0x00, 0x00, 0x00, 0x08, 0x6c, 0x6f, 0x63, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, - 0x0c, 0x6d, 0x61, 0x78, 0x2d, 0x66, 0x6f, 0x72, - 0x77, 0x61, 0x72, 0x64, 0x73, 0x00, 0x00, 0x00, - 0x06, 0x70, 0x72, 0x61, 0x67, 0x6d, 0x61, 0x00, - 0x00, 0x00, 0x12, 0x70, 0x72, 0x6f, 0x78, 0x79, - 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, - 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, - 0x13, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61, - 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x05, - 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, - 0x07, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x72, - 0x00, 0x00, 0x00, 0x0b, 0x72, 0x65, 0x74, 0x72, - 0x79, 0x2d, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, - 0x00, 0x00, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, - 0x72, 0x00, 0x00, 0x00, 0x02, 0x74, 0x65, 0x00, - 0x00, 0x00, 0x07, 0x74, 0x72, 0x61, 0x69, 0x6c, - 0x65, 0x72, 0x00, 0x00, 0x00, 0x11, 0x74, 0x72, - 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x2d, 0x65, - 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, - 0x00, 0x00, 0x07, 0x75, 0x70, 0x67, 0x72, 0x61, - 0x64, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x75, 0x73, - 0x65, 0x72, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74, - 0x00, 0x00, 0x00, 0x04, 0x76, 0x61, 0x72, 0x79, - 0x00, 0x00, 0x00, 0x03, 0x76, 0x69, 0x61, 0x00, - 0x00, 0x00, 0x07, 0x77, 0x61, 0x72, 0x6e, 0x69, - 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x77, 0x77, - 0x77, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, - 0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, - 0x00, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, - 0x00, 0x00, 0x00, 0x03, 0x67, 0x65, 0x74, 0x00, - 0x00, 0x00, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, - 0x73, 0x00, 0x00, 0x00, 0x06, 0x32, 0x30, 0x30, - 0x20, 0x4f, 0x4b, 0x00, 0x00, 0x00, 0x07, 0x76, - 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x00, 0x00, - 0x00, 0x08, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, - 0x2e, 0x31, 0x00, 0x00, 0x00, 0x03, 0x75, 0x72, - 0x6c, 0x00, 0x00, 0x00, 0x06, 0x70, 0x75, 0x62, - 0x6c, 0x69, 0x63, 0x00, 0x00, 0x00, 0x0a, 0x73, - 0x65, 0x74, 0x2d, 0x63, 0x6f, 0x6f, 0x6b, 0x69, - 0x65, 0x00, 0x00, 0x00, 0x0a, 0x6b, 0x65, 0x65, - 0x70, 0x2d, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x00, - 0x00, 0x00, 0x06, 0x6f, 0x72, 0x69, 0x67, 0x69, - 0x6e, 0x31, 0x30, 0x30, 0x31, 0x30, 0x31, 0x32, - 0x30, 0x31, 0x32, 0x30, 0x32, 0x32, 0x30, 0x35, - 0x32, 0x30, 0x36, 0x33, 0x30, 0x30, 0x33, 0x30, - 0x32, 0x33, 0x30, 0x33, 0x33, 0x30, 0x34, 0x33, - 0x30, 0x35, 0x33, 0x30, 0x36, 0x33, 0x30, 0x37, - 0x34, 0x30, 0x32, 0x34, 0x30, 0x35, 0x34, 0x30, - 0x36, 0x34, 0x30, 0x37, 0x34, 0x30, 0x38, 0x34, - 0x30, 0x39, 0x34, 0x31, 0x30, 0x34, 0x31, 0x31, - 0x34, 0x31, 0x32, 0x34, 0x31, 0x33, 0x34, 0x31, - 0x34, 0x34, 0x31, 0x35, 0x34, 0x31, 0x36, 0x34, - 0x31, 0x37, 0x35, 0x30, 0x32, 0x35, 0x30, 0x34, - 0x35, 0x30, 0x35, 0x32, 0x30, 0x33, 0x20, 0x4e, - 0x6f, 0x6e, 0x2d, 0x41, 0x75, 0x74, 0x68, 0x6f, - 0x72, 0x69, 0x74, 0x61, 0x74, 0x69, 0x76, 0x65, - 0x20, 0x49, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x32, 0x30, 0x34, 0x20, - 0x4e, 0x6f, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x65, - 0x6e, 0x74, 0x33, 0x30, 0x31, 0x20, 0x4d, 0x6f, - 0x76, 0x65, 0x64, 0x20, 0x50, 0x65, 0x72, 0x6d, - 0x61, 0x6e, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x34, - 0x30, 0x30, 0x20, 0x42, 0x61, 0x64, 0x20, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x34, 0x30, - 0x31, 0x20, 0x55, 0x6e, 0x61, 0x75, 0x74, 0x68, - 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x34, 0x30, - 0x33, 0x20, 0x46, 0x6f, 0x72, 0x62, 0x69, 0x64, - 0x64, 0x65, 0x6e, 0x34, 0x30, 0x34, 0x20, 0x4e, - 0x6f, 0x74, 0x20, 0x46, 0x6f, 0x75, 0x6e, 0x64, - 0x35, 0x30, 0x30, 0x20, 0x49, 0x6e, 0x74, 0x65, - 0x72, 0x6e, 0x61, 0x6c, 0x20, 0x53, 0x65, 0x72, - 0x76, 0x65, 0x72, 0x20, 0x45, 0x72, 0x72, 0x6f, - 0x72, 0x35, 0x30, 0x31, 0x20, 0x4e, 0x6f, 0x74, - 0x20, 0x49, 0x6d, 0x70, 0x6c, 0x65, 0x6d, 0x65, - 0x6e, 0x74, 0x65, 0x64, 0x35, 0x30, 0x33, 0x20, - 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, - 0x55, 0x6e, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, - 0x62, 0x6c, 0x65, 0x4a, 0x61, 0x6e, 0x20, 0x46, - 0x65, 0x62, 0x20, 0x4d, 0x61, 0x72, 0x20, 0x41, - 0x70, 0x72, 0x20, 0x4d, 0x61, 0x79, 0x20, 0x4a, - 0x75, 0x6e, 0x20, 0x4a, 0x75, 0x6c, 0x20, 0x41, - 0x75, 0x67, 0x20, 0x53, 0x65, 0x70, 0x74, 0x20, - 0x4f, 0x63, 0x74, 0x20, 0x4e, 0x6f, 0x76, 0x20, - 0x44, 0x65, 0x63, 0x20, 0x30, 0x30, 0x3a, 0x30, - 0x30, 0x3a, 0x30, 0x30, 0x20, 0x4d, 0x6f, 0x6e, - 0x2c, 0x20, 0x54, 0x75, 0x65, 0x2c, 0x20, 0x57, - 0x65, 0x64, 0x2c, 0x20, 0x54, 0x68, 0x75, 0x2c, - 0x20, 0x46, 0x72, 0x69, 0x2c, 0x20, 0x53, 0x61, - 0x74, 0x2c, 0x20, 0x53, 0x75, 0x6e, 0x2c, 0x20, - 0x47, 0x4d, 0x54, 0x63, 0x68, 0x75, 0x6e, 0x6b, - 0x65, 0x64, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, - 0x68, 0x74, 0x6d, 0x6c, 0x2c, 0x69, 0x6d, 0x61, - 0x67, 0x65, 0x2f, 0x70, 0x6e, 0x67, 0x2c, 0x69, - 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x6a, 0x70, 0x67, - 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x67, - 0x69, 0x66, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, - 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, - 0x6d, 0x6c, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, - 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, - 0x68, 0x74, 0x6d, 0x6c, 0x2b, 0x78, 0x6d, 0x6c, - 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x70, 0x6c, - 0x61, 0x69, 0x6e, 0x2c, 0x74, 0x65, 0x78, 0x74, - 0x2f, 0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72, - 0x69, 0x70, 0x74, 0x2c, 0x70, 0x75, 0x62, 0x6c, - 0x69, 0x63, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, - 0x65, 0x6d, 0x61, 0x78, 0x2d, 0x61, 0x67, 0x65, - 0x3d, 0x67, 0x7a, 0x69, 0x70, 0x2c, 0x64, 0x65, - 0x66, 0x6c, 0x61, 0x74, 0x65, 0x2c, 0x73, 0x64, - 0x63, 0x68, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, - 0x74, 0x3d, 0x75, 0x74, 0x66, 0x2d, 0x38, 0x63, - 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x69, - 0x73, 0x6f, 0x2d, 0x38, 0x38, 0x35, 0x39, 0x2d, - 0x31, 0x2c, 0x75, 0x74, 0x66, 0x2d, 0x2c, 0x2a, - 0x2c, 0x65, 0x6e, 0x71, 0x3d, 0x30, 0x2e, -} diff --git a/vendor/github.com/moby/spdystream/spdy/read.go b/vendor/github.com/moby/spdystream/spdy/read.go deleted file mode 100644 index 75ea045b8e3..00000000000 --- a/vendor/github.com/moby/spdystream/spdy/read.go +++ /dev/null @@ -1,364 +0,0 @@ -/* - Copyright 2014-2021 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. -*/ - -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package spdy - -import ( - "compress/zlib" - "encoding/binary" - "io" - "net/http" - "strings" -) - -func (frame *SynStreamFrame) read(h ControlFrameHeader, f *Framer) error { - return f.readSynStreamFrame(h, frame) -} - -func (frame *SynReplyFrame) read(h ControlFrameHeader, f *Framer) error { - return f.readSynReplyFrame(h, frame) -} - -func (frame *RstStreamFrame) read(h ControlFrameHeader, f *Framer) error { - frame.CFHeader = h - if err := binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { - return err - } - if err := binary.Read(f.r, binary.BigEndian, &frame.Status); err != nil { - return err - } - if frame.Status == 0 { - return &Error{InvalidControlFrame, frame.StreamId} - } - if frame.StreamId == 0 { - return &Error{ZeroStreamId, 0} - } - return nil -} - -func (frame *SettingsFrame) read(h ControlFrameHeader, f *Framer) error { - frame.CFHeader = h - var numSettings uint32 - if err := binary.Read(f.r, binary.BigEndian, &numSettings); err != nil { - return err - } - frame.FlagIdValues = make([]SettingsFlagIdValue, numSettings) - for i := uint32(0); i < numSettings; i++ { - if err := binary.Read(f.r, binary.BigEndian, &frame.FlagIdValues[i].Id); err != nil { - return err - } - frame.FlagIdValues[i].Flag = SettingsFlag((frame.FlagIdValues[i].Id & 0xff000000) >> 24) - frame.FlagIdValues[i].Id &= 0xffffff - if err := binary.Read(f.r, binary.BigEndian, &frame.FlagIdValues[i].Value); err != nil { - return err - } - } - return nil -} - -func (frame *PingFrame) read(h ControlFrameHeader, f *Framer) error { - frame.CFHeader = h - if err := binary.Read(f.r, binary.BigEndian, &frame.Id); err != nil { - return err - } - if frame.Id == 0 { - return &Error{ZeroStreamId, 0} - } - if frame.CFHeader.Flags != 0 { - return &Error{InvalidControlFrame, StreamId(frame.Id)} - } - return nil -} - -func (frame *GoAwayFrame) read(h ControlFrameHeader, f *Framer) error { - frame.CFHeader = h - if err := binary.Read(f.r, binary.BigEndian, &frame.LastGoodStreamId); err != nil { - return err - } - if frame.CFHeader.Flags != 0 { - return &Error{InvalidControlFrame, frame.LastGoodStreamId} - } - if frame.CFHeader.length != 8 { - return &Error{InvalidControlFrame, frame.LastGoodStreamId} - } - if err := binary.Read(f.r, binary.BigEndian, &frame.Status); err != nil { - return err - } - return nil -} - -func (frame *HeadersFrame) read(h ControlFrameHeader, f *Framer) error { - return f.readHeadersFrame(h, frame) -} - -func (frame *WindowUpdateFrame) read(h ControlFrameHeader, f *Framer) error { - frame.CFHeader = h - if err := binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { - return err - } - if frame.CFHeader.Flags != 0 { - return &Error{InvalidControlFrame, frame.StreamId} - } - if frame.CFHeader.length != 8 { - return &Error{InvalidControlFrame, frame.StreamId} - } - if err := binary.Read(f.r, binary.BigEndian, &frame.DeltaWindowSize); err != nil { - return err - } - return nil -} - -func newControlFrame(frameType ControlFrameType) (controlFrame, error) { - ctor, ok := cframeCtor[frameType] - if !ok { - return nil, &Error{Err: InvalidControlFrame} - } - return ctor(), nil -} - -var cframeCtor = map[ControlFrameType]func() controlFrame{ - TypeSynStream: func() controlFrame { return new(SynStreamFrame) }, - TypeSynReply: func() controlFrame { return new(SynReplyFrame) }, - TypeRstStream: func() controlFrame { return new(RstStreamFrame) }, - TypeSettings: func() controlFrame { return new(SettingsFrame) }, - TypePing: func() controlFrame { return new(PingFrame) }, - TypeGoAway: func() controlFrame { return new(GoAwayFrame) }, - TypeHeaders: func() controlFrame { return new(HeadersFrame) }, - TypeWindowUpdate: func() controlFrame { return new(WindowUpdateFrame) }, -} - -func (f *Framer) uncorkHeaderDecompressor(payloadSize int64) error { - if f.headerDecompressor != nil { - f.headerReader.N = payloadSize - return nil - } - f.headerReader = io.LimitedReader{R: f.r, N: payloadSize} - decompressor, err := zlib.NewReaderDict(&f.headerReader, []byte(headerDictionary)) - if err != nil { - return err - } - f.headerDecompressor = decompressor - return nil -} - -// ReadFrame reads SPDY encoded data and returns a decompressed Frame. -func (f *Framer) ReadFrame() (Frame, error) { - var firstWord uint32 - if err := binary.Read(f.r, binary.BigEndian, &firstWord); err != nil { - return nil, err - } - if firstWord&0x80000000 != 0 { - frameType := ControlFrameType(firstWord & 0xffff) - version := uint16(firstWord >> 16 & 0x7fff) - return f.parseControlFrame(version, frameType) - } - return f.parseDataFrame(StreamId(firstWord & 0x7fffffff)) -} - -func (f *Framer) parseControlFrame(version uint16, frameType ControlFrameType) (Frame, error) { - var length uint32 - if err := binary.Read(f.r, binary.BigEndian, &length); err != nil { - return nil, err - } - flags := ControlFlags((length & 0xff000000) >> 24) - length &= 0xffffff - header := ControlFrameHeader{version, frameType, flags, length} - cframe, err := newControlFrame(frameType) - if err != nil { - return nil, err - } - if err = cframe.read(header, f); err != nil { - return nil, err - } - return cframe, nil -} - -func parseHeaderValueBlock(r io.Reader, streamId StreamId) (http.Header, error) { - var numHeaders uint32 - if err := binary.Read(r, binary.BigEndian, &numHeaders); err != nil { - return nil, err - } - var e error - h := make(http.Header, int(numHeaders)) - for i := 0; i < int(numHeaders); i++ { - var length uint32 - if err := binary.Read(r, binary.BigEndian, &length); err != nil { - return nil, err - } - nameBytes := make([]byte, length) - if _, err := io.ReadFull(r, nameBytes); err != nil { - return nil, err - } - name := string(nameBytes) - if name != strings.ToLower(name) { - e = &Error{UnlowercasedHeaderName, streamId} - name = strings.ToLower(name) - } - if h[name] != nil { - e = &Error{DuplicateHeaders, streamId} - } - if err := binary.Read(r, binary.BigEndian, &length); err != nil { - return nil, err - } - value := make([]byte, length) - if _, err := io.ReadFull(r, value); err != nil { - return nil, err - } - valueList := strings.Split(string(value), headerValueSeparator) - for _, v := range valueList { - h.Add(name, v) - } - } - if e != nil { - return h, e - } - return h, nil -} - -func (f *Framer) readSynStreamFrame(h ControlFrameHeader, frame *SynStreamFrame) error { - frame.CFHeader = h - var err error - if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { - return err - } - if err = binary.Read(f.r, binary.BigEndian, &frame.AssociatedToStreamId); err != nil { - return err - } - if err = binary.Read(f.r, binary.BigEndian, &frame.Priority); err != nil { - return err - } - frame.Priority >>= 5 - if err = binary.Read(f.r, binary.BigEndian, &frame.Slot); err != nil { - return err - } - reader := f.r - if !f.headerCompressionDisabled { - err := f.uncorkHeaderDecompressor(int64(h.length - 10)) - if err != nil { - return err - } - reader = f.headerDecompressor - } - frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId) - if !f.headerCompressionDisabled && (err == io.EOF && f.headerReader.N == 0 || f.headerReader.N != 0) { - err = &Error{WrongCompressedPayloadSize, 0} - } - if err != nil { - return err - } - for h := range frame.Headers { - if invalidReqHeaders[h] { - return &Error{InvalidHeaderPresent, frame.StreamId} - } - } - if frame.StreamId == 0 { - return &Error{ZeroStreamId, 0} - } - return nil -} - -func (f *Framer) readSynReplyFrame(h ControlFrameHeader, frame *SynReplyFrame) error { - frame.CFHeader = h - var err error - if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { - return err - } - reader := f.r - if !f.headerCompressionDisabled { - err := f.uncorkHeaderDecompressor(int64(h.length - 4)) - if err != nil { - return err - } - reader = f.headerDecompressor - } - frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId) - if !f.headerCompressionDisabled && (err == io.EOF && f.headerReader.N == 0 || f.headerReader.N != 0) { - err = &Error{WrongCompressedPayloadSize, 0} - } - if err != nil { - return err - } - for h := range frame.Headers { - if invalidRespHeaders[h] { - return &Error{InvalidHeaderPresent, frame.StreamId} - } - } - if frame.StreamId == 0 { - return &Error{ZeroStreamId, 0} - } - return nil -} - -func (f *Framer) readHeadersFrame(h ControlFrameHeader, frame *HeadersFrame) error { - frame.CFHeader = h - var err error - if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { - return err - } - reader := f.r - if !f.headerCompressionDisabled { - err := f.uncorkHeaderDecompressor(int64(h.length - 4)) - if err != nil { - return err - } - reader = f.headerDecompressor - } - frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId) - if !f.headerCompressionDisabled && (err == io.EOF && f.headerReader.N == 0 || f.headerReader.N != 0) { - err = &Error{WrongCompressedPayloadSize, 0} - } - if err != nil { - return err - } - var invalidHeaders map[string]bool - if frame.StreamId%2 == 0 { - invalidHeaders = invalidReqHeaders - } else { - invalidHeaders = invalidRespHeaders - } - for h := range frame.Headers { - if invalidHeaders[h] { - return &Error{InvalidHeaderPresent, frame.StreamId} - } - } - if frame.StreamId == 0 { - return &Error{ZeroStreamId, 0} - } - return nil -} - -func (f *Framer) parseDataFrame(streamId StreamId) (*DataFrame, error) { - var length uint32 - if err := binary.Read(f.r, binary.BigEndian, &length); err != nil { - return nil, err - } - var frame DataFrame - frame.StreamId = streamId - frame.Flags = DataFlags(length >> 24) - length &= 0xffffff - frame.Data = make([]byte, length) - if _, err := io.ReadFull(f.r, frame.Data); err != nil { - return nil, err - } - if frame.StreamId == 0 { - return nil, &Error{ZeroStreamId, 0} - } - return &frame, nil -} diff --git a/vendor/github.com/moby/spdystream/spdy/types.go b/vendor/github.com/moby/spdystream/spdy/types.go deleted file mode 100644 index a254a43ab9d..00000000000 --- a/vendor/github.com/moby/spdystream/spdy/types.go +++ /dev/null @@ -1,291 +0,0 @@ -/* - Copyright 2014-2021 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. -*/ - -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package spdy implements the SPDY protocol (currently SPDY/3), described in -// http://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft3. -package spdy - -import ( - "bytes" - "compress/zlib" - "io" - "net/http" -) - -// Version is the protocol version number that this package implements. -const Version = 3 - -// ControlFrameType stores the type field in a control frame header. -type ControlFrameType uint16 - -const ( - TypeSynStream ControlFrameType = 0x0001 - TypeSynReply ControlFrameType = 0x0002 - TypeRstStream ControlFrameType = 0x0003 - TypeSettings ControlFrameType = 0x0004 - TypePing ControlFrameType = 0x0006 - TypeGoAway ControlFrameType = 0x0007 - TypeHeaders ControlFrameType = 0x0008 - TypeWindowUpdate ControlFrameType = 0x0009 -) - -// ControlFlags are the flags that can be set on a control frame. -type ControlFlags uint8 - -const ( - ControlFlagFin ControlFlags = 0x01 - ControlFlagUnidirectional ControlFlags = 0x02 - ControlFlagSettingsClearSettings ControlFlags = 0x01 -) - -// DataFlags are the flags that can be set on a data frame. -type DataFlags uint8 - -const ( - DataFlagFin DataFlags = 0x01 -) - -// MaxDataLength is the maximum number of bytes that can be stored in one frame. -const MaxDataLength = 1<<24 - 1 - -// headerValueSepator separates multiple header values. -const headerValueSeparator = "\x00" - -// Frame is a single SPDY frame in its unpacked in-memory representation. Use -// Framer to read and write it. -type Frame interface { - write(f *Framer) error -} - -// ControlFrameHeader contains all the fields in a control frame header, -// in its unpacked in-memory representation. -type ControlFrameHeader struct { - // Note, high bit is the "Control" bit. - version uint16 // spdy version number - frameType ControlFrameType - Flags ControlFlags - length uint32 // length of data field -} - -type controlFrame interface { - Frame - read(h ControlFrameHeader, f *Framer) error -} - -// StreamId represents a 31-bit value identifying the stream. -type StreamId uint32 - -// SynStreamFrame is the unpacked, in-memory representation of a SYN_STREAM -// frame. -type SynStreamFrame struct { - CFHeader ControlFrameHeader - StreamId StreamId - AssociatedToStreamId StreamId // stream id for a stream which this stream is associated to - Priority uint8 // priority of this frame (3-bit) - Slot uint8 // index in the server's credential vector of the client certificate - Headers http.Header -} - -// SynReplyFrame is the unpacked, in-memory representation of a SYN_REPLY frame. -type SynReplyFrame struct { - CFHeader ControlFrameHeader - StreamId StreamId - Headers http.Header -} - -// RstStreamStatus represents the status that led to a RST_STREAM. -type RstStreamStatus uint32 - -const ( - ProtocolError RstStreamStatus = iota + 1 - InvalidStream - RefusedStream - UnsupportedVersion - Cancel - InternalError - FlowControlError - StreamInUse - StreamAlreadyClosed - InvalidCredentials - FrameTooLarge -) - -// RstStreamFrame is the unpacked, in-memory representation of a RST_STREAM -// frame. -type RstStreamFrame struct { - CFHeader ControlFrameHeader - StreamId StreamId - Status RstStreamStatus -} - -// SettingsFlag represents a flag in a SETTINGS frame. -type SettingsFlag uint8 - -const ( - FlagSettingsPersistValue SettingsFlag = 0x1 - FlagSettingsPersisted SettingsFlag = 0x2 -) - -// SettingsFlag represents the id of an id/value pair in a SETTINGS frame. -type SettingsId uint32 - -const ( - SettingsUploadBandwidth SettingsId = iota + 1 - SettingsDownloadBandwidth - SettingsRoundTripTime - SettingsMaxConcurrentStreams - SettingsCurrentCwnd - SettingsDownloadRetransRate - SettingsInitialWindowSize - SettingsClientCretificateVectorSize -) - -// SettingsFlagIdValue is the unpacked, in-memory representation of the -// combined flag/id/value for a setting in a SETTINGS frame. -type SettingsFlagIdValue struct { - Flag SettingsFlag - Id SettingsId - Value uint32 -} - -// SettingsFrame is the unpacked, in-memory representation of a SPDY -// SETTINGS frame. -type SettingsFrame struct { - CFHeader ControlFrameHeader - FlagIdValues []SettingsFlagIdValue -} - -// PingFrame is the unpacked, in-memory representation of a PING frame. -type PingFrame struct { - CFHeader ControlFrameHeader - Id uint32 // unique id for this ping, from server is even, from client is odd. -} - -// GoAwayStatus represents the status in a GoAwayFrame. -type GoAwayStatus uint32 - -const ( - GoAwayOK GoAwayStatus = iota - GoAwayProtocolError - GoAwayInternalError -) - -// GoAwayFrame is the unpacked, in-memory representation of a GOAWAY frame. -type GoAwayFrame struct { - CFHeader ControlFrameHeader - LastGoodStreamId StreamId // last stream id which was accepted by sender - Status GoAwayStatus -} - -// HeadersFrame is the unpacked, in-memory representation of a HEADERS frame. -type HeadersFrame struct { - CFHeader ControlFrameHeader - StreamId StreamId - Headers http.Header -} - -// WindowUpdateFrame is the unpacked, in-memory representation of a -// WINDOW_UPDATE frame. -type WindowUpdateFrame struct { - CFHeader ControlFrameHeader - StreamId StreamId - DeltaWindowSize uint32 // additional number of bytes to existing window size -} - -// TODO: Implement credential frame and related methods. - -// DataFrame is the unpacked, in-memory representation of a DATA frame. -type DataFrame struct { - // Note, high bit is the "Control" bit. Should be 0 for data frames. - StreamId StreamId - Flags DataFlags - Data []byte // payload data of this frame -} - -// A SPDY specific error. -type ErrorCode string - -const ( - UnlowercasedHeaderName ErrorCode = "header was not lowercased" - DuplicateHeaders ErrorCode = "multiple headers with same name" - WrongCompressedPayloadSize ErrorCode = "compressed payload size was incorrect" - UnknownFrameType ErrorCode = "unknown frame type" - InvalidControlFrame ErrorCode = "invalid control frame" - InvalidDataFrame ErrorCode = "invalid data frame" - InvalidHeaderPresent ErrorCode = "frame contained invalid header" - ZeroStreamId ErrorCode = "stream id zero is disallowed" -) - -// Error contains both the type of error and additional values. StreamId is 0 -// if Error is not associated with a stream. -type Error struct { - Err ErrorCode - StreamId StreamId -} - -func (e *Error) Error() string { - return string(e.Err) -} - -var invalidReqHeaders = map[string]bool{ - "Connection": true, - "Host": true, - "Keep-Alive": true, - "Proxy-Connection": true, - "Transfer-Encoding": true, -} - -var invalidRespHeaders = map[string]bool{ - "Connection": true, - "Keep-Alive": true, - "Proxy-Connection": true, - "Transfer-Encoding": true, -} - -// Framer handles serializing/deserializing SPDY frames, including compressing/ -// decompressing payloads. -type Framer struct { - headerCompressionDisabled bool - w io.Writer - headerBuf *bytes.Buffer - headerCompressor *zlib.Writer - r io.Reader - headerReader io.LimitedReader - headerDecompressor io.ReadCloser -} - -// NewFramer allocates a new Framer for a given SPDY connection, represented by -// a io.Writer and io.Reader. Note that Framer will read and write individual fields -// from/to the Reader and Writer, so the caller should pass in an appropriately -// buffered implementation to optimize performance. -func NewFramer(w io.Writer, r io.Reader) (*Framer, error) { - compressBuf := new(bytes.Buffer) - compressor, err := zlib.NewWriterLevelDict(compressBuf, zlib.BestCompression, []byte(headerDictionary)) - if err != nil { - return nil, err - } - framer := &Framer{ - w: w, - headerBuf: compressBuf, - headerCompressor: compressor, - r: r, - } - return framer, nil -} diff --git a/vendor/github.com/moby/spdystream/spdy/write.go b/vendor/github.com/moby/spdystream/spdy/write.go deleted file mode 100644 index ab6d91f3b82..00000000000 --- a/vendor/github.com/moby/spdystream/spdy/write.go +++ /dev/null @@ -1,334 +0,0 @@ -/* - Copyright 2014-2021 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. -*/ - -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package spdy - -import ( - "encoding/binary" - "io" - "net/http" - "strings" -) - -func (frame *SynStreamFrame) write(f *Framer) error { - return f.writeSynStreamFrame(frame) -} - -func (frame *SynReplyFrame) write(f *Framer) error { - return f.writeSynReplyFrame(frame) -} - -func (frame *RstStreamFrame) write(f *Framer) (err error) { - if frame.StreamId == 0 { - return &Error{ZeroStreamId, 0} - } - frame.CFHeader.version = Version - frame.CFHeader.frameType = TypeRstStream - frame.CFHeader.Flags = 0 - frame.CFHeader.length = 8 - - // Serialize frame to Writer. - if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { - return - } - if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { - return - } - if frame.Status == 0 { - return &Error{InvalidControlFrame, frame.StreamId} - } - if err = binary.Write(f.w, binary.BigEndian, frame.Status); err != nil { - return - } - return -} - -func (frame *SettingsFrame) write(f *Framer) (err error) { - frame.CFHeader.version = Version - frame.CFHeader.frameType = TypeSettings - frame.CFHeader.length = uint32(len(frame.FlagIdValues)*8 + 4) - - // Serialize frame to Writer. - if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { - return - } - if err = binary.Write(f.w, binary.BigEndian, uint32(len(frame.FlagIdValues))); err != nil { - return - } - for _, flagIdValue := range frame.FlagIdValues { - flagId := uint32(flagIdValue.Flag)<<24 | uint32(flagIdValue.Id) - if err = binary.Write(f.w, binary.BigEndian, flagId); err != nil { - return - } - if err = binary.Write(f.w, binary.BigEndian, flagIdValue.Value); err != nil { - return - } - } - return -} - -func (frame *PingFrame) write(f *Framer) (err error) { - if frame.Id == 0 { - return &Error{ZeroStreamId, 0} - } - frame.CFHeader.version = Version - frame.CFHeader.frameType = TypePing - frame.CFHeader.Flags = 0 - frame.CFHeader.length = 4 - - // Serialize frame to Writer. - if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { - return - } - if err = binary.Write(f.w, binary.BigEndian, frame.Id); err != nil { - return - } - return -} - -func (frame *GoAwayFrame) write(f *Framer) (err error) { - frame.CFHeader.version = Version - frame.CFHeader.frameType = TypeGoAway - frame.CFHeader.Flags = 0 - frame.CFHeader.length = 8 - - // Serialize frame to Writer. - if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { - return - } - if err = binary.Write(f.w, binary.BigEndian, frame.LastGoodStreamId); err != nil { - return - } - if err = binary.Write(f.w, binary.BigEndian, frame.Status); err != nil { - return - } - return nil -} - -func (frame *HeadersFrame) write(f *Framer) error { - return f.writeHeadersFrame(frame) -} - -func (frame *WindowUpdateFrame) write(f *Framer) (err error) { - frame.CFHeader.version = Version - frame.CFHeader.frameType = TypeWindowUpdate - frame.CFHeader.Flags = 0 - frame.CFHeader.length = 8 - - // Serialize frame to Writer. - if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { - return - } - if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { - return - } - if err = binary.Write(f.w, binary.BigEndian, frame.DeltaWindowSize); err != nil { - return - } - return nil -} - -func (frame *DataFrame) write(f *Framer) error { - return f.writeDataFrame(frame) -} - -// WriteFrame writes a frame. -func (f *Framer) WriteFrame(frame Frame) error { - return frame.write(f) -} - -func writeControlFrameHeader(w io.Writer, h ControlFrameHeader) error { - if err := binary.Write(w, binary.BigEndian, 0x8000|h.version); err != nil { - return err - } - if err := binary.Write(w, binary.BigEndian, h.frameType); err != nil { - return err - } - flagsAndLength := uint32(h.Flags)<<24 | h.length - if err := binary.Write(w, binary.BigEndian, flagsAndLength); err != nil { - return err - } - return nil -} - -func writeHeaderValueBlock(w io.Writer, h http.Header) (n int, err error) { - n = 0 - if err = binary.Write(w, binary.BigEndian, uint32(len(h))); err != nil { - return - } - n += 2 - for name, values := range h { - if err = binary.Write(w, binary.BigEndian, uint32(len(name))); err != nil { - return - } - n += 2 - name = strings.ToLower(name) - if _, err = io.WriteString(w, name); err != nil { - return - } - n += len(name) - v := strings.Join(values, headerValueSeparator) - if err = binary.Write(w, binary.BigEndian, uint32(len(v))); err != nil { - return - } - n += 2 - if _, err = io.WriteString(w, v); err != nil { - return - } - n += len(v) - } - return -} - -func (f *Framer) writeSynStreamFrame(frame *SynStreamFrame) (err error) { - if frame.StreamId == 0 { - return &Error{ZeroStreamId, 0} - } - // Marshal the headers. - var writer io.Writer = f.headerBuf - if !f.headerCompressionDisabled { - writer = f.headerCompressor - } - if _, err = writeHeaderValueBlock(writer, frame.Headers); err != nil { - return - } - if !f.headerCompressionDisabled { - f.headerCompressor.Flush() - } - - // Set ControlFrameHeader. - frame.CFHeader.version = Version - frame.CFHeader.frameType = TypeSynStream - frame.CFHeader.length = uint32(len(f.headerBuf.Bytes()) + 10) - - // Serialize frame to Writer. - if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { - return err - } - if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { - return err - } - if err = binary.Write(f.w, binary.BigEndian, frame.AssociatedToStreamId); err != nil { - return err - } - if err = binary.Write(f.w, binary.BigEndian, frame.Priority<<5); err != nil { - return err - } - if err = binary.Write(f.w, binary.BigEndian, frame.Slot); err != nil { - return err - } - if _, err = f.w.Write(f.headerBuf.Bytes()); err != nil { - return err - } - f.headerBuf.Reset() - return nil -} - -func (f *Framer) writeSynReplyFrame(frame *SynReplyFrame) (err error) { - if frame.StreamId == 0 { - return &Error{ZeroStreamId, 0} - } - // Marshal the headers. - var writer io.Writer = f.headerBuf - if !f.headerCompressionDisabled { - writer = f.headerCompressor - } - if _, err = writeHeaderValueBlock(writer, frame.Headers); err != nil { - return - } - if !f.headerCompressionDisabled { - f.headerCompressor.Flush() - } - - // Set ControlFrameHeader. - frame.CFHeader.version = Version - frame.CFHeader.frameType = TypeSynReply - frame.CFHeader.length = uint32(len(f.headerBuf.Bytes()) + 4) - - // Serialize frame to Writer. - if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { - return - } - if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { - return - } - if _, err = f.w.Write(f.headerBuf.Bytes()); err != nil { - return - } - f.headerBuf.Reset() - return -} - -func (f *Framer) writeHeadersFrame(frame *HeadersFrame) (err error) { - if frame.StreamId == 0 { - return &Error{ZeroStreamId, 0} - } - // Marshal the headers. - var writer io.Writer = f.headerBuf - if !f.headerCompressionDisabled { - writer = f.headerCompressor - } - if _, err = writeHeaderValueBlock(writer, frame.Headers); err != nil { - return - } - if !f.headerCompressionDisabled { - f.headerCompressor.Flush() - } - - // Set ControlFrameHeader. - frame.CFHeader.version = Version - frame.CFHeader.frameType = TypeHeaders - frame.CFHeader.length = uint32(len(f.headerBuf.Bytes()) + 4) - - // Serialize frame to Writer. - if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { - return - } - if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { - return - } - if _, err = f.w.Write(f.headerBuf.Bytes()); err != nil { - return - } - f.headerBuf.Reset() - return -} - -func (f *Framer) writeDataFrame(frame *DataFrame) (err error) { - if frame.StreamId == 0 { - return &Error{ZeroStreamId, 0} - } - if frame.StreamId&0x80000000 != 0 || len(frame.Data) > MaxDataLength { - return &Error{InvalidDataFrame, frame.StreamId} - } - - // Serialize frame to Writer. - if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { - return - } - flagsAndLength := uint32(frame.Flags)<<24 | uint32(len(frame.Data)) - if err = binary.Write(f.w, binary.BigEndian, flagsAndLength); err != nil { - return - } - if _, err = f.w.Write(frame.Data); err != nil { - return - } - return nil -} diff --git a/vendor/github.com/moby/spdystream/stream.go b/vendor/github.com/moby/spdystream/stream.go deleted file mode 100644 index 404e3c02dfa..00000000000 --- a/vendor/github.com/moby/spdystream/stream.go +++ /dev/null @@ -1,343 +0,0 @@ -/* - Copyright 2014-2021 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. -*/ - -package spdystream - -import ( - "errors" - "fmt" - "io" - "net" - "net/http" - "sync" - "time" - - "github.com/moby/spdystream/spdy" -) - -var ( - ErrUnreadPartialData = errors.New("unread partial data") -) - -type Stream struct { - streamId spdy.StreamId - parent *Stream - conn *Connection - startChan chan error - - dataLock sync.RWMutex - dataChan chan []byte - unread []byte - - priority uint8 - headers http.Header - headerChan chan http.Header - finishLock sync.Mutex - finished bool - replyCond *sync.Cond - replied bool - closeLock sync.Mutex - closeChan chan bool -} - -// WriteData writes data to stream, sending a dataframe per call -func (s *Stream) WriteData(data []byte, fin bool) error { - s.waitWriteReply() - var flags spdy.DataFlags - - if fin { - flags = spdy.DataFlagFin - s.finishLock.Lock() - if s.finished { - s.finishLock.Unlock() - return ErrWriteClosedStream - } - s.finished = true - s.finishLock.Unlock() - } - - dataFrame := &spdy.DataFrame{ - StreamId: s.streamId, - Flags: flags, - Data: data, - } - - debugMessage("(%p) (%d) Writing data frame", s, s.streamId) - return s.conn.framer.WriteFrame(dataFrame) -} - -// Write writes bytes to a stream, calling write data for each call. -func (s *Stream) Write(data []byte) (n int, err error) { - err = s.WriteData(data, false) - if err == nil { - n = len(data) - } - return -} - -// Read reads bytes from a stream, a single read will never get more -// than what is sent on a single data frame, but a multiple calls to -// read may get data from the same data frame. -func (s *Stream) Read(p []byte) (n int, err error) { - if s.unread == nil { - select { - case <-s.closeChan: - return 0, io.EOF - case read, ok := <-s.dataChan: - if !ok { - return 0, io.EOF - } - s.unread = read - } - } - n = copy(p, s.unread) - if n < len(s.unread) { - s.unread = s.unread[n:] - } else { - s.unread = nil - } - return -} - -// ReadData reads an entire data frame and returns the byte array -// from the data frame. If there is unread data from the result -// of a Read call, this function will return an ErrUnreadPartialData. -func (s *Stream) ReadData() ([]byte, error) { - debugMessage("(%p) Reading data from %d", s, s.streamId) - if s.unread != nil { - return nil, ErrUnreadPartialData - } - select { - case <-s.closeChan: - return nil, io.EOF - case read, ok := <-s.dataChan: - if !ok { - return nil, io.EOF - } - return read, nil - } -} - -func (s *Stream) waitWriteReply() { - if s.replyCond != nil { - s.replyCond.L.Lock() - for !s.replied { - s.replyCond.Wait() - } - s.replyCond.L.Unlock() - } -} - -// Wait waits for the stream to receive a reply. -func (s *Stream) Wait() error { - return s.WaitTimeout(time.Duration(0)) -} - -// WaitTimeout waits for the stream to receive a reply or for timeout. -// When the timeout is reached, ErrTimeout will be returned. -func (s *Stream) WaitTimeout(timeout time.Duration) error { - var timeoutChan <-chan time.Time - if timeout > time.Duration(0) { - timeoutChan = time.After(timeout) - } - - select { - case err := <-s.startChan: - if err != nil { - return err - } - break - case <-timeoutChan: - return ErrTimeout - } - return nil -} - -// Close closes the stream by sending an empty data frame with the -// finish flag set, indicating this side is finished with the stream. -func (s *Stream) Close() error { - select { - case <-s.closeChan: - // Stream is now fully closed - s.conn.removeStream(s) - default: - break - } - return s.WriteData([]byte{}, true) -} - -// Reset sends a reset frame, putting the stream into the fully closed state. -func (s *Stream) Reset() error { - s.conn.removeStream(s) - return s.resetStream() -} - -func (s *Stream) resetStream() error { - // Always call closeRemoteChannels, even if s.finished is already true. - // This makes it so that stream.Close() followed by stream.Reset() allows - // stream.Read() to unblock. - s.closeRemoteChannels() - - s.finishLock.Lock() - if s.finished { - s.finishLock.Unlock() - return nil - } - s.finished = true - s.finishLock.Unlock() - - resetFrame := &spdy.RstStreamFrame{ - StreamId: s.streamId, - Status: spdy.Cancel, - } - return s.conn.framer.WriteFrame(resetFrame) -} - -// CreateSubStream creates a stream using the current as the parent -func (s *Stream) CreateSubStream(headers http.Header, fin bool) (*Stream, error) { - return s.conn.CreateStream(headers, s, fin) -} - -// SetPriority sets the stream priority, does not affect the -// remote priority of this stream after Open has been called. -// Valid values are 0 through 7, 0 being the highest priority -// and 7 the lowest. -func (s *Stream) SetPriority(priority uint8) { - s.priority = priority -} - -// SendHeader sends a header frame across the stream -func (s *Stream) SendHeader(headers http.Header, fin bool) error { - return s.conn.sendHeaders(headers, s, fin) -} - -// SendReply sends a reply on a stream, only valid to be called once -// when handling a new stream -func (s *Stream) SendReply(headers http.Header, fin bool) error { - if s.replyCond == nil { - return errors.New("cannot reply on initiated stream") - } - s.replyCond.L.Lock() - defer s.replyCond.L.Unlock() - if s.replied { - return nil - } - - err := s.conn.sendReply(headers, s, fin) - if err != nil { - return err - } - - s.replied = true - s.replyCond.Broadcast() - return nil -} - -// Refuse sends a reset frame with the status refuse, only -// valid to be called once when handling a new stream. This -// may be used to indicate that a stream is not allowed -// when http status codes are not being used. -func (s *Stream) Refuse() error { - if s.replied { - return nil - } - s.replied = true - return s.conn.sendReset(spdy.RefusedStream, s) -} - -// Cancel sends a reset frame with the status canceled. This -// can be used at any time by the creator of the Stream to -// indicate the stream is no longer needed. -func (s *Stream) Cancel() error { - return s.conn.sendReset(spdy.Cancel, s) -} - -// ReceiveHeader receives a header sent on the other side -// of the stream. This function will block until a header -// is received or stream is closed. -func (s *Stream) ReceiveHeader() (http.Header, error) { - select { - case <-s.closeChan: - break - case header, ok := <-s.headerChan: - if !ok { - return nil, fmt.Errorf("header chan closed") - } - return header, nil - } - return nil, fmt.Errorf("stream closed") -} - -// Parent returns the parent stream -func (s *Stream) Parent() *Stream { - return s.parent -} - -// Headers returns the headers used to create the stream -func (s *Stream) Headers() http.Header { - return s.headers -} - -// String returns the string version of stream using the -// streamId to uniquely identify the stream -func (s *Stream) String() string { - return fmt.Sprintf("stream:%d", s.streamId) -} - -// Identifier returns a 32 bit identifier for the stream -func (s *Stream) Identifier() uint32 { - return uint32(s.streamId) -} - -// IsFinished returns whether the stream has finished -// sending data -func (s *Stream) IsFinished() bool { - return s.finished -} - -// Implement net.Conn interface - -func (s *Stream) LocalAddr() net.Addr { - return s.conn.conn.LocalAddr() -} - -func (s *Stream) RemoteAddr() net.Addr { - return s.conn.conn.RemoteAddr() -} - -// TODO set per stream values instead of connection-wide - -func (s *Stream) SetDeadline(t time.Time) error { - return s.conn.conn.SetDeadline(t) -} - -func (s *Stream) SetReadDeadline(t time.Time) error { - return s.conn.conn.SetReadDeadline(t) -} - -func (s *Stream) SetWriteDeadline(t time.Time) error { - return s.conn.conn.SetWriteDeadline(t) -} - -func (s *Stream) closeRemoteChannels() { - s.closeLock.Lock() - defer s.closeLock.Unlock() - select { - case <-s.closeChan: - default: - close(s.closeChan) - } -} diff --git a/vendor/github.com/moby/spdystream/utils.go b/vendor/github.com/moby/spdystream/utils.go deleted file mode 100644 index e9f7fffd606..00000000000 --- a/vendor/github.com/moby/spdystream/utils.go +++ /dev/null @@ -1,32 +0,0 @@ -/* - Copyright 2014-2021 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. -*/ - -package spdystream - -import ( - "log" - "os" -) - -var ( - DEBUG = os.Getenv("DEBUG") -) - -func debugMessage(fmt string, args ...interface{}) { - if DEBUG != "" { - log.Printf(fmt, args...) - } -} diff --git a/vendor/github.com/moby/term/.gitignore b/vendor/github.com/moby/term/.gitignore deleted file mode 100644 index b0747ff010a..00000000000 --- a/vendor/github.com/moby/term/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# if you want to ignore files created by your editor/tools, consider using a -# global .gitignore or .git/info/exclude see https://help.github.com/articles/ignoring-files -.* -!.github -!.gitignore -profile.out -# support running go modules in vendor mode for local development -vendor/ diff --git a/vendor/github.com/moby/term/LICENSE b/vendor/github.com/moby/term/LICENSE deleted file mode 100644 index 6d8d58fb676..00000000000 --- a/vendor/github.com/moby/term/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/moby/term/README.md b/vendor/github.com/moby/term/README.md deleted file mode 100644 index 0ce92cc3398..00000000000 --- a/vendor/github.com/moby/term/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# term - utilities for dealing with terminals - -![Test](https://github.com/moby/term/workflows/Test/badge.svg) [![GoDoc](https://godoc.org/github.com/moby/term?status.svg)](https://godoc.org/github.com/moby/term) [![Go Report Card](https://goreportcard.com/badge/github.com/moby/term)](https://goreportcard.com/report/github.com/moby/term) - -term provides structures and helper functions to work with terminal (state, sizes). - -#### Using term - -```go -package main - -import ( - "log" - "os" - - "github.com/moby/term" -) - -func main() { - fd := os.Stdin.Fd() - if term.IsTerminal(fd) { - ws, err := term.GetWinsize(fd) - if err != nil { - log.Fatalf("term.GetWinsize: %s", err) - } - log.Printf("%d:%d\n", ws.Height, ws.Width) - } -} -``` - -## Contributing - -Want to hack on term? [Docker's contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md) apply. - -## Copyright and license -Code and documentation copyright 2015 Docker, inc. Code released under the Apache 2.0 license. Docs released under Creative commons. diff --git a/vendor/github.com/moby/term/ascii.go b/vendor/github.com/moby/term/ascii.go deleted file mode 100644 index 55873c0556c..00000000000 --- a/vendor/github.com/moby/term/ascii.go +++ /dev/null @@ -1,66 +0,0 @@ -package 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/moby/term/proxy.go b/vendor/github.com/moby/term/proxy.go deleted file mode 100644 index c47756b89a9..00000000000 --- a/vendor/github.com/moby/term/proxy.go +++ /dev/null @@ -1,88 +0,0 @@ -package 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 - buf []byte -} - -// 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) (n int, err error) { - if len(r.escapeKeys) > 0 && r.escapeKeyPos == len(r.escapeKeys) { - return 0, EscapeError{} - } - - if len(r.buf) > 0 { - n = copy(buf, r.buf) - r.buf = r.buf[n:] - } - - nr, err := r.r.Read(buf[n:]) - n += nr - if len(r.escapeKeys) == 0 { - return n, err - } - - for i := 0; i < n; i++ { - if buf[i] == r.escapeKeys[r.escapeKeyPos] { - r.escapeKeyPos++ - - // Check if the full escape sequence is matched. - if r.escapeKeyPos == len(r.escapeKeys) { - n = i + 1 - r.escapeKeyPos - if n < 0 { - n = 0 - } - return n, EscapeError{} - } - continue - } - - // If we need to prepend a partial escape sequence from the previous - // read, make sure the new buffer size doesn't exceed len(buf). - // Otherwise, preserve any extra data in a buffer for the next read. - if i < r.escapeKeyPos { - preserve := make([]byte, 0, r.escapeKeyPos+n) - preserve = append(preserve, r.escapeKeys[:r.escapeKeyPos]...) - preserve = append(preserve, buf[:n]...) - n = copy(buf, preserve) - i += r.escapeKeyPos - r.buf = append(r.buf, preserve[n:]...) - } - r.escapeKeyPos = 0 - } - - // If we're in the middle of reading an escape sequence, make sure we don't - // let the caller read it. If later on we find that this is not the escape - // sequence, we'll prepend it back to buf. - n -= r.escapeKeyPos - if n < 0 { - n = 0 - } - return n, err -} diff --git a/vendor/github.com/moby/term/tc.go b/vendor/github.com/moby/term/tc.go deleted file mode 100644 index 65556027a6d..00000000000 --- a/vendor/github.com/moby/term/tc.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build !windows - -package term - -import ( - "golang.org/x/sys/unix" -) - -func tcget(fd uintptr) (*Termios, error) { - p, err := unix.IoctlGetTermios(int(fd), getTermios) - if err != nil { - return nil, err - } - return p, nil -} - -func tcset(fd uintptr, p *Termios) error { - return unix.IoctlSetTermios(int(fd), setTermios, p) -} diff --git a/vendor/github.com/moby/term/term.go b/vendor/github.com/moby/term/term.go deleted file mode 100644 index 29c6acf1c7e..00000000000 --- a/vendor/github.com/moby/term/term.go +++ /dev/null @@ -1,120 +0,0 @@ -// +build !windows - -// Package term provides structures and helper functions to work with -// terminal (state, sizes). -package 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 { - _, err := tcget(fd) - return err == nil -} - -// 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 - } - return tcset(fd, &state.termios) -} - -// SaveState saves the state of the terminal connected to the given file descriptor. -func SaveState(fd uintptr) (*State, error) { - termios, err := tcget(fd) - if err != nil { - return nil, err - } - return &State{termios: *termios}, 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 != nil { - 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/moby/term/term_windows.go b/vendor/github.com/moby/term/term_windows.go deleted file mode 100644 index ba82960d4a6..00000000000 --- a/vendor/github.com/moby/term/term_windows.go +++ /dev/null @@ -1,231 +0,0 @@ -package term - -import ( - "io" - "os" - "os/signal" - - windowsconsole "github.com/moby/term/windows" - "golang.org/x/sys/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 - - mode uint32 - ) - - fd := windows.Handle(os.Stdin.Fd()) - if err := windows.GetConsoleMode(fd, &mode); err == nil { - // Validate that winterm.ENABLE_VIRTUAL_TERMINAL_INPUT is supported, but do not set it. - if err = windows.SetConsoleMode(fd, mode|windows.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. - _ = windows.SetConsoleMode(fd, mode) - } - - fd = windows.Handle(os.Stdout.Fd()) - if err := windows.GetConsoleMode(fd, &mode); err == nil { - // Validate winterm.DISABLE_NEWLINE_AUTO_RETURN is supported, but do not set it. - if err = windows.SetConsoleMode(fd, mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING|windows.DISABLE_NEWLINE_AUTO_RETURN); err != nil { - emulateStdout = true - } else { - _ = windows.SetConsoleMode(fd, mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING) - } - } - - fd = windows.Handle(os.Stderr.Fd()) - if err := windows.GetConsoleMode(fd, &mode); err == nil { - // Validate winterm.DISABLE_NEWLINE_AUTO_RETURN is supported, but do not set it. - if err = windows.SetConsoleMode(fd, mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING|windows.DISABLE_NEWLINE_AUTO_RETURN); err != nil { - emulateStderr = true - } else { - _ = windows.SetConsoleMode(fd, mode|windows.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 { - h := uint32(windows.STD_INPUT_HANDLE) - stdIn = windowsconsole.NewAnsiReader(int(h)) - } else { - stdIn = os.Stdin - } - - if emulateStdout { - h := uint32(windows.STD_OUTPUT_HANDLE) - stdOut = windowsconsole.NewAnsiWriter(int(h)) - } else { - stdOut = os.Stdout - } - - if emulateStderr { - h := uint32(windows.STD_ERROR_HANDLE) - stdErr = windowsconsole.NewAnsiWriter(int(h)) - } 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) { - var info windows.ConsoleScreenBufferInfo - if err := windows.GetConsoleScreenBufferInfo(windows.Handle(fd), &info); 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 { - var mode uint32 - err := windows.GetConsoleMode(windows.Handle(fd), &mode) - return err == nil -} - -// RestoreTerminal restores the terminal connected to the given file descriptor -// to a previous state. -func RestoreTerminal(fd uintptr, state *State) error { - return windows.SetConsoleMode(windows.Handle(fd), state.mode) -} - -// SaveState saves the state of the terminal connected to the given file descriptor. -func SaveState(fd uintptr) (*State, error) { - var mode uint32 - - if err := windows.GetConsoleMode(windows.Handle(fd), &mode); err != nil { - return nil, err - } - - 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 &^= windows.ENABLE_ECHO_INPUT - mode |= windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT - err := windows.SetConsoleMode(windows.Handle(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. - _ = windows.SetConsoleMode(windows.Handle(fd), state.mode|windows.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 &^= windows.ENABLE_ECHO_INPUT - mode &^= windows.ENABLE_LINE_INPUT - mode &^= windows.ENABLE_MOUSE_INPUT - mode &^= windows.ENABLE_WINDOW_INPUT - mode &^= windows.ENABLE_PROCESSED_INPUT - - // Enable these modes - mode |= windows.ENABLE_EXTENDED_FLAGS - mode |= windows.ENABLE_INSERT_MODE - mode |= windows.ENABLE_QUICK_EDIT_MODE - if vtInputSupported { - mode |= windows.ENABLE_VIRTUAL_TERMINAL_INPUT - } - - err = windows.SetConsoleMode(windows.Handle(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/moby/term/termios.go b/vendor/github.com/moby/term/termios.go deleted file mode 100644 index 0f028e2273a..00000000000 --- a/vendor/github.com/moby/term/termios.go +++ /dev/null @@ -1,35 +0,0 @@ -// +build !windows - -package term - -import ( - "golang.org/x/sys/unix" -) - -// Termios is the Unix API for terminal I/O. -type Termios = unix.Termios - -// MakeRaw puts 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 := tcget(fd) - if err != nil { - return nil, err - } - - oldState := State{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 := tcset(fd, termios); err != nil { - return nil, err - } - return &oldState, nil -} diff --git a/vendor/github.com/moby/term/termios_bsd.go b/vendor/github.com/moby/term/termios_bsd.go deleted file mode 100644 index 922dd4baab0..00000000000 --- a/vendor/github.com/moby/term/termios_bsd.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build darwin freebsd openbsd netbsd - -package term - -import ( - "golang.org/x/sys/unix" -) - -const ( - getTermios = unix.TIOCGETA - setTermios = unix.TIOCSETA -) diff --git a/vendor/github.com/moby/term/termios_nonbsd.go b/vendor/github.com/moby/term/termios_nonbsd.go deleted file mode 100644 index 038fd61ba1e..00000000000 --- a/vendor/github.com/moby/term/termios_nonbsd.go +++ /dev/null @@ -1,12 +0,0 @@ -//+build !darwin,!freebsd,!netbsd,!openbsd,!windows - -package term - -import ( - "golang.org/x/sys/unix" -) - -const ( - getTermios = unix.TCGETS - setTermios = unix.TCSETS -) diff --git a/vendor/github.com/moby/term/windows/ansi_reader.go b/vendor/github.com/moby/term/windows/ansi_reader.go deleted file mode 100644 index 155251521b0..00000000000 --- a/vendor/github.com/moby/term/windows/ansi_reader.go +++ /dev/null @@ -1,252 +0,0 @@ -// +build windows - -package windowsconsole - -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 { - 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 { - 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:] - } - - return copiedLength, nil - } - - // Read and translate key events - events, err := readInputEvents(ar, len(p)) - if err != nil { - return 0, err - } else if len(events) == 0 { - return 0, nil - } - - keyBytes := translateKeyEvents(events, []byte(escapeSequence)) - - // Save excess bytes and right-size keyBytes - if len(keyBytes) > len(p) { - ar.buffer = keyBytes[len(p):] - keyBytes = keyBytes[:len(p)] - } else if len(keyBytes) == 0 { - return 0, nil - } - - copiedLength := copy(p, keyBytes) - if copiedLength != len(keyBytes) { - return 0, errors.New("unexpected copy length encountered") - } - - return copiedLength, nil -} - -// readInputEvents polls until at least one event is available. -func readInputEvents(ar *ansiReader, 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 - } - - // Wait for and read input events - events := make([]winterm.INPUT_RECORD, countRecords) - nEvents := uint32(0) - eventsExist, err := winterm.WaitForSingleObject(ar.fd, winterm.WAIT_INFINITE) - if err != nil { - return nil, err - } - - if eventsExist { - err = winterm.ReadConsoleInput(ar.fd, events, &nEvents) - if err != nil { - return nil, err - } - } - - // Return a slice restricted to the number of returned records - 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/moby/term/windows/ansi_writer.go b/vendor/github.com/moby/term/windows/ansi_writer.go deleted file mode 100644 index ccb5ef07757..00000000000 --- a/vendor/github.com/moby/term/windows/ansi_writer.go +++ /dev/null @@ -1,56 +0,0 @@ -// +build windows - -package windowsconsole - -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 { - file, fd := winterm.GetStdFile(nFile) - info, err := winterm.GetConsoleScreenBufferInfo(fd) - if err != nil { - return nil - } - - parser := ansiterm.CreateParser("Ground", winterm.CreateWinEventHandler(fd, file)) - - return &ansiWriter{ - file: file, - fd: fd, - infoReset: info, - command: make([]byte, 0, ansiterm.ANSI_MAX_CMD_LENGTH), - escapeSequence: []byte(ansiterm.KEY_ESC_CSI), - parser: parser, - } -} - -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 - } - - return aw.parser.Parse(p) -} diff --git a/vendor/github.com/moby/term/windows/console.go b/vendor/github.com/moby/term/windows/console.go deleted file mode 100644 index 993694ddcd9..00000000000 --- a/vendor/github.com/moby/term/windows/console.go +++ /dev/null @@ -1,39 +0,0 @@ -// +build windows - -package windowsconsole - -import ( - "os" - - "golang.org/x/sys/windows" -) - -// 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. -// Deprecated: use golang.org/x/sys/windows.GetConsoleMode() or golang.org/x/term.IsTerminal() -var IsConsole = isConsole - -func isConsole(fd uintptr) bool { - var mode uint32 - err := windows.GetConsoleMode(windows.Handle(fd), &mode) - return err == nil -} diff --git a/vendor/github.com/moby/term/windows/doc.go b/vendor/github.com/moby/term/windows/doc.go deleted file mode 100644 index 54265fffaff..00000000000 --- a/vendor/github.com/moby/term/windows/doc.go +++ /dev/null @@ -1,5 +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 diff --git a/vendor/github.com/moby/term/winsize.go b/vendor/github.com/moby/term/winsize.go deleted file mode 100644 index 1ef98d59961..00000000000 --- a/vendor/github.com/moby/term/winsize.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build !windows - -package 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/modern-go/reflect2/.travis.yml b/vendor/github.com/modern-go/reflect2/.travis.yml index fbb43744d94..b097728dbff 100644 --- a/vendor/github.com/modern-go/reflect2/.travis.yml +++ b/vendor/github.com/modern-go/reflect2/.travis.yml @@ -1,7 +1,7 @@ language: go go: - - 1.8.x + - 1.9.x - 1.x before_install: diff --git a/vendor/github.com/modern-go/reflect2/Gopkg.lock b/vendor/github.com/modern-go/reflect2/Gopkg.lock index 2a3a69893b5..10ef811182d 100644 --- a/vendor/github.com/modern-go/reflect2/Gopkg.lock +++ b/vendor/github.com/modern-go/reflect2/Gopkg.lock @@ -1,15 +1,9 @@ # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. -[[projects]] - name = "github.com/modern-go/concurrent" - packages = ["."] - revision = "e0a39a4cb4216ea8db28e22a69f4ec25610d513a" - version = "1.0.0" - [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "daee8a88b3498b61c5640056665b8b9eea062006f5e596bbb6a3ed9119a11ec7" + input-imports = [] solver-name = "gps-cdcl" solver-version = 1 diff --git a/vendor/github.com/modern-go/reflect2/Gopkg.toml b/vendor/github.com/modern-go/reflect2/Gopkg.toml index 2f4f4dbdcc5..a9bc5061b04 100644 --- a/vendor/github.com/modern-go/reflect2/Gopkg.toml +++ b/vendor/github.com/modern-go/reflect2/Gopkg.toml @@ -26,10 +26,6 @@ ignored = [] -[[constraint]] - name = "github.com/modern-go/concurrent" - version = "1.0.0" - [prune] go-tests = true unused-packages = true diff --git a/vendor/github.com/modern-go/reflect2/go_above_118.go b/vendor/github.com/modern-go/reflect2/go_above_118.go new file mode 100644 index 00000000000..2b4116f6c9b --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/go_above_118.go @@ -0,0 +1,23 @@ +//+build go1.18 + +package reflect2 + +import ( + "unsafe" +) + +// m escapes into the return value, but the caller of mapiterinit +// doesn't let the return value escape. +//go:noescape +//go:linkname mapiterinit reflect.mapiterinit +func mapiterinit(rtype unsafe.Pointer, m unsafe.Pointer, it *hiter) + +func (type2 *UnsafeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { + var it hiter + mapiterinit(type2.rtype, *(*unsafe.Pointer)(obj), &it) + return &UnsafeMapIterator{ + hiter: &it, + pKeyRType: type2.pKeyRType, + pElemRType: type2.pElemRType, + } +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/go_above_17.go b/vendor/github.com/modern-go/reflect2/go_above_17.go deleted file mode 100644 index 5c1cea8683a..00000000000 --- a/vendor/github.com/modern-go/reflect2/go_above_17.go +++ /dev/null @@ -1,8 +0,0 @@ -//+build go1.7 - -package reflect2 - -import "unsafe" - -//go:linkname resolveTypeOff reflect.resolveTypeOff -func resolveTypeOff(rtype unsafe.Pointer, off int32) unsafe.Pointer diff --git a/vendor/github.com/modern-go/reflect2/go_above_19.go b/vendor/github.com/modern-go/reflect2/go_above_19.go index c7e3b780116..974f7685e49 100644 --- a/vendor/github.com/modern-go/reflect2/go_above_19.go +++ b/vendor/github.com/modern-go/reflect2/go_above_19.go @@ -6,6 +6,9 @@ import ( "unsafe" ) +//go:linkname resolveTypeOff reflect.resolveTypeOff +func resolveTypeOff(rtype unsafe.Pointer, off int32) unsafe.Pointer + //go:linkname makemap reflect.makemap func makemap(rtype unsafe.Pointer, cap int) (m unsafe.Pointer) diff --git a/vendor/github.com/modern-go/reflect2/go_below_118.go b/vendor/github.com/modern-go/reflect2/go_below_118.go new file mode 100644 index 00000000000..00003dbd7c5 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/go_below_118.go @@ -0,0 +1,21 @@ +//+build !go1.18 + +package reflect2 + +import ( + "unsafe" +) + +// m escapes into the return value, but the caller of mapiterinit +// doesn't let the return value escape. +//go:noescape +//go:linkname mapiterinit reflect.mapiterinit +func mapiterinit(rtype unsafe.Pointer, m unsafe.Pointer) (val *hiter) + +func (type2 *UnsafeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { + return &UnsafeMapIterator{ + hiter: mapiterinit(type2.rtype, *(*unsafe.Pointer)(obj)), + pKeyRType: type2.pKeyRType, + pElemRType: type2.pElemRType, + } +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/go_below_17.go b/vendor/github.com/modern-go/reflect2/go_below_17.go deleted file mode 100644 index 65a93c889b7..00000000000 --- a/vendor/github.com/modern-go/reflect2/go_below_17.go +++ /dev/null @@ -1,9 +0,0 @@ -//+build !go1.7 - -package reflect2 - -import "unsafe" - -func resolveTypeOff(rtype unsafe.Pointer, off int32) unsafe.Pointer { - return nil -} diff --git a/vendor/github.com/modern-go/reflect2/go_below_19.go b/vendor/github.com/modern-go/reflect2/go_below_19.go deleted file mode 100644 index b050ef70cdd..00000000000 --- a/vendor/github.com/modern-go/reflect2/go_below_19.go +++ /dev/null @@ -1,14 +0,0 @@ -//+build !go1.9 - -package reflect2 - -import ( - "unsafe" -) - -//go:linkname makemap reflect.makemap -func makemap(rtype unsafe.Pointer) (m unsafe.Pointer) - -func makeMapWithSize(rtype unsafe.Pointer, cap int) unsafe.Pointer { - return makemap(rtype) -} diff --git a/vendor/github.com/modern-go/reflect2/reflect2.go b/vendor/github.com/modern-go/reflect2/reflect2.go index 63b49c79919..c43c8b9d629 100644 --- a/vendor/github.com/modern-go/reflect2/reflect2.go +++ b/vendor/github.com/modern-go/reflect2/reflect2.go @@ -1,8 +1,9 @@ package reflect2 import ( - "github.com/modern-go/concurrent" "reflect" + "runtime" + "sync" "unsafe" ) @@ -130,13 +131,13 @@ var ConfigSafe = Config{UseSafeImplementation: true}.Froze() type frozenConfig struct { useSafeImplementation bool - cache *concurrent.Map + cache *sync.Map } func (cfg Config) Froze() *frozenConfig { return &frozenConfig{ useSafeImplementation: cfg.UseSafeImplementation, - cache: concurrent.NewMap(), + cache: new(sync.Map), } } @@ -288,11 +289,12 @@ func NoEscape(p unsafe.Pointer) unsafe.Pointer { } func UnsafeCastString(str string) []byte { + bytes := make([]byte, 0) stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&str)) - sliceHeader := &reflect.SliceHeader{ - Data: stringHeader.Data, - Cap: stringHeader.Len, - Len: stringHeader.Len, - } - return *(*[]byte)(unsafe.Pointer(sliceHeader)) + sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&bytes)) + sliceHeader.Data = stringHeader.Data + sliceHeader.Cap = stringHeader.Len + sliceHeader.Len = stringHeader.Len + runtime.KeepAlive(str) + return bytes } diff --git a/vendor/github.com/modern-go/reflect2/test.sh b/vendor/github.com/modern-go/reflect2/test.sh deleted file mode 100644 index 3d2b9768ce6..00000000000 --- a/vendor/github.com/modern-go/reflect2/test.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash - -set -e -echo "" > coverage.txt - -for d in $(go list github.com/modern-go/reflect2-tests/... | grep -v vendor); do - go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d - if [ -f profile.out ]; then - cat profile.out >> coverage.txt - rm profile.out - fi -done diff --git a/vendor/github.com/modern-go/reflect2/type_map.go b/vendor/github.com/modern-go/reflect2/type_map.go index 3acfb55803a..4b13c3155c8 100644 --- a/vendor/github.com/modern-go/reflect2/type_map.go +++ b/vendor/github.com/modern-go/reflect2/type_map.go @@ -1,17 +1,13 @@ +// +build !gccgo + package reflect2 import ( "reflect" - "runtime" - "strings" "sync" "unsafe" ) -// typelinks1 for 1.5 ~ 1.6 -//go:linkname typelinks1 reflect.typelinks -func typelinks1() [][]unsafe.Pointer - // typelinks2 for 1.7 ~ //go:linkname typelinks2 reflect.typelinks func typelinks2() (sections []unsafe.Pointer, offset [][]int32) @@ -27,49 +23,10 @@ func discoverTypes() { types = make(map[string]reflect.Type) packages = make(map[string]map[string]reflect.Type) - ver := runtime.Version() - if ver == "go1.5" || strings.HasPrefix(ver, "go1.5.") { - loadGo15Types() - } else if ver == "go1.6" || strings.HasPrefix(ver, "go1.6.") { - loadGo15Types() - } else { - loadGo17Types() - } -} - -func loadGo15Types() { - var obj interface{} = reflect.TypeOf(0) - typePtrss := typelinks1() - for _, typePtrs := range typePtrss { - for _, typePtr := range typePtrs { - (*emptyInterface)(unsafe.Pointer(&obj)).word = typePtr - typ := obj.(reflect.Type) - if typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Struct { - loadedType := typ.Elem() - pkgTypes := packages[loadedType.PkgPath()] - if pkgTypes == nil { - pkgTypes = map[string]reflect.Type{} - packages[loadedType.PkgPath()] = pkgTypes - } - types[loadedType.String()] = loadedType - pkgTypes[loadedType.Name()] = loadedType - } - if typ.Kind() == reflect.Slice && typ.Elem().Kind() == reflect.Ptr && - typ.Elem().Elem().Kind() == reflect.Struct { - loadedType := typ.Elem().Elem() - pkgTypes := packages[loadedType.PkgPath()] - if pkgTypes == nil { - pkgTypes = map[string]reflect.Type{} - packages[loadedType.PkgPath()] = pkgTypes - } - types[loadedType.String()] = loadedType - pkgTypes[loadedType.Name()] = loadedType - } - } - } + loadGoTypes() } -func loadGo17Types() { +func loadGoTypes() { var obj interface{} = reflect.TypeOf(0) sections, offset := typelinks2() for i, offs := range offset { diff --git a/vendor/github.com/modern-go/reflect2/unsafe_link.go b/vendor/github.com/modern-go/reflect2/unsafe_link.go index 57229c8db41..b49f614efc5 100644 --- a/vendor/github.com/modern-go/reflect2/unsafe_link.go +++ b/vendor/github.com/modern-go/reflect2/unsafe_link.go @@ -19,18 +19,12 @@ func typedslicecopy(elemType unsafe.Pointer, dst, src sliceHeader) int //go:linkname mapassign reflect.mapassign //go:noescape -func mapassign(rtype unsafe.Pointer, m unsafe.Pointer, key, val unsafe.Pointer) +func mapassign(rtype unsafe.Pointer, m unsafe.Pointer, key unsafe.Pointer, val unsafe.Pointer) //go:linkname mapaccess reflect.mapaccess //go:noescape func mapaccess(rtype unsafe.Pointer, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer) -// m escapes into the return value, but the caller of mapiterinit -// doesn't let the return value escape. -//go:noescape -//go:linkname mapiterinit reflect.mapiterinit -func mapiterinit(rtype unsafe.Pointer, m unsafe.Pointer) *hiter - //go:noescape //go:linkname mapiternext reflect.mapiternext func mapiternext(it *hiter) @@ -42,9 +36,21 @@ func ifaceE2I(rtype unsafe.Pointer, src interface{}, dst unsafe.Pointer) // If you modify hiter, also change cmd/internal/gc/reflect.go to indicate // the layout of this structure. type hiter struct { - key unsafe.Pointer // Must be in first position. Write nil to indicate iteration end (see cmd/internal/gc/range.go). - value unsafe.Pointer // Must be in second position (see cmd/internal/gc/range.go). - // rest fields are ignored + key unsafe.Pointer + value unsafe.Pointer + t unsafe.Pointer + h unsafe.Pointer + buckets unsafe.Pointer + bptr unsafe.Pointer + overflow *[]unsafe.Pointer + oldoverflow *[]unsafe.Pointer + startBucket uintptr + offset uint8 + wrapped bool + B uint8 + i uint8 + bucket uintptr + checkBucket uintptr } // add returns p+x. diff --git a/vendor/github.com/modern-go/reflect2/unsafe_map.go b/vendor/github.com/modern-go/reflect2/unsafe_map.go index f2e76e6bb14..37872da8191 100644 --- a/vendor/github.com/modern-go/reflect2/unsafe_map.go +++ b/vendor/github.com/modern-go/reflect2/unsafe_map.go @@ -107,14 +107,6 @@ func (type2 *UnsafeMapType) Iterate(obj interface{}) MapIterator { return type2.UnsafeIterate(objEFace.data) } -func (type2 *UnsafeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { - return &UnsafeMapIterator{ - hiter: mapiterinit(type2.rtype, *(*unsafe.Pointer)(obj)), - pKeyRType: type2.pKeyRType, - pElemRType: type2.pElemRType, - } -} - type UnsafeMapIterator struct { *hiter pKeyRType unsafe.Pointer diff --git a/vendor/github.com/monochromegane/go-gitignore/.travis.yml b/vendor/github.com/monochromegane/go-gitignore/.travis.yml deleted file mode 100644 index b06a36a466e..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: go -go: - - 1.14.x - - master -script: - - go test -v ./... diff --git a/vendor/github.com/monochromegane/go-gitignore/LICENSE b/vendor/github.com/monochromegane/go-gitignore/LICENSE deleted file mode 100644 index 91b84e92778..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) [2015] [go-gitignore] - -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/monochromegane/go-gitignore/README.md b/vendor/github.com/monochromegane/go-gitignore/README.md deleted file mode 100644 index 51a480747b0..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/README.md +++ /dev/null @@ -1,95 +0,0 @@ -# go-gitignore [![Build Status](https://travis-ci.org/monochromegane/go-gitignore.svg)](https://travis-ci.org/monochromegane/go-gitignore) - -A fast gitignore matching library for Go. - -This library use simple tree index for matching, so keep fast if gitignore file has many pattern. - -## Usage - -```go -gitignore, _ := gitignore.NewGitIgnore("/path/to/gitignore") - -path := "/path/to/file" -isDir := false -gitignore.Match(path, isDir) -``` - -### Specify base directory - -go-gitignore treat `path` as a base directory. -If you want to specify other base (e.g. current directory and Global gitignore), you can like the following. - -```go -gitignore, _ := gitignore.NewGitIgnore("/home/you/.gitignore", ".") -``` - -### From io.Reader - -go-gitignore can initialize from io.Reader. - -```go -gitignore, _ := gitignore.NewGitIgnoreFromReader(base, reader) -``` - -## Simple tree index - -go-gitignore parse gitignore file, and generate a simple tree index for matching like the following. - -``` -. -├── accept -│   ├── absolute -│   │   └── depth -│   │   ├── initial -│   │   └── other -│   └── relative -│   └── depth -│   ├── initial -│   └── other -└── ignore - ├── absolute - │   └── depth - │   ├── initial - │   └── other - └── relative - └── depth - ├── initial - └── other -``` - -## Features - -- Support absolute path (/path/to/ignore) -- Support relative path (path/to/ignore) -- Support accept pattern (!path/to/accept) -- Support directory pattern (path/to/directory/) -- Support glob pattern (path/to/\*.txt) - -*note: glob pattern* - -go-gitignore use [filepath.Match](https://golang.org/pkg/path/filepath/#Match) for matching meta char pattern, so not support recursive pattern (path/`**`/file). - -## Installation - -```sh -$ go get github.com/monochromegane/go-gitignore -``` - -## Contribution - -1. Fork it -2. Create a feature branch -3. Commit your changes -4. Rebase your local changes against the master branch -5. Run test suite with the `go test ./...` command and confirm that it passes -6. Run `gofmt -s` -7. Create new Pull Request - -## License - -[MIT](https://github.com/monochromegane/go-gitignore/blob/master/LICENSE) - -## Author - -[monochromegane](https://github.com/monochromegane) - diff --git a/vendor/github.com/monochromegane/go-gitignore/depth_holder.go b/vendor/github.com/monochromegane/go-gitignore/depth_holder.go deleted file mode 100644 index 9805b325d41..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/depth_holder.go +++ /dev/null @@ -1,79 +0,0 @@ -package gitignore - -import "strings" - -const ( - asc = iota - desc -) - -type depthPatternHolder struct { - patterns depthPatterns - order int -} - -func newDepthPatternHolder(order int) depthPatternHolder { - return depthPatternHolder{ - patterns: depthPatterns{m: map[int]initialPatternHolder{}}, - order: order, - } -} - -func (h *depthPatternHolder) add(pattern string) { - count := strings.Count(strings.Trim(pattern, "/"), "/") - h.patterns.set(count+1, pattern) -} - -func (h depthPatternHolder) match(path string, isDir bool) bool { - if h.patterns.size() == 0 { - return false - } - - for depth := 1; ; depth++ { - var part string - var isLast, isDirCurrent bool - if h.order == asc { - part, isLast = cutN(path, depth) - if isLast { - isDirCurrent = isDir - } else { - isDirCurrent = false - } - } else { - part, isLast = cutLastN(path, depth) - isDirCurrent = isDir - } - if patterns, ok := h.patterns.get(depth); ok { - if patterns.match(part, isDirCurrent) { - return true - } - } - if isLast { - break - } - } - return false -} - -type depthPatterns struct { - m map[int]initialPatternHolder -} - -func (p *depthPatterns) set(depth int, pattern string) { - if ps, ok := p.m[depth]; ok { - ps.add(pattern) - } else { - holder := newInitialPatternHolder() - holder.add(pattern) - p.m[depth] = holder - } -} - -func (p depthPatterns) get(depth int) (initialPatternHolder, bool) { - patterns, ok := p.m[depth] - return patterns, ok -} - -func (p depthPatterns) size() int { - return len(p.m) -} diff --git a/vendor/github.com/monochromegane/go-gitignore/full_scan_patterns.go b/vendor/github.com/monochromegane/go-gitignore/full_scan_patterns.go deleted file mode 100644 index 8c04ef3a77d..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/full_scan_patterns.go +++ /dev/null @@ -1,31 +0,0 @@ -package gitignore - -import "strings" - -// Only benchmark use -type fullScanPatterns struct { - absolute patterns - relative patterns -} - -func newFullScanPatterns() *fullScanPatterns { - return &fullScanPatterns{ - absolute: patterns{}, - relative: patterns{}, - } -} - -func (ps *fullScanPatterns) add(pattern string) { - if strings.HasPrefix(pattern, "/") { - ps.absolute.add(newPattern(pattern)) - } else { - ps.relative.add(newPattern(pattern)) - } -} - -func (ps fullScanPatterns) match(path string, isDir bool) bool { - if ps.absolute.match(path, isDir) { - return true - } - return ps.relative.match(path, isDir) -} diff --git a/vendor/github.com/monochromegane/go-gitignore/gitignore.go b/vendor/github.com/monochromegane/go-gitignore/gitignore.go deleted file mode 100644 index 9c719a6caba..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/gitignore.go +++ /dev/null @@ -1,80 +0,0 @@ -package gitignore - -import ( - "bufio" - "io" - "os" - "path/filepath" - "strings" -) - -type IgnoreMatcher interface { - Match(path string, isDir bool) bool -} - -type DummyIgnoreMatcher bool - -func (d DummyIgnoreMatcher) Match(path string, isDir bool) bool { - return bool(d) -} - -type gitIgnore struct { - ignorePatterns scanStrategy - acceptPatterns scanStrategy - path string -} - -func NewGitIgnore(gitignore string, base ...string) (IgnoreMatcher, error) { - var path string - if len(base) > 0 { - path = base[0] - } else { - path = filepath.Dir(gitignore) - } - - file, err := os.Open(gitignore) - if err != nil { - return nil, err - } - defer file.Close() - - return NewGitIgnoreFromReader(path, file), nil -} - -func NewGitIgnoreFromReader(path string, r io.Reader) IgnoreMatcher { - g := gitIgnore{ - ignorePatterns: newIndexScanPatterns(), - acceptPatterns: newIndexScanPatterns(), - path: path, - } - scanner := bufio.NewScanner(r) - for scanner.Scan() { - line := strings.Trim(scanner.Text(), " ") - if len(line) == 0 || strings.HasPrefix(line, "#") { - continue - } - if strings.HasPrefix(line, `\#`) { - line = strings.TrimPrefix(line, `\`) - } - - if strings.HasPrefix(line, "!") { - g.acceptPatterns.add(strings.TrimPrefix(line, "!")) - } else { - g.ignorePatterns.add(line) - } - } - return g -} - -func (g gitIgnore) Match(path string, isDir bool) bool { - relativePath, err := filepath.Rel(g.path, path) - if err != nil { - return false - } - relativePath = filepath.ToSlash(relativePath) - - if g.acceptPatterns.match(relativePath, isDir) { - return false - } - return g.ignorePatterns.match(relativePath, isDir) -} diff --git a/vendor/github.com/monochromegane/go-gitignore/index_scan_patterns.go b/vendor/github.com/monochromegane/go-gitignore/index_scan_patterns.go deleted file mode 100644 index 882280e9530..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/index_scan_patterns.go +++ /dev/null @@ -1,35 +0,0 @@ -package gitignore - -import "strings" - -type indexScanPatterns struct { - absolute depthPatternHolder - relative depthPatternHolder -} - -func newIndexScanPatterns() *indexScanPatterns { - return &indexScanPatterns{ - absolute: newDepthPatternHolder(asc), - relative: newDepthPatternHolder(desc), - } -} - -func (ps *indexScanPatterns) add(pattern string) { - if strings.HasPrefix(pattern, "/") { - ps.absolute.add(pattern) - } else { - ps.relative.add(pattern) - } -} - -func (ps indexScanPatterns) match(path string, isDir bool) bool { - if ps.absolute.match(path, isDir) { - return true - } - return ps.relative.match(path, isDir) -} - -type scanStrategy interface { - add(pattern string) - match(path string, isDir bool) bool -} diff --git a/vendor/github.com/monochromegane/go-gitignore/initial_holder.go b/vendor/github.com/monochromegane/go-gitignore/initial_holder.go deleted file mode 100644 index 86f0bfee2be..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/initial_holder.go +++ /dev/null @@ -1,62 +0,0 @@ -package gitignore - -import "strings" - -const initials = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ." - -type initialPatternHolder struct { - patterns initialPatterns - otherPatterns *patterns -} - -func newInitialPatternHolder() initialPatternHolder { - return initialPatternHolder{ - patterns: initialPatterns{m: map[byte]*patterns{}}, - otherPatterns: &patterns{}, - } -} - -func (h *initialPatternHolder) add(pattern string) { - trimedPattern := strings.TrimPrefix(pattern, "/") - if strings.IndexAny(trimedPattern[0:1], initials) != -1 { - h.patterns.set(trimedPattern[0], newPatternForEqualizedPath(pattern)) - } else { - h.otherPatterns.add(newPatternForEqualizedPath(pattern)) - } -} - -func (h initialPatternHolder) match(path string, isDir bool) bool { - if h.patterns.size() == 0 && h.otherPatterns.size() == 0 { - return false - } - if patterns, ok := h.patterns.get(path[0]); ok { - if patterns.match(path, isDir) { - return true - } - } - return h.otherPatterns.match(path, isDir) -} - -type initialPatterns struct { - m map[byte]*patterns -} - -func (p *initialPatterns) set(initial byte, pattern pattern) { - if ps, ok := p.m[initial]; ok { - ps.add(pattern) - } else { - patterns := &patterns{} - patterns.add(pattern) - p.m[initial] = patterns - - } -} - -func (p initialPatterns) get(initial byte) (*patterns, bool) { - patterns, ok := p.m[initial] - return patterns, ok -} - -func (p initialPatterns) size() int { - return len(p.m) -} diff --git a/vendor/github.com/monochromegane/go-gitignore/match.go b/vendor/github.com/monochromegane/go-gitignore/match.go deleted file mode 100644 index 4140a9bdc52..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/match.go +++ /dev/null @@ -1,24 +0,0 @@ -package gitignore - -import "path/filepath" - -type pathMatcher interface { - match(path string) bool -} - -type simpleMatcher struct { - path string -} - -func (m simpleMatcher) match(path string) bool { - return m.path == path -} - -type filepathMatcher struct { - path string -} - -func (m filepathMatcher) match(path string) bool { - match, _ := filepath.Match(m.path, path) - return match -} diff --git a/vendor/github.com/monochromegane/go-gitignore/pattern.go b/vendor/github.com/monochromegane/go-gitignore/pattern.go deleted file mode 100644 index 93adbf76361..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/pattern.go +++ /dev/null @@ -1,69 +0,0 @@ -package gitignore - -import ( - "path/filepath" - "strings" -) - -var Separator = string(filepath.Separator) - -type pattern struct { - hasRootPrefix bool - hasDirSuffix bool - pathDepth int - matcher pathMatcher - onlyEqualizedPath bool -} - -func newPattern(path string) pattern { - hasRootPrefix := path[0] == '/' - hasDirSuffix := path[len(path)-1] == '/' - - var pathDepth int - if !hasRootPrefix { - pathDepth = strings.Count(path, "/") - } - - var matcher pathMatcher - matchingPath := strings.Trim(path, "/") - if hasMeta(path) { - matcher = filepathMatcher{path: matchingPath} - } else { - matcher = simpleMatcher{path: matchingPath} - } - - return pattern{ - hasRootPrefix: hasRootPrefix, - hasDirSuffix: hasDirSuffix, - pathDepth: pathDepth, - matcher: matcher, - } -} - -func newPatternForEqualizedPath(path string) pattern { - pattern := newPattern(path) - pattern.onlyEqualizedPath = true - return pattern -} - -func (p pattern) match(path string, isDir bool) bool { - - if p.hasDirSuffix && !isDir { - return false - } - - var targetPath string - if p.hasRootPrefix || p.onlyEqualizedPath { - // absolute pattern or only equalized path mode - targetPath = path - } else { - // relative pattern - targetPath = p.equalizeDepth(path) - } - return p.matcher.match(targetPath) -} - -func (p pattern) equalizeDepth(path string) string { - equalizedPath, _ := cutLastN(path, p.pathDepth+1) - return equalizedPath -} diff --git a/vendor/github.com/monochromegane/go-gitignore/patterns.go b/vendor/github.com/monochromegane/go-gitignore/patterns.go deleted file mode 100644 index 6770fb46558..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/patterns.go +++ /dev/null @@ -1,22 +0,0 @@ -package gitignore - -type patterns struct { - patterns []pattern -} - -func (ps *patterns) add(pattern pattern) { - ps.patterns = append(ps.patterns, pattern) -} - -func (ps *patterns) size() int { - return len(ps.patterns) -} - -func (ps patterns) match(path string, isDir bool) bool { - for _, p := range ps.patterns { - if match := p.match(path, isDir); match { - return true - } - } - return false -} diff --git a/vendor/github.com/monochromegane/go-gitignore/util.go b/vendor/github.com/monochromegane/go-gitignore/util.go deleted file mode 100644 index b5ab9bbfd24..00000000000 --- a/vendor/github.com/monochromegane/go-gitignore/util.go +++ /dev/null @@ -1,45 +0,0 @@ -package gitignore - -import ( - "os" - "strings" -) - -func cutN(path string, n int) (string, bool) { - isLast := true - - var i, count int - for i < len(path)-1 { - if os.IsPathSeparator(path[i]) { - count++ - if count >= n { - isLast = false - break - } - } - i++ - } - return path[:i+1], isLast -} - -func cutLastN(path string, n int) (string, bool) { - isLast := true - i := len(path) - 1 - - var count int - for i >= 0 { - if os.IsPathSeparator(path[i]) { - count++ - if count >= n { - isLast = false - break - } - } - i-- - } - return path[i+1:], isLast -} - -func hasMeta(path string) bool { - return strings.IndexAny(path, "*?[") >= 0 -} diff --git a/vendor/github.com/openshift/api/config/v1/0000_00_cluster-version-operator_01_clusterversion.crd.yaml b/vendor/github.com/openshift/api/config/v1/0000_00_cluster-version-operator_01_clusterversion.crd.yaml index 3e27d0e9b5a..477435fd617 100644 --- a/vendor/github.com/openshift/api/config/v1/0000_00_cluster-version-operator_01_clusterversion.crd.yaml +++ b/vendor/github.com/openshift/api/config/v1/0000_00_cluster-version-operator_01_clusterversion.crd.yaml @@ -238,7 +238,7 @@ spec: - promql properties: promql: - description: PromQL is a PromQL query classifying clusters. This query query should return a 1 in the match case and a 0 in the does-not-match case case. Queries which return no time series, or which return values besides 0 or 1, are evaluation failures. + description: PromQL is a PromQL query classifying clusters. This query query should return a 1 in the match case and a 0 in the does-not-match case. Queries which return no time series, or which return values besides 0 or 1, are evaluation failures. type: string type: description: type represents the cluster-condition type. This defines the members and semantics of any additional properties. diff --git a/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_infrastructure.crd.yaml b/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_infrastructure.crd.yaml index 43549229033..60b30a86562 100644 --- a/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_infrastructure.crd.yaml +++ b/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_infrastructure.crd.yaml @@ -98,6 +98,29 @@ spec: powervs: description: PowerVS contains settings specific to the IBM Power Systems Virtual Servers infrastructure provider. type: object + properties: + serviceEndpoints: + description: serviceEndpoints is a list of custom endpoints which will override the default service endpoints of a Power VS service. + type: array + items: + description: PowervsServiceEndpoint stores the configuration of a custom url to override existing defaults of PowerVS Services. + type: object + required: + - name + - url + properties: + name: + description: name is the name of the Power VS service. Few of the services are IAM - https://cloud.ibm.com/apidocs/iam-identity-token-api ResourceController - https://cloud.ibm.com/apidocs/resource-controller/resource-controller Power Cloud - https://cloud.ibm.com/apidocs/power-cloud + type: string + pattern: ^[a-z0-9-]+$ + url: + description: url is fully qualified URI with scheme https, that overrides the default generated endpoint for a client. This must be provided and cannot be empty. + type: string + format: uri + pattern: ^https:// + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map type: description: type is the underlying infrastructure provider for the cluster. This value controls whether infrastructure automation such as service load balancers, dynamic volume provisioning, machine creation and deletion, and other integrations are enabled. If None, no infrastructure automation is enabled. Allowed values are "AWS", "Azure", "BareMetal", "GCP", "Libvirt", "OpenStack", "VSphere", "oVirt", "KubeVirt", "EquinixMetal", "PowerVS", "AlibabaCloud" and "None". Individual components may not support all platforms, and must handle unrecognized platforms as None if they do not support that platform. type: string @@ -179,7 +202,6 @@ spec: type: object required: - region - - resourceGroupID properties: region: description: region specifies the region for Alibaba Cloud resources created for the cluster. @@ -390,7 +412,7 @@ spec: - url properties: name: - description: name is the name of the Power VS service. + description: name is the name of the Power VS service. Few of the services are IAM - https://cloud.ibm.com/apidocs/iam-identity-token-api ResourceController - https://cloud.ibm.com/apidocs/resource-controller/resource-controller Power Cloud - https://cloud.ibm.com/apidocs/power-cloud type: string pattern: ^[a-z0-9-]+$ url: diff --git a/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_network.crd.yaml b/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_network.crd.yaml index 0056dc60fac..c0117850619 100644 --- a/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_network.crd.yaml +++ b/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_network.crd.yaml @@ -113,6 +113,38 @@ spec: description: Migration contains the cluster network migration configuration. type: object properties: + mtu: + description: MTU contains the MTU migration configuration. + type: object + properties: + machine: + description: Machine contains MTU migration configuration for the machine's uplink. + type: object + properties: + from: + description: From is the MTU to migrate from. + type: integer + format: int32 + minimum: 0 + to: + description: To is the MTU to migrate to. + type: integer + format: int32 + minimum: 0 + network: + description: Network contains MTU migration configuration for the default network. + type: object + properties: + from: + description: From is the MTU to migrate from. + type: integer + format: int32 + minimum: 0 + to: + description: To is the MTU to migrate to. + type: integer + format: int32 + minimum: 0 networkType: description: 'NetworkType is the target plugin that is to be deployed. Currently supported values are: OpenShiftSDN, OVNKubernetes' type: string diff --git a/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_oauth.crd.yaml b/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_oauth.crd.yaml index bd1c8cde5f8..883c623b36f 100644 --- a/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_oauth.crd.yaml +++ b/vendor/github.com/openshift/api/config/v1/0000_10_config-operator_01_oauth.crd.yaml @@ -36,19 +36,6 @@ spec: description: spec holds user settable values for configuration type: object properties: - audit: - description: audit specifies what should be audited in the context of OAuthServer. By default the Audit is turned on. - type: object - default: - profile: WriteLoginEvents - properties: - profile: - description: profile is a simple drop in profile type that can be turned off by setting it to "None" or it can be turned on by setting it to "WriteLoginEvents". By default the profile is set to "WriteLoginEvents". - type: string - default: WriteLoginEvents - enum: - - None - - WriteLoginEvents identityProviders: description: identityProviders is an ordered list of ways for a user to identify themselves. When this list is empty, no identities are provisioned for users. type: array diff --git a/vendor/github.com/openshift/api/config/v1/types_cluster_version.go b/vendor/github.com/openshift/api/config/v1/types_cluster_version.go index d23f8ff3c28..44e8677789c 100644 --- a/vendor/github.com/openshift/api/config/v1/types_cluster_version.go +++ b/vendor/github.com/openshift/api/config/v1/types_cluster_version.go @@ -408,7 +408,7 @@ type ClusterCondition struct { type PromQLClusterCondition struct { // PromQL is a PromQL query classifying clusters. This query // query should return a 1 in the match case and a 0 in the - // does-not-match case case. Queries which return no time + // does-not-match case. Queries which return no time // series, or which return values besides 0 or 1, are // evaluation failures. // +kubebuilder:validation:Required diff --git a/vendor/github.com/openshift/api/config/v1/types_feature.go b/vendor/github.com/openshift/api/config/v1/types_feature.go index 2e98aba56d1..149cf8e6f60 100644 --- a/vendor/github.com/openshift/api/config/v1/types_feature.go +++ b/vendor/github.com/openshift/api/config/v1/types_feature.go @@ -111,19 +111,21 @@ var FeatureSets = map[FeatureSet]*FeatureGateEnabledDisabled{ Disabled: []string{}, }, TechPreviewNoUpgrade: newDefaultFeatures(). - with("CSIDriverAzureDisk"). // sig-storage, jsafrane, OCP specific - with("CSIDriverAzureFile"). // sig-storage, fbertina, OCP specific - with("CSIDriverVSphere"). // sig-storage, jsafrane, OCP specific - with("CSIMigrationAWS"). // sig-storage, jsafrane, Kubernetes feature gate - with("CSIMigrationOpenStack"). // sig-storage, jsafrane, Kubernetes feature gate - with("CSIMigrationGCE"). // sig-storage, fbertina, Kubernetes feature gate - with("CSIMigrationAzureDisk"). // sig-storage, fbertina, Kubernetes feature gate - with("CSIMigrationAzureFile"). // sig-storage, fbertina, Kubernetes feature gate - with("CSIMigrationvSphere"). // sig-storage, fbertina, Kubernetes feature gate - with("ExternalCloudProvider"). // sig-cloud-provider, jspeed, OCP specific - with("InsightsOperatorPullingSCA"). // insights-operator/ccx, tremes, OCP specific - with("CSIDriverSharedResource"). // sig-build, adkaplan, OCP specific - with("BuildCSIVolumes"). // sig-build, adkaplan, OCP specific + with("CSIDriverAzureDisk"). // sig-storage, jsafrane, OCP specific + with("CSIDriverAzureFile"). // sig-storage, fbertina, OCP specific + with("CSIDriverVSphere"). // sig-storage, jsafrane, OCP specific + with("CSIMigrationAWS"). // sig-storage, jsafrane, Kubernetes feature gate + with("CSIMigrationOpenStack"). // sig-storage, jsafrane, Kubernetes feature gate + with("CSIMigrationGCE"). // sig-storage, fbertina, Kubernetes feature gate + with("CSIMigrationAzureDisk"). // sig-storage, fbertina, Kubernetes feature gate + with("CSIMigrationAzureFile"). // sig-storage, fbertina, Kubernetes feature gate + with("CSIMigrationvSphere"). // sig-storage, fbertina, Kubernetes feature gate + with("ExternalCloudProvider"). // sig-cloud-provider, jspeed, OCP specific + with("InsightsOperatorPullingSCA"). // insights-operator/ccx, tremes, OCP specific + with("CSIDriverSharedResource"). // sig-build, adkaplan, OCP specific + with("BuildCSIVolumes"). // sig-build, adkaplan, OCP specific + with("NodeSwap"). // sig-node, ehashman, Kubernetes feature gate + with("MachineAPIProviderOpenStack"). // openstack, egarcia (#forum-openstack), OCP specific toFeatures(), LatencySensitive: newDefaultFeatures(). with( diff --git a/vendor/github.com/openshift/api/config/v1/types_infrastructure.go b/vendor/github.com/openshift/api/config/v1/types_infrastructure.go index 4863a98e70b..016b1a3f9c3 100644 --- a/vendor/github.com/openshift/api/config/v1/types_infrastructure.go +++ b/vendor/github.com/openshift/api/config/v1/types_infrastructure.go @@ -180,6 +180,10 @@ const ( // VPC means that the IBM Cloud cluster is using VPC infrastructure IBMCloudProviderTypeVPC IBMCloudProviderType = "VPC" + + // IBMCloudProviderTypeUPI means that the IBM Cloud cluster is using user provided infrastructure. + // This is utilized in IBM Cloud Satellite environments. + IBMCloudProviderTypeUPI IBMCloudProviderType = "UPI" ) // PlatformSpec holds the desired state specific to the underlying infrastructure provider @@ -599,6 +603,10 @@ type EquinixMetalPlatformStatus struct { // override existing defaults of PowerVS Services. type PowerVSServiceEndpoint struct { // name is the name of the Power VS service. + // Few of the services are + // IAM - https://cloud.ibm.com/apidocs/iam-identity-token-api + // ResourceController - https://cloud.ibm.com/apidocs/resource-controller/resource-controller + // Power Cloud - https://cloud.ibm.com/apidocs/power-cloud // // +kubebuilder:validation:Required // +kubebuilder:validation:Pattern=`^[a-z0-9-]+$` @@ -617,7 +625,14 @@ type PowerVSServiceEndpoint struct { // PowerVSPlatformSpec holds the desired state of the IBM Power Systems Virtual Servers infrastructure provider. // This only includes fields that can be modified in the cluster. -type PowerVSPlatformSpec struct{} +type PowerVSPlatformSpec struct { + // serviceEndpoints is a list of custom endpoints which will override the default + // service endpoints of a Power VS service. + // +listType=map + // +listMapKey=name + // +optional + ServiceEndpoints []PowerVSServiceEndpoint `json:"serviceEndpoints,omitempty"` +} // PowerVSPlatformStatus holds the current status of the IBM Power Systems Virtual Servers infrastrucutre provider. type PowerVSPlatformStatus struct { @@ -650,10 +665,9 @@ type AlibabaCloudPlatformStatus struct { // +required Region string `json:"region"` // resourceGroupID is the ID of the resource group for the cluster. - // +kubebuilder:validation:Required // +kubebuilder:validation:Pattern=`^rg-[0-9A-Za-z]+$` - // +required - ResourceGroupID string `json:"resourceGroupID"` + // +optional + ResourceGroupID string `json:"resourceGroupID,omitempty"` // resourceTags is a list of additional tags to apply to Alibaba Cloud resources created for the cluster. // +kubebuilder:validation:MaxItems=20 // +listType=map diff --git a/vendor/github.com/openshift/api/config/v1/types_network.go b/vendor/github.com/openshift/api/config/v1/types_network.go index 322f062e476..59392a96dd6 100644 --- a/vendor/github.com/openshift/api/config/v1/types_network.go +++ b/vendor/github.com/openshift/api/config/v1/types_network.go @@ -145,5 +145,33 @@ type NetworkMigration struct { // NetworkType is the target plugin that is to be deployed. // Currently supported values are: OpenShiftSDN, OVNKubernetes // +kubebuilder:validation:Enum={"OpenShiftSDN","OVNKubernetes"} - NetworkType string `json:"networkType"` + // +optional + NetworkType string `json:"networkType,omitempty"` + + // MTU contains the MTU migration configuration. + // +optional + MTU *MTUMigration `json:"mtu,omitempty"` +} + +// MTUMigration contains infomation about MTU migration. +type MTUMigration struct { + // Network contains MTU migration configuration for the default network. + // +optional + Network *MTUMigrationValues `json:"network,omitempty"` + + // Machine contains MTU migration configuration for the machine's uplink. + // +optional + Machine *MTUMigrationValues `json:"machine,omitempty"` +} + +// MTUMigrationValues contains the values for a MTU migration. +type MTUMigrationValues struct { + // To is the MTU to migrate to. + // +kubebuilder:validation:Minimum=0 + To *uint32 `json:"to"` + + // From is the MTU to migrate from. + // +kubebuilder:validation:Minimum=0 + // +optional + From *uint32 `json:"from,omitempty"` } diff --git a/vendor/github.com/openshift/api/config/v1/types_oauth.go b/vendor/github.com/openshift/api/config/v1/types_oauth.go index 61a1e51d352..02fbbf9d4b2 100644 --- a/vendor/github.com/openshift/api/config/v1/types_oauth.go +++ b/vendor/github.com/openshift/api/config/v1/types_oauth.go @@ -40,36 +40,8 @@ type OAuthSpec struct { // templates allow you to customize pages like the login page. // +optional Templates OAuthTemplates `json:"templates"` - // audit specifies what should be audited in the context of OAuthServer. By - // default the Audit is turned on. - // +optional - // +kubebuilder:default:={"profile":"WriteLoginEvents"} - Audit OAuthAudit `json:"audit"` -} - -// OAuthAudit specifies the Audit profile in use. -type OAuthAudit struct { - // profile is a simple drop in profile type that can be turned off by - // setting it to "None" or it can be turned on by setting it to - // "WriteLoginEvents". By default the profile is set to "WriteLoginEvents". - // +kubebuilder:default:="WriteLoginEvents" - Profile OAuthAuditProfileType `json:"profile,omitempty"` } -// OAuthAuditProfileType defines a simple audit profile, which can turn OAuth -// authentication audit logging on or off. -// +kubebuilder:validation:Enum=None;WriteLoginEvents -type OAuthAuditProfileType string - -const ( - // "None" disables audit logs. - OAuthNoneAuditProfileType AuditProfileType = "None" - - // "WriteLoginEvents" logs login and login failure events. - // This is the default. - OAuthWriteLoginEventsProfileType AuditProfileType = "WriteLoginEvents" -) - // OAuthStatus shows current known state of OAuth server in the cluster type OAuthStatus struct { // TODO Fill in with status of identityProviders and templates (and maybe tokenConfig) diff --git a/vendor/github.com/openshift/api/config/v1/zz_generated.deepcopy.go b/vendor/github.com/openshift/api/config/v1/zz_generated.deepcopy.go index ea9e5f6a9f3..00ffa323357 100644 --- a/vendor/github.com/openshift/api/config/v1/zz_generated.deepcopy.go +++ b/vendor/github.com/openshift/api/config/v1/zz_generated.deepcopy.go @@ -1,3 +1,4 @@ +//go:build !ignore_autogenerated // +build !ignore_autogenerated // Code generated by deepcopy-gen. DO NOT EDIT. @@ -2731,6 +2732,58 @@ func (in *LeaderElection) DeepCopy() *LeaderElection { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MTUMigration) DeepCopyInto(out *MTUMigration) { + *out = *in + if in.Network != nil { + in, out := &in.Network, &out.Network + *out = new(MTUMigrationValues) + (*in).DeepCopyInto(*out) + } + if in.Machine != nil { + in, out := &in.Machine, &out.Machine + *out = new(MTUMigrationValues) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MTUMigration. +func (in *MTUMigration) DeepCopy() *MTUMigration { + if in == nil { + return nil + } + out := new(MTUMigration) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MTUMigrationValues) DeepCopyInto(out *MTUMigrationValues) { + *out = *in + if in.To != nil { + in, out := &in.To, &out.To + *out = new(uint32) + **out = **in + } + if in.From != nil { + in, out := &in.From, &out.From + *out = new(uint32) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MTUMigrationValues. +func (in *MTUMigrationValues) DeepCopy() *MTUMigrationValues { + if in == nil { + return nil + } + out := new(MTUMigrationValues) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MaxAgePolicy) DeepCopyInto(out *MaxAgePolicy) { *out = *in @@ -2859,6 +2912,11 @@ func (in *NetworkList) DeepCopyObject() runtime.Object { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NetworkMigration) DeepCopyInto(out *NetworkMigration) { *out = *in + if in.MTU != nil { + in, out := &in.MTU, &out.MTU + *out = new(MTUMigration) + (*in).DeepCopyInto(*out) + } return } @@ -2919,7 +2977,7 @@ func (in *NetworkStatus) DeepCopyInto(out *NetworkStatus) { if in.Migration != nil { in, out := &in.Migration, &out.Migration *out = new(NetworkMigration) - **out = **in + (*in).DeepCopyInto(*out) } return } @@ -2962,22 +3020,6 @@ func (in *OAuth) DeepCopyObject() runtime.Object { return nil } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *OAuthAudit) DeepCopyInto(out *OAuthAudit) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OAuthAudit. -func (in *OAuthAudit) DeepCopy() *OAuthAudit { - if in == nil { - return nil - } - out := new(OAuthAudit) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OAuthList) DeepCopyInto(out *OAuthList) { *out = *in @@ -3042,7 +3084,6 @@ func (in *OAuthSpec) DeepCopyInto(out *OAuthSpec) { } in.TokenConfig.DeepCopyInto(&out.TokenConfig) out.Templates = in.Templates - out.Audit = in.Audit return } @@ -3429,7 +3470,7 @@ func (in *PlatformSpec) DeepCopyInto(out *PlatformSpec) { if in.PowerVS != nil { in, out := &in.PowerVS, &out.PowerVS *out = new(PowerVSPlatformSpec) - **out = **in + (*in).DeepCopyInto(*out) } if in.AlibabaCloud != nil { in, out := &in.AlibabaCloud, &out.AlibabaCloud @@ -3528,6 +3569,11 @@ func (in *PlatformStatus) DeepCopy() *PlatformStatus { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PowerVSPlatformSpec) DeepCopyInto(out *PowerVSPlatformSpec) { *out = *in + if in.ServiceEndpoints != nil { + in, out := &in.ServiceEndpoints, &out.ServiceEndpoints + *out = make([]PowerVSServiceEndpoint, len(*in)) + copy(*out, *in) + } return } diff --git a/vendor/github.com/openshift/api/config/v1/zz_generated.swagger_doc_generated.go b/vendor/github.com/openshift/api/config/v1/zz_generated.swagger_doc_generated.go index 7ea1847919d..326fc10bb1d 100644 --- a/vendor/github.com/openshift/api/config/v1/zz_generated.swagger_doc_generated.go +++ b/vendor/github.com/openshift/api/config/v1/zz_generated.swagger_doc_generated.go @@ -622,7 +622,7 @@ func (ConditionalUpdateRisk) SwaggerDoc() map[string]string { var map_PromQLClusterCondition = map[string]string{ "": "PromQLClusterCondition represents a cluster condition based on PromQL.", - "promql": "PromQL is a PromQL query classifying clusters. This query query should return a 1 in the match case and a 0 in the does-not-match case case. Queries which return no time series, or which return values besides 0 or 1, are evaluation failures.", + "promql": "PromQL is a PromQL query classifying clusters. This query query should return a 1 in the match case and a 0 in the does-not-match case. Queries which return no time series, or which return values besides 0 or 1, are evaluation failures.", } func (PromQLClusterCondition) SwaggerDoc() map[string]string { @@ -1190,7 +1190,8 @@ func (PlatformStatus) SwaggerDoc() map[string]string { } var map_PowerVSPlatformSpec = map[string]string{ - "": "PowerVSPlatformSpec holds the desired state of the IBM Power Systems Virtual Servers infrastructure provider. This only includes fields that can be modified in the cluster.", + "": "PowerVSPlatformSpec holds the desired state of the IBM Power Systems Virtual Servers infrastructure provider. This only includes fields that can be modified in the cluster.", + "serviceEndpoints": "serviceEndpoints is a list of custom endpoints which will override the default service endpoints of a Power VS service.", } func (PowerVSPlatformSpec) SwaggerDoc() map[string]string { @@ -1211,7 +1212,7 @@ func (PowerVSPlatformStatus) SwaggerDoc() map[string]string { var map_PowerVSServiceEndpoint = map[string]string{ "": "PowervsServiceEndpoint stores the configuration of a custom url to override existing defaults of PowerVS Services.", - "name": "name is the name of the Power VS service.", + "name": "name is the name of the Power VS service. Few of the services are IAM - https://cloud.ibm.com/apidocs/iam-identity-token-api ResourceController - https://cloud.ibm.com/apidocs/resource-controller/resource-controller Power Cloud - https://cloud.ibm.com/apidocs/power-cloud", "url": "url is fully qualified URI with scheme https, that overrides the default generated endpoint for a client. This must be provided and cannot be empty.", } @@ -1332,6 +1333,26 @@ func (ExternalIPPolicy) SwaggerDoc() map[string]string { return map_ExternalIPPolicy } +var map_MTUMigration = map[string]string{ + "": "MTUMigration contains infomation about MTU migration.", + "network": "Network contains MTU migration configuration for the default network.", + "machine": "Machine contains MTU migration configuration for the machine's uplink.", +} + +func (MTUMigration) SwaggerDoc() map[string]string { + return map_MTUMigration +} + +var map_MTUMigrationValues = map[string]string{ + "": "MTUMigrationValues contains the values for a MTU migration.", + "to": "To is the MTU to migrate to.", + "from": "From is the MTU to migrate from.", +} + +func (MTUMigrationValues) SwaggerDoc() map[string]string { + return map_MTUMigrationValues +} + var map_Network = map[string]string{ "": "Network holds cluster-wide information about Network. The canonical name is `cluster`. It is used to configure the desired network configuration, such as: IP address pools for services/pod IPs, network plugin, etc. Please view network.spec for an explanation on what applies when configuring this resource.\n\nCompatibility level 1: Stable within a major release for a minimum of 12 months or 3 minor releases (whichever is longer).", "spec": "spec holds user settable values for configuration. As a general rule, this SHOULD NOT be read directly. Instead, you should consume the NetworkStatus, as it indicates the currently deployed configuration. Currently, most spec fields are immutable after installation. Please view the individual ones for further details on each.", @@ -1353,6 +1374,7 @@ func (NetworkList) SwaggerDoc() map[string]string { var map_NetworkMigration = map[string]string{ "": "NetworkMigration represents the cluster network configuration.", "networkType": "NetworkType is the target plugin that is to be deployed. Currently supported values are: OpenShiftSDN, OVNKubernetes", + "mtu": "MTU contains the MTU migration configuration.", } func (NetworkMigration) SwaggerDoc() map[string]string { @@ -1512,15 +1534,6 @@ func (OAuth) SwaggerDoc() map[string]string { return map_OAuth } -var map_OAuthAudit = map[string]string{ - "": "OAuthAudit specifies the Audit profile in use.", - "profile": "profile is a simple drop in profile type that can be turned off by setting it to \"None\" or it can be turned on by setting it to \"WriteLoginEvents\". By default the profile is set to \"WriteLoginEvents\".", -} - -func (OAuthAudit) SwaggerDoc() map[string]string { - return map_OAuthAudit -} - var map_OAuthList = map[string]string{ "": "Compatibility level 1: Stable within a major release for a minimum of 12 months or 3 minor releases (whichever is longer).", } @@ -1546,7 +1559,6 @@ var map_OAuthSpec = map[string]string{ "identityProviders": "identityProviders is an ordered list of ways for a user to identify themselves. When this list is empty, no identities are provisioned for users.", "tokenConfig": "tokenConfig contains options for authorization and access tokens", "templates": "templates allow you to customize pages like the login page.", - "audit": "audit specifies what should be audited in the context of OAuthServer. By default the Audit is turned on.", } func (OAuthSpec) SwaggerDoc() map[string]string { diff --git a/vendor/github.com/openshift/api/machine/v1beta1/0000_10_machine.crd.yaml b/vendor/github.com/openshift/api/machine/v1beta1/0000_10_machine.crd.yaml index 0e4fb4c5c95..d1ff62cd674 100644 --- a/vendor/github.com/openshift/api/machine/v1beta1/0000_10_machine.crd.yaml +++ b/vendor/github.com/openshift/api/machine/v1beta1/0000_10_machine.crd.yaml @@ -70,6 +70,46 @@ spec: description: MachineSpec defines the desired state of Machine type: object properties: + lifecycleHooks: + description: LifecycleHooks allow users to pause operations on the machine at certain predefined points within the machine lifecycle. + type: object + properties: + preDrain: + description: PreDrain hooks prevent the machine from being drained. This also blocks further lifecycle events, such as termination. + type: array + items: + description: LifecycleHook represents a single instance of a lifecycle hook + type: object + properties: + name: + description: Name defines a unique name for the lifcycle hook. The name should be unique and descriptive, ideally 1-3 words, in CamelCase or it may be namespaced, eg. foo.example.com/CamelCase. Names must be unique and should only be managed by a single entity. + type: string + maxLength: 256 + minLength: 3 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + owner: + description: Owner defines the owner of the lifecycle hook. This should be descriptive enough so that users can identify who/what is responsible for blocking the lifecycle. This could be the name of a controller (e.g. clusteroperator/etcd) or an administrator managing the hook. + type: string + maxLength: 512 + minLength: 3 + preTerminate: + description: PreTerminate hooks prevent the machine from being terminated. PreTerminate hooks be actioned after the Machine has been drained. + type: array + items: + description: LifecycleHook represents a single instance of a lifecycle hook + type: object + properties: + name: + description: Name defines a unique name for the lifcycle hook. The name should be unique and descriptive, ideally 1-3 words, in CamelCase or it may be namespaced, eg. foo.example.com/CamelCase. Names must be unique and should only be managed by a single entity. + type: string + maxLength: 256 + minLength: 3 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + owner: + description: Owner defines the owner of the lifecycle hook. This should be descriptive enough so that users can identify who/what is responsible for blocking the lifecycle. This could be the name of a controller (e.g. clusteroperator/etcd) or an administrator managing the hook. + type: string + maxLength: 512 + minLength: 3 metadata: description: ObjectMeta will autopopulate the Node created. Use this to indicate what labels, annotations, name prefix, etc., should be used when creating the Node. type: object diff --git a/vendor/github.com/openshift/api/machine/v1beta1/0000_10_machineset.crd.yaml b/vendor/github.com/openshift/api/machine/v1beta1/0000_10_machineset.crd.yaml index 8bc57660de4..038802366a9 100644 --- a/vendor/github.com/openshift/api/machine/v1beta1/0000_10_machineset.crd.yaml +++ b/vendor/github.com/openshift/api/machine/v1beta1/0000_10_machineset.crd.yaml @@ -163,6 +163,46 @@ spec: description: 'Specification of the desired behavior of the machine. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status' type: object properties: + lifecycleHooks: + description: LifecycleHooks allow users to pause operations on the machine at certain predefined points within the machine lifecycle. + type: object + properties: + preDrain: + description: PreDrain hooks prevent the machine from being drained. This also blocks further lifecycle events, such as termination. + type: array + items: + description: LifecycleHook represents a single instance of a lifecycle hook + type: object + properties: + name: + description: Name defines a unique name for the lifcycle hook. The name should be unique and descriptive, ideally 1-3 words, in CamelCase or it may be namespaced, eg. foo.example.com/CamelCase. Names must be unique and should only be managed by a single entity. + type: string + maxLength: 256 + minLength: 3 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + owner: + description: Owner defines the owner of the lifecycle hook. This should be descriptive enough so that users can identify who/what is responsible for blocking the lifecycle. This could be the name of a controller (e.g. clusteroperator/etcd) or an administrator managing the hook. + type: string + maxLength: 512 + minLength: 3 + preTerminate: + description: PreTerminate hooks prevent the machine from being terminated. PreTerminate hooks be actioned after the Machine has been drained. + type: array + items: + description: LifecycleHook represents a single instance of a lifecycle hook + type: object + properties: + name: + description: Name defines a unique name for the lifcycle hook. The name should be unique and descriptive, ideally 1-3 words, in CamelCase or it may be namespaced, eg. foo.example.com/CamelCase. Names must be unique and should only be managed by a single entity. + type: string + maxLength: 256 + minLength: 3 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + owner: + description: Owner defines the owner of the lifecycle hook. This should be descriptive enough so that users can identify who/what is responsible for blocking the lifecycle. This could be the name of a controller (e.g. clusteroperator/etcd) or an administrator managing the hook. + type: string + maxLength: 512 + minLength: 3 metadata: description: ObjectMeta will autopopulate the Node created. Use this to indicate what labels, annotations, name prefix, etc., should be used when creating the Node. type: object diff --git a/vendor/github.com/openshift/api/machine/v1beta1/types_azureprovider.go b/vendor/github.com/openshift/api/machine/v1beta1/types_azureprovider.go index 65aea789563..32bc47aaa3c 100644 --- a/vendor/github.com/openshift/api/machine/v1beta1/types_azureprovider.go +++ b/vendor/github.com/openshift/api/machine/v1beta1/types_azureprovider.go @@ -203,6 +203,28 @@ type OSDisk struct { ManagedDisk ManagedDiskParameters `json:"managedDisk"` // DiskSizeGB is the size in GB to assign to the data disk. DiskSizeGB int32 `json:"diskSizeGB"` + // DiskSettings describe ephemeral disk settings for the os disk. + // +optional + DiskSettings DiskSettings `json:"diskSettings,omitempty"` + // CachingType specifies the caching requirements. + // Possible values include: 'None', 'ReadOnly', 'ReadWrite'. + // Empty value means no opinion and the platform chooses a default, which is subject to change over + // time. Currently the default is `None`. + // +optional + // +kubebuilder:validation:Enum=None;ReadOnly;ReadWrite + CachingType string `json:"cachingType,omitempty"` +} + +// DiskSettings describe ephemeral disk settings for the os disk. +type DiskSettings struct { + // EphemeralStorageLocation enables ephemeral OS when set to 'Local'. + // Possible values include: 'Local'. + // See https://docs.microsoft.com/en-us/azure/virtual-machines/ephemeral-os-disks for full details. + // Empty value means no opinion and the platform chooses a default, which is subject to change over + // time. Currently the default is that disks are saved to remote Azure storage. + // +optional + // +kubebuilder:validation:Enum=Local + EphemeralStorageLocation string `json:"ephemeralStorageLocation,omitempty"` } // ManagedDiskParameters is the parameters of a managed disk. diff --git a/vendor/github.com/openshift/api/machine/v1beta1/types_machine.go b/vendor/github.com/openshift/api/machine/v1beta1/types_machine.go index 73c33e44d31..8d304076552 100644 --- a/vendor/github.com/openshift/api/machine/v1beta1/types_machine.go +++ b/vendor/github.com/openshift/api/machine/v1beta1/types_machine.go @@ -167,6 +167,11 @@ type MachineSpec struct { // +optional ObjectMeta `json:"metadata,omitempty"` + // LifecycleHooks allow users to pause operations on the machine at + // certain predefined points within the machine lifecycle. + // +optional + LifecycleHooks LifecycleHooks `json:"lifecycleHooks,omitempty"` + // The list of the taints to be applied to the corresponding Node in additive // manner. This list will not overwrite any other taints added to the Node on // an ongoing basis by other entities. These taints should be actively reconciled @@ -194,6 +199,43 @@ type MachineSpec struct { ProviderID *string `json:"providerID,omitempty"` } +// LifecycleHooks allow users to pause operations on the machine at +// certain prefedined points within the machine lifecycle. +type LifecycleHooks struct { + // PreDrain hooks prevent the machine from being drained. + // This also blocks further lifecycle events, such as termination. + // +optional + PreDrain []LifecycleHook `json:"preDrain,omitempty"` + + // PreTerminate hooks prevent the machine from being terminated. + // PreTerminate hooks be actioned after the Machine has been drained. + // +optional + PreTerminate []LifecycleHook `json:"preTerminate,omitempty"` +} + +// LifecycleHook represents a single instance of a lifecycle hook +type LifecycleHook struct { + // Name defines a unique name for the lifcycle hook. + // The name should be unique and descriptive, ideally 1-3 words, in CamelCase or + // it may be namespaced, eg. foo.example.com/CamelCase. + // Names must be unique and should only be managed by a single entity. + // +kubebuilder:validation:Pattern=`^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$` + // +kubebuilder:validation:MinLength:=3 + // +kubebuilder:validation:MaxLength:=256 + // +required + Name string `json:"name"` + + // Owner defines the owner of the lifecycle hook. + // This should be descriptive enough so that users can identify + // who/what is responsible for blocking the lifecycle. + // This could be the name of a controller (e.g. clusteroperator/etcd) + // or an administrator managing the hook. + // +kubebuilder:validation:MinLength:=3 + // +kubebuilder:validation:MaxLength:=512 + // +required + Owner string `json:"owner"` +} + // MachineStatus defines the observed state of Machine type MachineStatus struct { // NodeRef will point to the corresponding Node if it exists. diff --git a/vendor/github.com/openshift/api/machine/v1beta1/types_provider.go b/vendor/github.com/openshift/api/machine/v1beta1/types_provider.go index 10bb715da33..69a5bd07ecc 100644 --- a/vendor/github.com/openshift/api/machine/v1beta1/types_provider.go +++ b/vendor/github.com/openshift/api/machine/v1beta1/types_provider.go @@ -144,6 +144,15 @@ const ( // ExternalRemediationRequestAvailable is set on machinehealthchecks when MachineHealthCheck controller uses external remediation. // ExternalRemediationRequestAvailable is set to false if creating external remediation request fails. ExternalRemediationRequestAvailable ConditionType = "ExternalRemediationRequestAvailable" + // MachineDrained is set on a machine to indicate that the machine has been drained. When an error occurs during + // the drain process, the condition will be added with a false status and details of the error. + MachineDrained ConditionType = "Drained" + // MachineDrainable is set on a machine to indicate whether or not the machine can be drained, or, whether some + // deletion hook is blocking the drain operation. + MachineDrainable ConditionType = "Drainable" + // MachineTerminable is set on a machine to indicate whether or not the machine can be terminated, or, whether some + // deletion hook is blocking the termination operation. + MachineTerminable ConditionType = "Terminable" ) const ( @@ -165,6 +174,12 @@ const ( ExternalRemediationTemplateNotFound = "ExternalRemediationTemplateNotFound" // ExternalRemediationRequestCreationFailed is the reason used when a machine health check fails to create external remediation request. ExternalRemediationRequestCreationFailed = "ExternalRemediationRequestCreationFailed" + // MachineHookPresent indicates that a machine lifecycle hook is blocking part of the lifecycle of the machine. + // This should be used with the `Drainable` and `Terminable` machine condition types. + MachineHookPresent = "HookPresent" + // MachineDrainError indicates an error occurred when draining the machine. + // This should be used with the `Drained` condition type. + MachineDrainError = "DrainError" ) // Condition defines an observation of a Machine API resource operational state. diff --git a/vendor/github.com/openshift/api/machine/v1beta1/zz_generated.deepcopy.go b/vendor/github.com/openshift/api/machine/v1beta1/zz_generated.deepcopy.go index 5bf2a5f036f..f9bf7ca9862 100644 --- a/vendor/github.com/openshift/api/machine/v1beta1/zz_generated.deepcopy.go +++ b/vendor/github.com/openshift/api/machine/v1beta1/zz_generated.deepcopy.go @@ -1,3 +1,4 @@ +//go:build !ignore_autogenerated // +build !ignore_autogenerated // Code generated by deepcopy-gen. DO NOT EDIT. @@ -418,6 +419,22 @@ func (in *DiskEncryptionSetParameters) DeepCopy() *DiskEncryptionSetParameters { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DiskSettings) DeepCopyInto(out *DiskSettings) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DiskSettings. +func (in *DiskSettings) DeepCopy() *DiskSettings { + if in == nil { + return nil + } + out := new(DiskSettings) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EBSBlockDeviceSpec) DeepCopyInto(out *EBSBlockDeviceSpec) { *out = *in @@ -822,6 +839,48 @@ func (in *LastOperation) DeepCopy() *LastOperation { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LifecycleHook) DeepCopyInto(out *LifecycleHook) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LifecycleHook. +func (in *LifecycleHook) DeepCopy() *LifecycleHook { + if in == nil { + return nil + } + out := new(LifecycleHook) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LifecycleHooks) DeepCopyInto(out *LifecycleHooks) { + *out = *in + if in.PreDrain != nil { + in, out := &in.PreDrain, &out.PreDrain + *out = make([]LifecycleHook, len(*in)) + copy(*out, *in) + } + if in.PreTerminate != nil { + in, out := &in.PreTerminate, &out.PreTerminate + *out = make([]LifecycleHook, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LifecycleHooks. +func (in *LifecycleHooks) DeepCopy() *LifecycleHooks { + if in == nil { + return nil + } + out := new(LifecycleHooks) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LoadBalancerReference) DeepCopyInto(out *LoadBalancerReference) { *out = *in @@ -1144,6 +1203,7 @@ func (in *MachineSetStatus) DeepCopy() *MachineSetStatus { func (in *MachineSpec) DeepCopyInto(out *MachineSpec) { *out = *in in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.LifecycleHooks.DeepCopyInto(&out.LifecycleHooks) if in.Taints != nil { in, out := &in.Taints, &out.Taints *out = make([]v1.Taint, len(*in)) @@ -1312,6 +1372,7 @@ func (in *NetworkSpec) DeepCopy() *NetworkSpec { func (in *OSDisk) DeepCopyInto(out *OSDisk) { *out = *in in.ManagedDisk.DeepCopyInto(&out.ManagedDisk) + out.DiskSettings = in.DiskSettings return } diff --git a/vendor/github.com/openshift/api/machine/v1beta1/zz_generated.swagger_doc_generated.go b/vendor/github.com/openshift/api/machine/v1beta1/zz_generated.swagger_doc_generated.go index a5da31fff1b..a1a3e3799a0 100644 --- a/vendor/github.com/openshift/api/machine/v1beta1/zz_generated.swagger_doc_generated.go +++ b/vendor/github.com/openshift/api/machine/v1beta1/zz_generated.swagger_doc_generated.go @@ -218,6 +218,15 @@ func (DiskEncryptionSetParameters) SwaggerDoc() map[string]string { return map_DiskEncryptionSetParameters } +var map_DiskSettings = map[string]string{ + "": "DiskSettings describe ephemeral disk settings for the os disk.", + "ephemeralStorageLocation": "EphemeralStorageLocation enables ephemeral OS when set to 'Local'. Possible values include: 'Local'. See https://docs.microsoft.com/en-us/azure/virtual-machines/ephemeral-os-disks for full details. Empty value means no opinion and the platform chooses a default, which is subject to change over time. Currently the default is that disks are saved to remote Azure storage.", +} + +func (DiskSettings) SwaggerDoc() map[string]string { + return map_DiskSettings +} + var map_Image = map[string]string{ "": "Image is a mirror of azure sdk compute.ImageReference", "publisher": "Publisher is the name of the organization that created the image", @@ -243,9 +252,11 @@ func (ManagedDiskParameters) SwaggerDoc() map[string]string { } var map_OSDisk = map[string]string{ - "osType": "OSType is the operating system type of the OS disk. Possible values include \"Linux\" and \"Windows\".", - "managedDisk": "ManagedDisk specifies the Managed Disk parameters for the OS disk.", - "diskSizeGB": "DiskSizeGB is the size in GB to assign to the data disk.", + "osType": "OSType is the operating system type of the OS disk. Possible values include \"Linux\" and \"Windows\".", + "managedDisk": "ManagedDisk specifies the Managed Disk parameters for the OS disk.", + "diskSizeGB": "DiskSizeGB is the size in GB to assign to the data disk.", + "diskSettings": "DiskSettings describe ephemeral disk settings for the os disk.", + "cachingType": "CachingType specifies the caching requirements. Possible values include: 'None', 'ReadOnly', 'ReadWrite'. Empty value means no opinion and the platform chooses a default, which is subject to change over time. Currently the default is `None`.", } func (OSDisk) SwaggerDoc() map[string]string { @@ -413,6 +424,26 @@ func (LastOperation) SwaggerDoc() map[string]string { return map_LastOperation } +var map_LifecycleHook = map[string]string{ + "": "LifecycleHook represents a single instance of a lifecycle hook", + "name": "Name defines a unique name for the lifcycle hook. The name should be unique and descriptive, ideally 1-3 words, in CamelCase or it may be namespaced, eg. foo.example.com/CamelCase. Names must be unique and should only be managed by a single entity.", + "owner": "Owner defines the owner of the lifecycle hook. This should be descriptive enough so that users can identify who/what is responsible for blocking the lifecycle. This could be the name of a controller (e.g. clusteroperator/etcd) or an administrator managing the hook.", +} + +func (LifecycleHook) SwaggerDoc() map[string]string { + return map_LifecycleHook +} + +var map_LifecycleHooks = map[string]string{ + "": "LifecycleHooks allow users to pause operations on the machine at certain prefedined points within the machine lifecycle.", + "preDrain": "PreDrain hooks prevent the machine from being drained. This also blocks further lifecycle events, such as termination.", + "preTerminate": "PreTerminate hooks prevent the machine from being terminated. PreTerminate hooks be actioned after the Machine has been drained.", +} + +func (LifecycleHooks) SwaggerDoc() map[string]string { + return map_LifecycleHooks +} + var map_Machine = map[string]string{ "": "Machine is the Schema for the machines API Compatibility level 2: Stable within a major release for a minimum of 9 months or 3 minor releases (whichever is longer).", } @@ -430,11 +461,12 @@ func (MachineList) SwaggerDoc() map[string]string { } var map_MachineSpec = map[string]string{ - "": "MachineSpec defines the desired state of Machine", - "metadata": "ObjectMeta will autopopulate the Node created. Use this to indicate what labels, annotations, name prefix, etc., should be used when creating the Node.", - "taints": "The list of the taints to be applied to the corresponding Node in additive manner. This list will not overwrite any other taints added to the Node on an ongoing basis by other entities. These taints should be actively reconciled e.g. if you ask the machine controller to apply a taint and then manually remove the taint the machine controller will put it back) but not have the machine controller remove any taints", - "providerSpec": "ProviderSpec details Provider-specific configuration to use during node creation.", - "providerID": "ProviderID is the identification ID of the machine provided by the provider. This field must match the provider ID as seen on the node object corresponding to this machine. This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a generic out-of-tree provider for autoscaler, this field is required by autoscaler to be able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver and then a comparison is done to find out unregistered machines and are marked for delete. This field will be set by the actuators and consumed by higher level entities like autoscaler that will be interfacing with cluster-api as generic provider.", + "": "MachineSpec defines the desired state of Machine", + "metadata": "ObjectMeta will autopopulate the Node created. Use this to indicate what labels, annotations, name prefix, etc., should be used when creating the Node.", + "lifecycleHooks": "LifecycleHooks allow users to pause operations on the machine at certain predefined points within the machine lifecycle.", + "taints": "The list of the taints to be applied to the corresponding Node in additive manner. This list will not overwrite any other taints added to the Node on an ongoing basis by other entities. These taints should be actively reconciled e.g. if you ask the machine controller to apply a taint and then manually remove the taint the machine controller will put it back) but not have the machine controller remove any taints", + "providerSpec": "ProviderSpec details Provider-specific configuration to use during node creation.", + "providerID": "ProviderID is the identification ID of the machine provided by the provider. This field must match the provider ID as seen on the node object corresponding to this machine. This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a generic out-of-tree provider for autoscaler, this field is required by autoscaler to be able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver and then a comparison is done to find out unregistered machines and are marked for delete. This field will be set by the actuators and consumed by higher level entities like autoscaler that will be interfacing with cluster-api as generic provider.", } func (MachineSpec) SwaggerDoc() map[string]string { diff --git a/vendor/github.com/openshift/api/operator/v1/0000_70_cluster-network-operator_01.crd.yaml b/vendor/github.com/openshift/api/operator/v1/0000_70_cluster-network-operator_01.crd.yaml index ab52d00b174..5c088482c08 100644 --- a/vendor/github.com/openshift/api/operator/v1/0000_70_cluster-network-operator_01.crd.yaml +++ b/vendor/github.com/openshift/api/operator/v1/0000_70_cluster-network-operator_01.crd.yaml @@ -290,9 +290,24 @@ spec: type: integer type: object ovnKubernetesConfig: - description: oVNKubernetesConfig configures the ovn-kubernetes - plugin. This is currently not implemented. + description: ovnKubernetesConfig configures the ovn-kubernetes + plugin. properties: + gatewayConfig: + description: gatewayConfig holds the configuration for node + gateway options. + properties: + routingViaHost: + default: false + description: RoutingViaHost allows pod egress traffic + to exit via the ovn-k8s-mp0 management port into the + host before sending it out. If this is not set, traffic + will always egress directly from OVN to outside without + touching the host stack. Setting this to true means + hardware offload will not be supported. Default is false + if GatewayConfig is specified. + type: boolean + type: object genevePort: description: geneve port is the UDP port to be used by geneve encapulation. Default is 6081 @@ -501,13 +516,56 @@ spec: type: string migration: description: migration enables and configures the cluster network - migration. Setting this to the target network type to allow changing - the default network. If unset, the operation of changing cluster - default network plugin will be rejected. + migration. The migration procedure allows to change the network + type and the MTU. properties: + mtu: + description: mtu contains the MTU migration configuration. Set + this to allow changing the MTU values for the default network. + If unset, the operation of changing the MTU for the default + network will be rejected. + properties: + machine: + description: machine contains MTU migration configuration + for the machine's uplink. Needs to be migrated along with + the default network MTU unless the current uplink MTU already + accommodates the default network MTU. + properties: + from: + description: from is the MTU to migrate from. + format: int32 + minimum: 0 + type: integer + to: + description: to is the MTU to migrate to. + format: int32 + minimum: 0 + type: integer + type: object + network: + description: network contains information about MTU migration + for the default network. Migrations are only allowed to + MTU values lower than the machine's uplink MTU by the minimum + appropriate offset. + properties: + from: + description: from is the MTU to migrate from. + format: int32 + minimum: 0 + type: integer + to: + description: to is the MTU to migrate to. + format: int32 + minimum: 0 + type: integer + type: object + type: object networkType: - description: networkType is the target type of network migration - The supported values are OpenShiftSDN, OVNKubernetes + description: networkType is the target type of network migration. + Set this to the target network type to allow changing the default + network. If unset, the operation of changing cluster default + network plugin will be rejected. The supported values are OpenShiftSDN, + OVNKubernetes type: string type: object observedConfig: diff --git a/vendor/github.com/openshift/api/operator/v1/0000_70_dns-operator_00-custom-resource-definition.yaml b/vendor/github.com/openshift/api/operator/v1/0000_70_dns-operator_00-custom-resource-definition.yaml deleted file mode 100644 index 054f908cc37..00000000000 --- a/vendor/github.com/openshift/api/operator/v1/0000_70_dns-operator_00-custom-resource-definition.yaml +++ /dev/null @@ -1,156 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - name: dnses.operator.openshift.io - annotations: - api-approved.openshift.io: https://github.com/openshift/api/pull/475 - include.release.openshift.io/ibm-cloud-managed: "true" - include.release.openshift.io/self-managed-high-availability: "true" - include.release.openshift.io/single-node-developer: "true" -spec: - group: operator.openshift.io - names: - kind: DNS - listKind: DNSList - plural: dnses - singular: dns - scope: Cluster - versions: - - name: v1 - served: true - storage: true - subresources: - status: {} - schema: - openAPIV3Schema: - description: "DNS manages the CoreDNS component to provide a name resolution service for pods and services in the cluster. \n This supports the DNS-based service discovery specification: https://github.com/kubernetes/dns/blob/master/docs/specification.md \n More details: https://kubernetes.io/docs/tasks/administer-cluster/coredns \n Compatibility level 1: Stable within a major release for a minimum of 12 months or 3 minor releases (whichever is longer)." - type: object - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - description: spec is the specification of the desired behavior of the DNS. - type: object - properties: - logLevel: - description: 'logLevel describes the desired logging verbosity for CoreDNS. Any one of the following values may be specified: * Normal logs errors from upstream resolvers. * Debug logs errors, NXDOMAIN responses, and NODATA responses. * Trace logs errors and all responses. Setting logLevel: Trace will produce extremely verbose logs. Valid values are: "Normal", "Debug", "Trace". Defaults to "Normal".' - type: string - default: Normal - enum: - - Normal - - Debug - - Trace - managementState: - description: managementState indicates whether the DNS operator should manage cluster DNS - type: string - pattern: ^(Managed|Unmanaged|Force|Removed)$ - nodePlacement: - description: "nodePlacement provides explicit control over the scheduling of DNS pods. \n Generally, it is useful to run a DNS pod on every node so that DNS queries are always handled by a local DNS pod instead of going over the network to a DNS pod on another node. However, security policies may require restricting the placement of DNS pods to specific nodes. For example, if a security policy prohibits pods on arbitrary nodes from communicating with the API, a node selector can be specified to restrict DNS pods to nodes that are permitted to communicate with the API. Conversely, if running DNS pods on nodes with a particular taint is desired, a toleration can be specified for that taint. \n If unset, defaults are used. See nodePlacement for more details." - type: object - properties: - nodeSelector: - description: "nodeSelector is the node selector applied to DNS pods. \n If empty, the default is used, which is currently the following: \n kubernetes.io/os: linux \n This default is subject to change. \n If set, the specified selector is used and replaces the default." - type: object - additionalProperties: - type: string - tolerations: - description: "tolerations is a list of tolerations applied to DNS pods. \n If empty, the DNS operator sets a toleration for the \"node-role.kubernetes.io/master\" taint. This default is subject to change. Specifying tolerations without including a toleration for the \"node-role.kubernetes.io/master\" taint may be risky as it could lead to an outage if all worker nodes become unavailable. \n Note that the daemon controller adds some tolerations as well. See https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/" - type: array - items: - description: The pod this Toleration is attached to tolerates any taint that matches the triple using the matching operator . - type: object - properties: - effect: - description: Effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute. - type: string - key: - description: Key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys. - type: string - operator: - description: Operator represents a key's relationship to the value. Valid operators are Exists and Equal. Defaults to Equal. Exists is equivalent to wildcard for value, so that a pod can tolerate all taints of a particular category. - type: string - tolerationSeconds: - description: TolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system. - type: integer - format: int64 - value: - description: Value is the taint value the toleration matches to. If the operator is Exists, the value should be empty, otherwise just a regular string. - type: string - operatorLogLevel: - description: 'operatorLogLevel controls the logging level of the DNS Operator. Valid values are: "Normal", "Debug", "Trace". Defaults to "Normal". setting operatorLogLevel: Trace will produce extremely verbose logs.' - type: string - default: Normal - enum: - - Normal - - Debug - - Trace - servers: - description: "servers is a list of DNS resolvers that provide name query delegation for one or more subdomains outside the scope of the cluster domain. If servers consists of more than one Server, longest suffix match will be used to determine the Server. \n For example, if there are two Servers, one for \"foo.com\" and another for \"a.foo.com\", and the name query is for \"www.a.foo.com\", it will be routed to the Server with Zone \"a.foo.com\". \n If this field is nil, no servers are created." - type: array - items: - description: Server defines the schema for a server that runs per instance of CoreDNS. - type: object - properties: - forwardPlugin: - description: forwardPlugin defines a schema for configuring CoreDNS to proxy DNS messages to upstream resolvers. - type: object - properties: - policy: - description: "policy is used to determine the order in which upstream servers are selected for querying. Any one of the following values may be specified: \n * \"Random\" picks a random upstream server for each query. * \"RoundRobin\" picks upstream servers in a round-robin order, moving to the next server for each new query. * \"Sequential\" tries querying upstream servers in a sequential order until one responds, starting with the first server for each new query. \n The default value is \"Random\"" - type: string - default: Random - enum: - - Random - - RoundRobin - - Sequential - upstreams: - description: "upstreams is a list of resolvers to forward name queries for subdomains of Zones. Each instance of CoreDNS performs health checking of Upstreams. When a healthy upstream returns an error during the exchange, another resolver is tried from Upstreams. The Upstreams are selected in the order specified in Policy. Each upstream is represented by an IP address or IP:port if the upstream listens on a port other than 53. \n A maximum of 15 upstreams is allowed per ForwardPlugin." - type: array - maxItems: 15 - items: - type: string - name: - description: name is required and specifies a unique name for the server. Name must comply with the Service Name Syntax of rfc6335. - type: string - zones: - description: zones is required and specifies the subdomains that Server is authoritative for. Zones must conform to the rfc1123 definition of a subdomain. Specifying the cluster domain (i.e., "cluster.local") is invalid. - type: array - items: - type: string - status: - description: status is the most recently observed status of the DNS. - type: object - required: - - clusterDomain - - clusterIP - properties: - clusterDomain: - description: "clusterDomain is the local cluster DNS domain suffix for DNS services. This will be a subdomain as defined in RFC 1034, section 3.5: https://tools.ietf.org/html/rfc1034#section-3.5 Example: \"cluster.local\" \n More info: https://kubernetes.io/docs/concepts/services-networking/dns-pod-service" - type: string - clusterIP: - description: "clusterIP is the service IP through which this DNS is made available. \n In the case of the default DNS, this will be a well known IP that is used as the default nameserver for pods that are using the default ClusterFirst DNS policy. \n In general, this IP can be specified in a pod's spec.dnsConfig.nameservers list or used explicitly when performing name resolution from within the cluster. Example: dig foo.com @ \n More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies" - type: string - conditions: - description: "conditions provide information about the state of the DNS on the cluster. \n These are the supported DNS conditions: \n * Available - True if the following conditions are met: * DNS controller daemonset is available. - False if any of those conditions are unsatisfied." - type: array - items: - description: OperatorCondition is just the standard condition fields. - type: object - properties: - lastTransitionTime: - type: string - format: date-time - message: - type: string - reason: - type: string - status: - type: string - type: - type: string diff --git a/vendor/github.com/openshift/api/operator/v1/0000_70_dns-operator_00.crd.yaml b/vendor/github.com/openshift/api/operator/v1/0000_70_dns-operator_00.crd.yaml new file mode 100644 index 00000000000..158a99bd7ae --- /dev/null +++ b/vendor/github.com/openshift/api/operator/v1/0000_70_dns-operator_00.crd.yaml @@ -0,0 +1,351 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + api-approved.openshift.io: https://github.com/openshift/api/pull/475 + include.release.openshift.io/ibm-cloud-managed: "true" + include.release.openshift.io/self-managed-high-availability: "true" + include.release.openshift.io/single-node-developer: "true" + name: dnses.operator.openshift.io +spec: + group: operator.openshift.io + names: + kind: DNS + listKind: DNSList + plural: dnses + singular: dns + scope: Cluster + versions: + - name: v1 + schema: + openAPIV3Schema: + description: "DNS manages the CoreDNS component to provide a name resolution + service for pods and services in the cluster. \n This supports the DNS-based + service discovery specification: https://github.com/kubernetes/dns/blob/master/docs/specification.md + \n More details: https://kubernetes.io/docs/tasks/administer-cluster/coredns + \n Compatibility level 1: Stable within a major release for a minimum of + 12 months or 3 minor releases (whichever is longer)." + properties: + apiVersion: + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + type: string + kind: + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + type: string + metadata: + type: object + spec: + description: spec is the specification of the desired behavior of the + DNS. + properties: + logLevel: + default: Normal + description: 'logLevel describes the desired logging verbosity for + CoreDNS. Any one of the following values may be specified: * Normal + logs errors from upstream resolvers. * Debug logs errors, NXDOMAIN + responses, and NODATA responses. * Trace logs errors and all responses. Setting + logLevel: Trace will produce extremely verbose logs. Valid values + are: "Normal", "Debug", "Trace". Defaults to "Normal".' + enum: + - Normal + - Debug + - Trace + type: string + managementState: + description: managementState indicates whether the DNS operator should + manage cluster DNS + pattern: ^(Managed|Unmanaged|Force|Removed)$ + type: string + nodePlacement: + description: "nodePlacement provides explicit control over the scheduling + of DNS pods. \n Generally, it is useful to run a DNS pod on every + node so that DNS queries are always handled by a local DNS pod instead + of going over the network to a DNS pod on another node. However, + security policies may require restricting the placement of DNS pods + to specific nodes. For example, if a security policy prohibits pods + on arbitrary nodes from communicating with the API, a node selector + can be specified to restrict DNS pods to nodes that are permitted + to communicate with the API. Conversely, if running DNS pods on + nodes with a particular taint is desired, a toleration can be specified + for that taint. \n If unset, defaults are used. See nodePlacement + for more details." + properties: + nodeSelector: + additionalProperties: + type: string + description: "nodeSelector is the node selector applied to DNS + pods. \n If empty, the default is used, which is currently the + following: \n kubernetes.io/os: linux \n This default is subject + to change. \n If set, the specified selector is used and replaces + the default." + type: object + tolerations: + description: "tolerations is a list of tolerations applied to + DNS pods. \n If empty, the DNS operator sets a toleration for + the \"node-role.kubernetes.io/master\" taint. This default + is subject to change. Specifying tolerations without including + a toleration for the \"node-role.kubernetes.io/master\" taint + may be risky as it could lead to an outage if all worker nodes + become unavailable. \n Note that the daemon controller adds + some tolerations as well. See https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/" + items: + description: The pod this Toleration is attached to tolerates + any taint that matches the triple using + the matching operator . + properties: + effect: + description: Effect indicates the taint effect to match. + Empty means match all taint effects. When specified, allowed + values are NoSchedule, PreferNoSchedule and NoExecute. + type: string + key: + description: Key is the taint key that the toleration applies + to. Empty means match all taint keys. If the key is empty, + operator must be Exists; this combination means to match + all values and all keys. + type: string + operator: + description: Operator represents a key's relationship to + the value. Valid operators are Exists and Equal. Defaults + to Equal. Exists is equivalent to wildcard for value, + so that a pod can tolerate all taints of a particular + category. + type: string + tolerationSeconds: + description: TolerationSeconds represents the period of + time the toleration (which must be of effect NoExecute, + otherwise this field is ignored) tolerates the taint. + By default, it is not set, which means tolerate the taint + forever (do not evict). Zero and negative values will + be treated as 0 (evict immediately) by the system. + format: int64 + type: integer + value: + description: Value is the taint value the toleration matches + to. If the operator is Exists, the value should be empty, + otherwise just a regular string. + type: string + type: object + type: array + type: object + operatorLogLevel: + default: Normal + description: 'operatorLogLevel controls the logging level of the DNS + Operator. Valid values are: "Normal", "Debug", "Trace". Defaults + to "Normal". setting operatorLogLevel: Trace will produce extremely + verbose logs.' + enum: + - Normal + - Debug + - Trace + type: string + servers: + description: "servers is a list of DNS resolvers that provide name + query delegation for one or more subdomains outside the scope of + the cluster domain. If servers consists of more than one Server, + longest suffix match will be used to determine the Server. \n For + example, if there are two Servers, one for \"foo.com\" and another + for \"a.foo.com\", and the name query is for \"www.a.foo.com\", + it will be routed to the Server with Zone \"a.foo.com\". \n If this + field is nil, no servers are created." + items: + description: Server defines the schema for a server that runs per + instance of CoreDNS. + properties: + forwardPlugin: + description: forwardPlugin defines a schema for configuring + CoreDNS to proxy DNS messages to upstream resolvers. + properties: + policy: + default: Random + description: "policy is used to determine the order in which + upstream servers are selected for querying. Any one of + the following values may be specified: \n * \"Random\" + picks a random upstream server for each query. * \"RoundRobin\" + picks upstream servers in a round-robin order, moving + to the next server for each new query. * \"Sequential\" + tries querying upstream servers in a sequential order + until one responds, starting with the first server for + each new query. \n The default value is \"Random\"" + enum: + - Random + - RoundRobin + - Sequential + type: string + upstreams: + description: "upstreams is a list of resolvers to forward + name queries for subdomains of Zones. Each instance of + CoreDNS performs health checking of Upstreams. When a + healthy upstream returns an error during the exchange, + another resolver is tried from Upstreams. The Upstreams + are selected in the order specified in Policy. Each upstream + is represented by an IP address or IP:port if the upstream + listens on a port other than 53. \n A maximum of 15 upstreams + is allowed per ForwardPlugin." + items: + type: string + maxItems: 15 + type: array + type: object + name: + description: name is required and specifies a unique name for + the server. Name must comply with the Service Name Syntax + of rfc6335. + type: string + zones: + description: zones is required and specifies the subdomains + that Server is authoritative for. Zones must conform to the + rfc1123 definition of a subdomain. Specifying the cluster + domain (i.e., "cluster.local") is invalid. + items: + type: string + type: array + type: object + type: array + upstreamResolvers: + default: {} + description: "upstreamResolvers defines a schema for configuring CoreDNS + to proxy DNS messages to upstream resolvers for the case of the + default (\".\") server \n If this field is not specified, the upstream + used will default to /etc/resolv.conf, with policy \"sequential\"" + properties: + policy: + default: Sequential + description: "Policy is used to determine the order in which upstream + servers are selected for querying. Any one of the following + values may be specified: \n * \"Random\" picks a random upstream + server for each query. * \"RoundRobin\" picks upstream servers + in a round-robin order, moving to the next server for each new + query. * \"Sequential\" tries querying upstream servers in a + sequential order until one responds, starting with the first + server for each new query. \n The default value is \"Sequential\"" + enum: + - Random + - RoundRobin + - Sequential + type: string + upstreams: + default: + - type: SystemResolvConf + description: "Upstreams is a list of resolvers to forward name + queries for the \".\" domain. Each instance of CoreDNS performs + health checking of Upstreams. When a healthy upstream returns + an error during the exchange, another resolver is tried from + Upstreams. The Upstreams are selected in the order specified + in Policy. \n A maximum of 15 upstreams is allowed per ForwardPlugin. + If no Upstreams are specified, /etc/resolv.conf is used by default" + items: + anyOf: + - not: + required: + - address + - port + properties: + type: + enum: + - "" + - SystemResolvConf + - optional: + - port + properties: + type: + enum: + - Network + required: + - address + description: "Upstream can either be of type SystemResolvConf, + or of type Network. \n * For an Upstream of type SystemResolvConf, + no further fields are necessary: The upstream will be configured + to use /etc/resolv.conf. * For an Upstream of type Network, + a NetworkResolver field needs to be defined with an IP address + or IP:port if the upstream listens on a port other than 53." + properties: + address: + anyOf: + - format: ipv4 + - format: ipv6 + description: Address must be defined when Type is set to + Network. It will be ignored otherwise. It must be a valid + ipv4 or ipv6 address. + type: string + port: + default: 53 + description: Port may be defined when Type is set to Network. + It will be ignored otherwise. Port must be between 65535 + format: int32 + maximum: 65535 + minimum: 1 + type: integer + type: + description: "Type defines whether this upstream contains + an IP/IP:port resolver or the local /etc/resolv.conf. + Type accepts 2 possible values: SystemResolvConf or Network. + \n * When SystemResolvConf is used, the Upstream structure + does not require any further fields to be defined: /etc/resolv.conf + will be used * When Network is used, the Upstream structure + must contain at least an Address" + enum: + - SystemResolvConf + - Network + - "" + type: string + required: + - type + type: object + maxItems: 15 + type: array + type: object + type: object + status: + description: status is the most recently observed status of the DNS. + properties: + clusterDomain: + description: "clusterDomain is the local cluster DNS domain suffix + for DNS services. This will be a subdomain as defined in RFC 1034, + section 3.5: https://tools.ietf.org/html/rfc1034#section-3.5 Example: + \"cluster.local\" \n More info: https://kubernetes.io/docs/concepts/services-networking/dns-pod-service" + type: string + clusterIP: + description: "clusterIP is the service IP through which this DNS is + made available. \n In the case of the default DNS, this will be + a well known IP that is used as the default nameserver for pods + that are using the default ClusterFirst DNS policy. \n In general, + this IP can be specified in a pod's spec.dnsConfig.nameservers list + or used explicitly when performing name resolution from within the + cluster. Example: dig foo.com @ \n More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies" + type: string + conditions: + description: "conditions provide information about the state of the + DNS on the cluster. \n These are the supported DNS conditions: \n + \ * Available - True if the following conditions are met: * + DNS controller daemonset is available. - False if any of those + conditions are unsatisfied." + items: + description: OperatorCondition is just the standard condition fields. + properties: + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + type: string + status: + type: string + type: + type: string + type: object + type: array + required: + - clusterDomain + - clusterIP + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/vendor/github.com/openshift/api/operator/v1/0000_70_dns-operator_00.crd.yaml-patch b/vendor/github.com/openshift/api/operator/v1/0000_70_dns-operator_00.crd.yaml-patch new file mode 100644 index 00000000000..285a5267290 --- /dev/null +++ b/vendor/github.com/openshift/api/operator/v1/0000_70_dns-operator_00.crd.yaml-patch @@ -0,0 +1,21 @@ +- op: add + path: /spec/versions/name=v1/schema/openAPIV3Schema/properties/spec/properties/upstreamResolvers/default + value: {} +- op: add + path: /spec/versions/name=v1/schema/openAPIV3Schema/properties/spec/properties/upstreamResolvers/properties/upstreams/items/properties/address/anyOf + value: + - format: ipv4 + - format: ipv6 +- op: add + path: /spec/versions/name=v1/schema/openAPIV3Schema/properties/spec/properties/upstreamResolvers/properties/upstreams/items/anyOf + value: + - properties: + type: + enum: [ "","SystemResolvConf" ] # empty string because client-side validation will not see the default value + not: + required: [ "address", "port" ] + - properties: + type: + enum: [ "Network" ] + required: [ "address" ] + optional: [ "port" ] diff --git a/vendor/github.com/openshift/api/operator/v1/types_dns.go b/vendor/github.com/openshift/api/operator/v1/types_dns.go index d73fed96ef1..c05a826cdf7 100644 --- a/vendor/github.com/openshift/api/operator/v1/types_dns.go +++ b/vendor/github.com/openshift/api/operator/v1/types_dns.go @@ -48,6 +48,16 @@ type DNSSpec struct { // +optional Servers []Server `json:"servers,omitempty"` + // upstreamResolvers defines a schema for configuring CoreDNS + // to proxy DNS messages to upstream resolvers for the case of the + // default (".") server + // + // If this field is not specified, the upstream used will default to + // /etc/resolv.conf, with policy "sequential" + // + // +optional + UpstreamResolvers UpstreamResolvers `json:"upstreamResolvers"` + // nodePlacement provides explicit control over the scheduling of DNS // pods. // @@ -162,6 +172,84 @@ type ForwardPlugin struct { Policy ForwardingPolicy `json:"policy,omitempty"` } +// UpstreamResolvers defines a schema for configuring the CoreDNS forward plugin in the +// specific case of the default (".") server. +// It defers from ForwardPlugin in the default values it accepts: +// * At least one upstream should be specified. +// * the default policy is Sequential +type UpstreamResolvers struct { + // Upstreams is a list of resolvers to forward name queries for the "." domain. + // Each instance of CoreDNS performs health checking of Upstreams. When a healthy upstream + // returns an error during the exchange, another resolver is tried from Upstreams. The + // Upstreams are selected in the order specified in Policy. + // + // A maximum of 15 upstreams is allowed per ForwardPlugin. + // If no Upstreams are specified, /etc/resolv.conf is used by default + // + // +optional + // +kubebuilder:validation:MaxItems=15 + // +kubebuilder:default={{"type":"SystemResolvConf"}} + Upstreams []Upstream `json:"upstreams"` + + // Policy is used to determine the order in which upstream servers are selected for querying. + // Any one of the following values may be specified: + // + // * "Random" picks a random upstream server for each query. + // * "RoundRobin" picks upstream servers in a round-robin order, moving to the next server for each new query. + // * "Sequential" tries querying upstream servers in a sequential order until one responds, starting with the first server for each new query. + // + // The default value is "Sequential" + // + // +optional + // +kubebuilder:default="Sequential" + Policy ForwardingPolicy `json:"policy,omitempty"` +} + +// Upstream can either be of type SystemResolvConf, or of type Network. +// +// * For an Upstream of type SystemResolvConf, no further fields are necessary: +// The upstream will be configured to use /etc/resolv.conf. +// * For an Upstream of type Network, a NetworkResolver field needs to be defined +// with an IP address or IP:port if the upstream listens on a port other than 53. +type Upstream struct { + + // Type defines whether this upstream contains an IP/IP:port resolver or the local /etc/resolv.conf. + // Type accepts 2 possible values: SystemResolvConf or Network. + // + // * When SystemResolvConf is used, the Upstream structure does not require any further fields to be defined: + // /etc/resolv.conf will be used + // * When Network is used, the Upstream structure must contain at least an Address + // + // +kubebuilder:validation:Required + // +required + Type UpstreamType `json:"type"` + + // Address must be defined when Type is set to Network. It will be ignored otherwise. + // It must be a valid ipv4 or ipv6 address. + // + // +optional + // +kubebuilder:validation:Optional + Address string `json:"address,omitempty"` + + // Port may be defined when Type is set to Network. It will be ignored otherwise. + // Port must be between 65535 + // + // +optional + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=65535 + // +kubebuilder:validation:Optional + // +kubebuilder:default=53 + Port uint32 `json:"port,omitempty"` +} + +// +kubebuilder:validation:Enum=SystemResolvConf;Network;"" +type UpstreamType string + +const ( + SystemResolveConfType UpstreamType = "SystemResolvConf" + NetworkResolverType UpstreamType = "Network" +) + // DNSNodePlacement describes the node scheduling configuration for DNS pods. type DNSNodePlacement struct { // nodeSelector is the node selector applied to DNS pods. diff --git a/vendor/github.com/openshift/api/operator/v1/types_network.go b/vendor/github.com/openshift/api/operator/v1/types_network.go index b04c6b6d332..b3e397ab0bf 100644 --- a/vendor/github.com/openshift/api/operator/v1/types_network.go +++ b/vendor/github.com/openshift/api/operator/v1/types_network.go @@ -103,18 +103,53 @@ type NetworkSpec struct { // +optional ExportNetworkFlows *ExportNetworkFlows `json:"exportNetworkFlows,omitempty"` - // migration enables and configures the cluster network migration. - // Setting this to the target network type to allow changing the default network. - // If unset, the operation of changing cluster default network plugin will be rejected. + // migration enables and configures the cluster network migration. The + // migration procedure allows to change the network type and the MTU. // +optional Migration *NetworkMigration `json:"migration,omitempty"` } // NetworkMigration represents the cluster network configuration. type NetworkMigration struct { - // networkType is the target type of network migration + // networkType is the target type of network migration. Set this to the + // target network type to allow changing the default network. If unset, the + // operation of changing cluster default network plugin will be rejected. // The supported values are OpenShiftSDN, OVNKubernetes - NetworkType NetworkType `json:"networkType"` + // +optional + NetworkType string `json:"networkType,omitempty"` + + // mtu contains the MTU migration configuration. Set this to allow changing + // the MTU values for the default network. If unset, the operation of + // changing the MTU for the default network will be rejected. + // +optional + MTU *MTUMigration `json:"mtu,omitempty"` +} + +// MTUMigration MTU contains infomation about MTU migration. +type MTUMigration struct { + // network contains information about MTU migration for the default network. + // Migrations are only allowed to MTU values lower than the machine's uplink + // MTU by the minimum appropriate offset. + // +optional + Network *MTUMigrationValues `json:"network,omitempty"` + + // machine contains MTU migration configuration for the machine's uplink. + // Needs to be migrated along with the default network MTU unless the + // current uplink MTU already accommodates the default network MTU. + // +optional + Machine *MTUMigrationValues `json:"machine,omitempty"` +} + +// MTUMigrationValues contains the values for a MTU migration. +type MTUMigrationValues struct { + // to is the MTU to migrate to. + // +kubebuilder:validation:Minimum=0 + To *uint32 `json:"to"` + + // from is the MTU to migrate from. + // +kubebuilder:validation:Minimum=0 + // +optional + From *uint32 `json:"from,omitempty"` } // ClusterNetworkEntry is a subnet from which to allocate PodIPs. A network of size @@ -139,8 +174,7 @@ type DefaultNetworkDefinition struct { // +optional OpenShiftSDNConfig *OpenShiftSDNConfig `json:"openshiftSDNConfig,omitempty"` - // oVNKubernetesConfig configures the ovn-kubernetes plugin. This is currently - // not implemented. + // ovnKubernetesConfig configures the ovn-kubernetes plugin. // +optional OVNKubernetesConfig *OVNKubernetesConfig `json:"ovnKubernetesConfig,omitempty"` @@ -374,6 +408,9 @@ type OVNKubernetesConfig struct { // reported defaults are used. // +optional PolicyAuditConfig *PolicyAuditConfig `json:"policyAuditConfig,omitempty"` + // gatewayConfig holds the configuration for node gateway options. + // +optional + GatewayConfig *GatewayConfig `json:"gatewayConfig,omitempty"` } type HybridOverlayConfig struct { @@ -388,6 +425,17 @@ type HybridOverlayConfig struct { type IPsecConfig struct { } +// GatewayConfig holds node gateway-related parsed config file parameters and command-line overrides +type GatewayConfig struct { + // RoutingViaHost allows pod egress traffic to exit via the ovn-k8s-mp0 management port + // into the host before sending it out. If this is not set, traffic will always egress directly + // from OVN to outside without touching the host stack. Setting this to true means hardware + // offload will not be supported. Default is false if GatewayConfig is specified. + // +kubebuilder:default:=false + // +optional + RoutingViaHost bool `json:"routingViaHost,omitempty"` +} + type ExportNetworkFlows struct { // netFlow defines the NetFlow configuration. // +optional diff --git a/vendor/github.com/openshift/api/operator/v1/zz_generated.deepcopy.go b/vendor/github.com/openshift/api/operator/v1/zz_generated.deepcopy.go index c6938bfbb43..23859af6d2b 100644 --- a/vendor/github.com/openshift/api/operator/v1/zz_generated.deepcopy.go +++ b/vendor/github.com/openshift/api/operator/v1/zz_generated.deepcopy.go @@ -1,3 +1,4 @@ +//go:build !ignore_autogenerated // +build !ignore_autogenerated // Code generated by deepcopy-gen. DO NOT EDIT. @@ -927,6 +928,7 @@ func (in *DNSSpec) DeepCopyInto(out *DNSSpec) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + in.UpstreamResolvers.DeepCopyInto(&out.UpstreamResolvers) in.NodePlacement.DeepCopyInto(&out.NodePlacement) return } @@ -1262,6 +1264,22 @@ func (in *GCPLoadBalancerParameters) DeepCopy() *GCPLoadBalancerParameters { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GatewayConfig) DeepCopyInto(out *GatewayConfig) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GatewayConfig. +func (in *GatewayConfig) DeepCopy() *GatewayConfig { + if in == nil { + return nil + } + out := new(GatewayConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GenerationStatus) DeepCopyInto(out *GenerationStatus) { *out = *in @@ -2207,6 +2225,58 @@ func (in *LoggingDestination) DeepCopy() *LoggingDestination { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MTUMigration) DeepCopyInto(out *MTUMigration) { + *out = *in + if in.Network != nil { + in, out := &in.Network, &out.Network + *out = new(MTUMigrationValues) + (*in).DeepCopyInto(*out) + } + if in.Machine != nil { + in, out := &in.Machine, &out.Machine + *out = new(MTUMigrationValues) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MTUMigration. +func (in *MTUMigration) DeepCopy() *MTUMigration { + if in == nil { + return nil + } + out := new(MTUMigration) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MTUMigrationValues) DeepCopyInto(out *MTUMigrationValues) { + *out = *in + if in.To != nil { + in, out := &in.To, &out.To + *out = new(uint32) + **out = **in + } + if in.From != nil { + in, out := &in.From, &out.From + *out = new(uint32) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MTUMigrationValues. +func (in *MTUMigrationValues) DeepCopy() *MTUMigrationValues { + if in == nil { + return nil + } + out := new(MTUMigrationValues) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MyOperatorResource) DeepCopyInto(out *MyOperatorResource) { *out = *in @@ -2346,6 +2416,11 @@ func (in *NetworkList) DeepCopyObject() runtime.Object { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NetworkMigration) DeepCopyInto(out *NetworkMigration) { *out = *in + if in.MTU != nil { + in, out := &in.MTU, &out.MTU + *out = new(MTUMigration) + (*in).DeepCopyInto(*out) + } return } @@ -2409,7 +2484,7 @@ func (in *NetworkSpec) DeepCopyInto(out *NetworkSpec) { if in.Migration != nil { in, out := &in.Migration, &out.Migration *out = new(NetworkMigration) - **out = **in + (*in).DeepCopyInto(*out) } return } @@ -2554,6 +2629,11 @@ func (in *OVNKubernetesConfig) DeepCopyInto(out *OVNKubernetesConfig) { *out = new(PolicyAuditConfig) (*in).DeepCopyInto(*out) } + if in.GatewayConfig != nil { + in, out := &in.GatewayConfig, &out.GatewayConfig + *out = new(GatewayConfig) + **out = **in + } return } @@ -3638,3 +3718,40 @@ func (in *SyslogLoggingDestinationParameters) DeepCopy() *SyslogLoggingDestinati in.DeepCopyInto(out) return out } + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Upstream) DeepCopyInto(out *Upstream) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Upstream. +func (in *Upstream) DeepCopy() *Upstream { + if in == nil { + return nil + } + out := new(Upstream) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *UpstreamResolvers) DeepCopyInto(out *UpstreamResolvers) { + *out = *in + if in.Upstreams != nil { + in, out := &in.Upstreams, &out.Upstreams + *out = make([]Upstream, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UpstreamResolvers. +func (in *UpstreamResolvers) DeepCopy() *UpstreamResolvers { + if in == nil { + return nil + } + out := new(UpstreamResolvers) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/github.com/openshift/api/operator/v1/zz_generated.swagger_doc_generated.go b/vendor/github.com/openshift/api/operator/v1/zz_generated.swagger_doc_generated.go index 95b3fd700cd..e42c685eb9b 100644 --- a/vendor/github.com/openshift/api/operator/v1/zz_generated.swagger_doc_generated.go +++ b/vendor/github.com/openshift/api/operator/v1/zz_generated.swagger_doc_generated.go @@ -422,12 +422,13 @@ func (DNSNodePlacement) SwaggerDoc() map[string]string { } var map_DNSSpec = map[string]string{ - "": "DNSSpec is the specification of the desired behavior of the DNS.", - "servers": "servers is a list of DNS resolvers that provide name query delegation for one or more subdomains outside the scope of the cluster domain. If servers consists of more than one Server, longest suffix match will be used to determine the Server.\n\nFor example, if there are two Servers, one for \"foo.com\" and another for \"a.foo.com\", and the name query is for \"www.a.foo.com\", it will be routed to the Server with Zone \"a.foo.com\".\n\nIf this field is nil, no servers are created.", - "nodePlacement": "nodePlacement provides explicit control over the scheduling of DNS pods.\n\nGenerally, it is useful to run a DNS pod on every node so that DNS queries are always handled by a local DNS pod instead of going over the network to a DNS pod on another node. However, security policies may require restricting the placement of DNS pods to specific nodes. For example, if a security policy prohibits pods on arbitrary nodes from communicating with the API, a node selector can be specified to restrict DNS pods to nodes that are permitted to communicate with the API. Conversely, if running DNS pods on nodes with a particular taint is desired, a toleration can be specified for that taint.\n\nIf unset, defaults are used. See nodePlacement for more details.", - "managementState": "managementState indicates whether the DNS operator should manage cluster DNS", - "operatorLogLevel": "operatorLogLevel controls the logging level of the DNS Operator. Valid values are: \"Normal\", \"Debug\", \"Trace\". Defaults to \"Normal\". setting operatorLogLevel: Trace will produce extremely verbose logs.", - "logLevel": "logLevel describes the desired logging verbosity for CoreDNS. Any one of the following values may be specified: * Normal logs errors from upstream resolvers. * Debug logs errors, NXDOMAIN responses, and NODATA responses. * Trace logs errors and all responses.\n Setting logLevel: Trace will produce extremely verbose logs.\nValid values are: \"Normal\", \"Debug\", \"Trace\". Defaults to \"Normal\".", + "": "DNSSpec is the specification of the desired behavior of the DNS.", + "servers": "servers is a list of DNS resolvers that provide name query delegation for one or more subdomains outside the scope of the cluster domain. If servers consists of more than one Server, longest suffix match will be used to determine the Server.\n\nFor example, if there are two Servers, one for \"foo.com\" and another for \"a.foo.com\", and the name query is for \"www.a.foo.com\", it will be routed to the Server with Zone \"a.foo.com\".\n\nIf this field is nil, no servers are created.", + "upstreamResolvers": "upstreamResolvers defines a schema for configuring CoreDNS to proxy DNS messages to upstream resolvers for the case of the default (\".\") server\n\nIf this field is not specified, the upstream used will default to /etc/resolv.conf, with policy \"sequential\"", + "nodePlacement": "nodePlacement provides explicit control over the scheduling of DNS pods.\n\nGenerally, it is useful to run a DNS pod on every node so that DNS queries are always handled by a local DNS pod instead of going over the network to a DNS pod on another node. However, security policies may require restricting the placement of DNS pods to specific nodes. For example, if a security policy prohibits pods on arbitrary nodes from communicating with the API, a node selector can be specified to restrict DNS pods to nodes that are permitted to communicate with the API. Conversely, if running DNS pods on nodes with a particular taint is desired, a toleration can be specified for that taint.\n\nIf unset, defaults are used. See nodePlacement for more details.", + "managementState": "managementState indicates whether the DNS operator should manage cluster DNS", + "operatorLogLevel": "operatorLogLevel controls the logging level of the DNS Operator. Valid values are: \"Normal\", \"Debug\", \"Trace\". Defaults to \"Normal\". setting operatorLogLevel: Trace will produce extremely verbose logs.", + "logLevel": "logLevel describes the desired logging verbosity for CoreDNS. Any one of the following values may be specified: * Normal logs errors from upstream resolvers. * Debug logs errors, NXDOMAIN responses, and NODATA responses. * Trace logs errors and all responses.\n Setting logLevel: Trace will produce extremely verbose logs.\nValid values are: \"Normal\", \"Debug\", \"Trace\". Defaults to \"Normal\".", } func (DNSSpec) SwaggerDoc() map[string]string { @@ -466,6 +467,27 @@ func (Server) SwaggerDoc() map[string]string { return map_Server } +var map_Upstream = map[string]string{ + "": "Upstream can either be of type SystemResolvConf, or of type Network.\n\n* For an Upstream of type SystemResolvConf, no further fields are necessary:\n The upstream will be configured to use /etc/resolv.conf.\n* For an Upstream of type Network, a NetworkResolver field needs to be defined\n with an IP address or IP:port if the upstream listens on a port other than 53.", + "type": "Type defines whether this upstream contains an IP/IP:port resolver or the local /etc/resolv.conf. Type accepts 2 possible values: SystemResolvConf or Network.\n\n* When SystemResolvConf is used, the Upstream structure does not require any further fields to be defined:\n /etc/resolv.conf will be used\n* When Network is used, the Upstream structure must contain at least an Address", + "address": "Address must be defined when Type is set to Network. It will be ignored otherwise. It must be a valid ipv4 or ipv6 address.", + "port": "Port may be defined when Type is set to Network. It will be ignored otherwise. Port must be between 65535", +} + +func (Upstream) SwaggerDoc() map[string]string { + return map_Upstream +} + +var map_UpstreamResolvers = map[string]string{ + "": "UpstreamResolvers defines a schema for configuring the CoreDNS forward plugin in the specific case of the default (\".\") server. It defers from ForwardPlugin in the default values it accepts: * At least one upstream should be specified. * the default policy is Sequential", + "upstreams": "Upstreams is a list of resolvers to forward name queries for the \".\" domain. Each instance of CoreDNS performs health checking of Upstreams. When a healthy upstream returns an error during the exchange, another resolver is tried from Upstreams. The Upstreams are selected in the order specified in Policy.\n\nA maximum of 15 upstreams is allowed per ForwardPlugin. If no Upstreams are specified, /etc/resolv.conf is used by default", + "policy": "Policy is used to determine the order in which upstream servers are selected for querying. Any one of the following values may be specified:\n\n* \"Random\" picks a random upstream server for each query. * \"RoundRobin\" picks upstream servers in a round-robin order, moving to the next server for each new query. * \"Sequential\" tries querying upstream servers in a sequential order until one responds, starting with the first server for each new query.\n\nThe default value is \"Sequential\"", +} + +func (UpstreamResolvers) SwaggerDoc() map[string]string { + return map_UpstreamResolvers +} + var map_Etcd = map[string]string{ "": "Etcd provides information to configure an operator to manage etcd.\n\nCompatibility level 1: Stable within a major release for a minimum of 12 months or 3 minor releases (whichever is longer).", } @@ -896,7 +918,7 @@ var map_DefaultNetworkDefinition = map[string]string{ "": "DefaultNetworkDefinition represents a single network plugin's configuration. type must be specified, along with exactly one \"Config\" that matches the type.", "type": "type is the type of network All NetworkTypes are supported except for NetworkTypeRaw", "openshiftSDNConfig": "openShiftSDNConfig configures the openshift-sdn plugin", - "ovnKubernetesConfig": "oVNKubernetesConfig configures the ovn-kubernetes plugin. This is currently not implemented.", + "ovnKubernetesConfig": "ovnKubernetesConfig configures the ovn-kubernetes plugin.", "kuryrConfig": "KuryrConfig configures the kuryr plugin", } @@ -914,6 +936,15 @@ func (ExportNetworkFlows) SwaggerDoc() map[string]string { return map_ExportNetworkFlows } +var map_GatewayConfig = map[string]string{ + "": "GatewayConfig holds node gateway-related parsed config file parameters and command-line overrides", + "routingViaHost": "RoutingViaHost allows pod egress traffic to exit via the ovn-k8s-mp0 management port into the host before sending it out. If this is not set, traffic will always egress directly from OVN to outside without touching the host stack. Setting this to true means hardware offload will not be supported. Default is false if GatewayConfig is specified.", +} + +func (GatewayConfig) SwaggerDoc() map[string]string { + return map_GatewayConfig +} + var map_HybridOverlayConfig = map[string]string{ "hybridClusterNetwork": "HybridClusterNetwork defines a network space given to nodes on an additional overlay network.", "hybridOverlayVXLANPort": "HybridOverlayVXLANPort defines the VXLAN port number to be used by the additional overlay network. Default is 4789", @@ -957,6 +988,26 @@ func (KuryrConfig) SwaggerDoc() map[string]string { return map_KuryrConfig } +var map_MTUMigration = map[string]string{ + "": "MTUMigration MTU contains infomation about MTU migration.", + "network": "network contains information about MTU migration for the default network. Migrations are only allowed to MTU values lower than the machine's uplink MTU by the minimum appropriate offset.", + "machine": "machine contains MTU migration configuration for the machine's uplink. Needs to be migrated along with the default network MTU unless the current uplink MTU already accommodates the default network MTU.", +} + +func (MTUMigration) SwaggerDoc() map[string]string { + return map_MTUMigration +} + +var map_MTUMigrationValues = map[string]string{ + "": "MTUMigrationValues contains the values for a MTU migration.", + "to": "to is the MTU to migrate to.", + "from": "from is the MTU to migrate from.", +} + +func (MTUMigrationValues) SwaggerDoc() map[string]string { + return map_MTUMigrationValues +} + var map_NetFlowConfig = map[string]string{ "collectors": "netFlow defines the NetFlow collectors that will consume the flow data exported from OVS. It is a list of strings formatted as ip:port with a maximum of ten items", } @@ -983,7 +1034,8 @@ func (NetworkList) SwaggerDoc() map[string]string { var map_NetworkMigration = map[string]string{ "": "NetworkMigration represents the cluster network configuration.", - "networkType": "networkType is the target type of network migration The supported values are OpenShiftSDN, OVNKubernetes", + "networkType": "networkType is the target type of network migration. Set this to the target network type to allow changing the default network. If unset, the operation of changing cluster default network plugin will be rejected. The supported values are OpenShiftSDN, OVNKubernetes", + "mtu": "mtu contains the MTU migration configuration. Set this to allow changing the MTU values for the default network. If unset, the operation of changing the MTU for the default network will be rejected.", } func (NetworkMigration) SwaggerDoc() map[string]string { @@ -1002,7 +1054,7 @@ var map_NetworkSpec = map[string]string{ "disableNetworkDiagnostics": "disableNetworkDiagnostics specifies whether or not PodNetworkConnectivityCheck CRs from a test pod to every node, apiserver and LB should be disabled or not. If unset, this property defaults to 'false' and network diagnostics is enabled. Setting this to 'true' would reduce the additional load of the pods performing the checks.", "kubeProxyConfig": "kubeProxyConfig lets us configure desired proxy configuration. If not specified, sensible defaults will be chosen by OpenShift directly. Not consumed by all network providers - currently only openshift-sdn.", "exportNetworkFlows": "exportNetworkFlows enables and configures the export of network flow metadata from the pod network by using protocols NetFlow, SFlow or IPFIX. Currently only supported on OVN-Kubernetes plugin. If unset, flows will not be exported to any collector.", - "migration": "migration enables and configures the cluster network migration. Setting this to the target network type to allow changing the default network. If unset, the operation of changing cluster default network plugin will be rejected.", + "migration": "migration enables and configures the cluster network migration. The migration procedure allows to change the network type and the MTU.", } func (NetworkSpec) SwaggerDoc() map[string]string { @@ -1024,6 +1076,7 @@ var map_OVNKubernetesConfig = map[string]string{ "hybridOverlayConfig": "HybridOverlayConfig configures an additional overlay network for peers that are not using OVN.", "ipsecConfig": "ipsecConfig enables and configures IPsec for pods on the pod network within the cluster.", "policyAuditConfig": "policyAuditConfig is the configuration for network policy audit events. If unset, reported defaults are used.", + "gatewayConfig": "gatewayConfig holds the configuration for node gateway options.", } func (OVNKubernetesConfig) SwaggerDoc() map[string]string { diff --git a/vendor/github.com/openshift/api/operator/v1alpha1/zz_generated.deepcopy.go b/vendor/github.com/openshift/api/operator/v1alpha1/zz_generated.deepcopy.go index 79f75bd0bea..4013889c6f2 100644 --- a/vendor/github.com/openshift/api/operator/v1alpha1/zz_generated.deepcopy.go +++ b/vendor/github.com/openshift/api/operator/v1alpha1/zz_generated.deepcopy.go @@ -1,3 +1,4 @@ +//go:build !ignore_autogenerated // +build !ignore_autogenerated // Code generated by deepcopy-gen. DO NOT EDIT. diff --git a/vendor/github.com/openshift/api/route/v1/zz_generated.deepcopy.go b/vendor/github.com/openshift/api/route/v1/zz_generated.deepcopy.go index a9576c414ca..ad8aa77fc7b 100644 --- a/vendor/github.com/openshift/api/route/v1/zz_generated.deepcopy.go +++ b/vendor/github.com/openshift/api/route/v1/zz_generated.deepcopy.go @@ -1,3 +1,4 @@ +//go:build !ignore_autogenerated // +build !ignore_autogenerated // Code generated by deepcopy-gen. DO NOT EDIT. diff --git a/vendor/github.com/openshift/client-go/config/clientset/versioned/clientset.go b/vendor/github.com/openshift/client-go/config/clientset/versioned/clientset.go index 70cd52cc073..992f9b22c97 100644 --- a/vendor/github.com/openshift/client-go/config/clientset/versioned/clientset.go +++ b/vendor/github.com/openshift/client-go/config/clientset/versioned/clientset.go @@ -4,6 +4,7 @@ package versioned import ( "fmt" + "net/http" configv1 "github.com/openshift/client-go/config/clientset/versioned/typed/config/v1" discovery "k8s.io/client-go/discovery" @@ -39,22 +40,41 @@ func (c *Clientset) Discovery() discovery.DiscoveryInterface { // NewForConfig creates a new Clientset for the given config. // If config's RateLimiter is not set and QPS and Burst are acceptable, // NewForConfig will generate a rate-limiter in configShallowCopy. +// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), +// where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*Clientset, error) { configShallowCopy := *c + + // share the transport between all clients + httpClient, err := rest.HTTPClientFor(&configShallowCopy) + if err != nil { + return nil, err + } + + return NewForConfigAndClient(&configShallowCopy, httpClient) +} + +// NewForConfigAndClient creates a new Clientset for the given config and http client. +// Note the http client provided takes precedence over the configured transport values. +// If config's RateLimiter is not set and QPS and Burst are acceptable, +// NewForConfigAndClient will generate a rate-limiter in configShallowCopy. +func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, error) { + configShallowCopy := *c if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { if configShallowCopy.Burst <= 0 { return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0") } configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) } + var cs Clientset var err error - cs.configV1, err = configv1.NewForConfig(&configShallowCopy) + cs.configV1, err = configv1.NewForConfigAndClient(&configShallowCopy, httpClient) if err != nil { return nil, err } - cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) + cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfigAndClient(&configShallowCopy, httpClient) if err != nil { return nil, err } @@ -64,11 +84,11 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { // NewForConfigOrDie creates a new Clientset for the given config and // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *Clientset { - var cs Clientset - cs.configV1 = configv1.NewForConfigOrDie(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) - return &cs + cs, err := NewForConfig(c) + if err != nil { + panic(err) + } + return cs } // New creates a new Clientset for the given RESTClient. diff --git a/vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/config_client.go b/vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/config_client.go index 0f2182d2f5d..5792b9aa740 100644 --- a/vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/config_client.go +++ b/vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/config_client.go @@ -3,6 +3,8 @@ package v1 import ( + "net/http" + v1 "github.com/openshift/api/config/v1" "github.com/openshift/client-go/config/clientset/versioned/scheme" rest "k8s.io/client-go/rest" @@ -19,6 +21,7 @@ type ConfigV1Interface interface { DNSesGetter FeatureGatesGetter ImagesGetter + ImageContentPoliciesGetter InfrastructuresGetter IngressesGetter NetworksGetter @@ -70,6 +73,10 @@ func (c *ConfigV1Client) Images() ImageInterface { return newImages(c) } +func (c *ConfigV1Client) ImageContentPolicies() ImageContentPolicyInterface { + return newImageContentPolicies(c) +} + func (c *ConfigV1Client) Infrastructures() InfrastructureInterface { return newInfrastructures(c) } @@ -103,12 +110,28 @@ func (c *ConfigV1Client) Schedulers() SchedulerInterface { } // NewForConfig creates a new ConfigV1Client for the given config. +// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), +// where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*ConfigV1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } - client, err := rest.RESTClientFor(&config) + httpClient, err := rest.HTTPClientFor(&config) + if err != nil { + return nil, err + } + return NewForConfigAndClient(&config, httpClient) +} + +// NewForConfigAndClient creates a new ConfigV1Client for the given config and http client. +// Note the http client provided takes precedence over the configured transport values. +func NewForConfigAndClient(c *rest.Config, h *http.Client) (*ConfigV1Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err } diff --git a/vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/generated_expansion.go b/vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/generated_expansion.go index 50a4ec7f8f3..646801584ad 100644 --- a/vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/generated_expansion.go +++ b/vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/generated_expansion.go @@ -20,6 +20,8 @@ type FeatureGateExpansion interface{} type ImageExpansion interface{} +type ImageContentPolicyExpansion interface{} + type InfrastructureExpansion interface{} type IngressExpansion interface{} diff --git a/vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/imagecontentpolicy.go b/vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/imagecontentpolicy.go new file mode 100644 index 00000000000..17c441e5be4 --- /dev/null +++ b/vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/imagecontentpolicy.go @@ -0,0 +1,152 @@ +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + "time" + + v1 "github.com/openshift/api/config/v1" + scheme "github.com/openshift/client-go/config/clientset/versioned/scheme" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// ImageContentPoliciesGetter has a method to return a ImageContentPolicyInterface. +// A group's client should implement this interface. +type ImageContentPoliciesGetter interface { + ImageContentPolicies() ImageContentPolicyInterface +} + +// ImageContentPolicyInterface has methods to work with ImageContentPolicy resources. +type ImageContentPolicyInterface interface { + Create(ctx context.Context, imageContentPolicy *v1.ImageContentPolicy, opts metav1.CreateOptions) (*v1.ImageContentPolicy, error) + Update(ctx context.Context, imageContentPolicy *v1.ImageContentPolicy, opts metav1.UpdateOptions) (*v1.ImageContentPolicy, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.ImageContentPolicy, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.ImageContentPolicyList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ImageContentPolicy, err error) + ImageContentPolicyExpansion +} + +// imageContentPolicies implements ImageContentPolicyInterface +type imageContentPolicies struct { + client rest.Interface +} + +// newImageContentPolicies returns a ImageContentPolicies +func newImageContentPolicies(c *ConfigV1Client) *imageContentPolicies { + return &imageContentPolicies{ + client: c.RESTClient(), + } +} + +// Get takes name of the imageContentPolicy, and returns the corresponding imageContentPolicy object, and an error if there is any. +func (c *imageContentPolicies) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ImageContentPolicy, err error) { + result = &v1.ImageContentPolicy{} + err = c.client.Get(). + Resource("imagecontentpolicies"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of ImageContentPolicies that match those selectors. +func (c *imageContentPolicies) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ImageContentPolicyList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.ImageContentPolicyList{} + err = c.client.Get(). + Resource("imagecontentpolicies"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested imageContentPolicies. +func (c *imageContentPolicies) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Resource("imagecontentpolicies"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a imageContentPolicy and creates it. Returns the server's representation of the imageContentPolicy, and an error, if there is any. +func (c *imageContentPolicies) Create(ctx context.Context, imageContentPolicy *v1.ImageContentPolicy, opts metav1.CreateOptions) (result *v1.ImageContentPolicy, err error) { + result = &v1.ImageContentPolicy{} + err = c.client.Post(). + Resource("imagecontentpolicies"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(imageContentPolicy). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a imageContentPolicy and updates it. Returns the server's representation of the imageContentPolicy, and an error, if there is any. +func (c *imageContentPolicies) Update(ctx context.Context, imageContentPolicy *v1.ImageContentPolicy, opts metav1.UpdateOptions) (result *v1.ImageContentPolicy, err error) { + result = &v1.ImageContentPolicy{} + err = c.client.Put(). + Resource("imagecontentpolicies"). + Name(imageContentPolicy.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(imageContentPolicy). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the imageContentPolicy and deletes it. Returns an error if one occurs. +func (c *imageContentPolicies) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Resource("imagecontentpolicies"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *imageContentPolicies) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Resource("imagecontentpolicies"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched imageContentPolicy. +func (c *imageContentPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ImageContentPolicy, err error) { + result = &v1.ImageContentPolicy{} + err = c.client.Patch(pt). + Resource("imagecontentpolicies"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/vendor/github.com/openshift/client-go/route/clientset/versioned/clientset.go b/vendor/github.com/openshift/client-go/route/clientset/versioned/clientset.go index 6689bcac66b..2d3ba95de00 100644 --- a/vendor/github.com/openshift/client-go/route/clientset/versioned/clientset.go +++ b/vendor/github.com/openshift/client-go/route/clientset/versioned/clientset.go @@ -4,6 +4,7 @@ package versioned import ( "fmt" + "net/http" routev1 "github.com/openshift/client-go/route/clientset/versioned/typed/route/v1" discovery "k8s.io/client-go/discovery" @@ -39,22 +40,41 @@ func (c *Clientset) Discovery() discovery.DiscoveryInterface { // NewForConfig creates a new Clientset for the given config. // If config's RateLimiter is not set and QPS and Burst are acceptable, // NewForConfig will generate a rate-limiter in configShallowCopy. +// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), +// where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*Clientset, error) { configShallowCopy := *c + + // share the transport between all clients + httpClient, err := rest.HTTPClientFor(&configShallowCopy) + if err != nil { + return nil, err + } + + return NewForConfigAndClient(&configShallowCopy, httpClient) +} + +// NewForConfigAndClient creates a new Clientset for the given config and http client. +// Note the http client provided takes precedence over the configured transport values. +// If config's RateLimiter is not set and QPS and Burst are acceptable, +// NewForConfigAndClient will generate a rate-limiter in configShallowCopy. +func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, error) { + configShallowCopy := *c if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { if configShallowCopy.Burst <= 0 { return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0") } configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) } + var cs Clientset var err error - cs.routeV1, err = routev1.NewForConfig(&configShallowCopy) + cs.routeV1, err = routev1.NewForConfigAndClient(&configShallowCopy, httpClient) if err != nil { return nil, err } - cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) + cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfigAndClient(&configShallowCopy, httpClient) if err != nil { return nil, err } @@ -64,11 +84,11 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { // NewForConfigOrDie creates a new Clientset for the given config and // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *Clientset { - var cs Clientset - cs.routeV1 = routev1.NewForConfigOrDie(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) - return &cs + cs, err := NewForConfig(c) + if err != nil { + panic(err) + } + return cs } // New creates a new Clientset for the given RESTClient. diff --git a/vendor/github.com/openshift/client-go/route/clientset/versioned/typed/route/v1/route_client.go b/vendor/github.com/openshift/client-go/route/clientset/versioned/typed/route/v1/route_client.go index 351945deab7..e71d826c9f2 100644 --- a/vendor/github.com/openshift/client-go/route/clientset/versioned/typed/route/v1/route_client.go +++ b/vendor/github.com/openshift/client-go/route/clientset/versioned/typed/route/v1/route_client.go @@ -3,6 +3,8 @@ package v1 import ( + "net/http" + v1 "github.com/openshift/api/route/v1" "github.com/openshift/client-go/route/clientset/versioned/scheme" rest "k8s.io/client-go/rest" @@ -23,12 +25,28 @@ func (c *RouteV1Client) Routes(namespace string) RouteInterface { } // NewForConfig creates a new RouteV1Client for the given config. +// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), +// where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*RouteV1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } - client, err := rest.RESTClientFor(&config) + httpClient, err := rest.HTTPClientFor(&config) + if err != nil { + return nil, err + } + return NewForConfigAndClient(&config, httpClient) +} + +// NewForConfigAndClient creates a new RouteV1Client for the given config and http client. +// Note the http client provided takes precedence over the configured transport values. +func NewForConfigAndClient(c *rest.Config, h *http.Client) (*RouteV1Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err } diff --git a/vendor/github.com/peterbourgon/diskv/LICENSE b/vendor/github.com/peterbourgon/diskv/LICENSE deleted file mode 100644 index 41ce7f16e1d..00000000000 --- a/vendor/github.com/peterbourgon/diskv/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011-2012 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/peterbourgon/diskv/README.md b/vendor/github.com/peterbourgon/diskv/README.md deleted file mode 100644 index 3474739edc7..00000000000 --- a/vendor/github.com/peterbourgon/diskv/README.md +++ /dev/null @@ -1,141 +0,0 @@ -# What is diskv? - -Diskv (disk-vee) is a simple, persistent key-value store written in the Go -language. It starts with an incredibly simple API for storing arbitrary data on -a filesystem by key, and builds several layers of performance-enhancing -abstraction on top. The end result is a conceptually simple, but highly -performant, disk-backed storage system. - -[![Build Status][1]][2] - -[1]: https://drone.io/github.com/peterbourgon/diskv/status.png -[2]: https://drone.io/github.com/peterbourgon/diskv/latest - - -# Installing - -Install [Go 1][3], either [from source][4] or [with a prepackaged binary][5]. -Then, - -```bash -$ go get github.com/peterbourgon/diskv -``` - -[3]: http://golang.org -[4]: http://golang.org/doc/install/source -[5]: http://golang.org/doc/install - - -# Usage - -```go -package main - -import ( - "fmt" - "github.com/peterbourgon/diskv" -) - -func main() { - // Simplest transform function: put all the data files into the base dir. - flatTransform := func(s string) []string { return []string{} } - - // Initialize a new diskv store, rooted at "my-data-dir", with a 1MB cache. - d := diskv.New(diskv.Options{ - BasePath: "my-data-dir", - Transform: flatTransform, - CacheSizeMax: 1024 * 1024, - }) - - // Write three bytes to the key "alpha". - key := "alpha" - d.Write(key, []byte{'1', '2', '3'}) - - // Read the value back out of the store. - value, _ := d.Read(key) - fmt.Printf("%v\n", value) - - // Erase the key+value from the store (and the disk). - d.Erase(key) -} -``` - -More complex examples can be found in the "examples" subdirectory. - - -# Theory - -## Basic idea - -At its core, diskv is a map of a key (`string`) to arbitrary data (`[]byte`). -The data is written to a single file on disk, with the same name as the key. -The key determines where that file will be stored, via a user-provided -`TransformFunc`, which takes a key and returns a slice (`[]string`) -corresponding to a path list where the key file will be stored. The simplest -TransformFunc, - -```go -func SimpleTransform (key string) []string { - return []string{} -} -``` - -will place all keys in the same, base directory. The design is inspired by -[Redis diskstore][6]; a TransformFunc which emulates the default diskstore -behavior is available in the content-addressable-storage example. - -[6]: http://groups.google.com/group/redis-db/browse_thread/thread/d444bc786689bde9?pli=1 - -**Note** that your TransformFunc should ensure that one valid key doesn't -transform to a subset of another valid key. That is, it shouldn't be possible -to construct valid keys that resolve to directory names. As a concrete example, -if your TransformFunc splits on every 3 characters, then - -```go -d.Write("abcabc", val) // OK: written to /abc/abc/abcabc -d.Write("abc", val) // Error: attempted write to /abc/abc, but it's a directory -``` - -This will be addressed in an upcoming version of diskv. - -Probably the most important design principle behind diskv is that your data is -always flatly available on the disk. diskv will never do anything that would -prevent you from accessing, copying, backing up, or otherwise interacting with -your data via common UNIX commandline tools. - -## Adding a cache - -An in-memory caching layer is provided by combining the BasicStore -functionality with a simple map structure, and keeping it up-to-date as -appropriate. Since the map structure in Go is not threadsafe, it's combined -with a RWMutex to provide safe concurrent access. - -## Adding order - -diskv is a key-value store and therefore inherently unordered. An ordering -system can be injected into the store by passing something which satisfies the -diskv.Index interface. (A default implementation, using Google's -[btree][7] package, is provided.) Basically, diskv keeps an ordered (by a -user-provided Less function) index of the keys, which can be queried. - -[7]: https://github.com/google/btree - -## Adding compression - -Something which implements the diskv.Compression interface may be passed -during store creation, so that all Writes and Reads are filtered through -a compression/decompression pipeline. Several default implementations, -using stdlib compression algorithms, are provided. Note that data is cached -compressed; the cost of decompression is borne with each Read. - -## Streaming - -diskv also now provides ReadStream and WriteStream methods, to allow very large -data to be handled efficiently. - - -# Future plans - - * Needs plenty of robust testing: huge datasets, etc... - * More thorough benchmarking - * Your suggestions for use-cases I haven't thought of diff --git a/vendor/github.com/peterbourgon/diskv/compression.go b/vendor/github.com/peterbourgon/diskv/compression.go deleted file mode 100644 index 5192b027330..00000000000 --- a/vendor/github.com/peterbourgon/diskv/compression.go +++ /dev/null @@ -1,64 +0,0 @@ -package diskv - -import ( - "compress/flate" - "compress/gzip" - "compress/zlib" - "io" -) - -// Compression is an interface that Diskv uses to implement compression of -// data. Writer takes a destination io.Writer and returns a WriteCloser that -// compresses all data written through it. Reader takes a source io.Reader and -// returns a ReadCloser that decompresses all data read through it. You may -// define these methods on your own type, or use one of the NewCompression -// helpers. -type Compression interface { - Writer(dst io.Writer) (io.WriteCloser, error) - Reader(src io.Reader) (io.ReadCloser, error) -} - -// NewGzipCompression returns a Gzip-based Compression. -func NewGzipCompression() Compression { - return NewGzipCompressionLevel(flate.DefaultCompression) -} - -// NewGzipCompressionLevel returns a Gzip-based Compression with the given level. -func NewGzipCompressionLevel(level int) Compression { - return &genericCompression{ - wf: func(w io.Writer) (io.WriteCloser, error) { return gzip.NewWriterLevel(w, level) }, - rf: func(r io.Reader) (io.ReadCloser, error) { return gzip.NewReader(r) }, - } -} - -// NewZlibCompression returns a Zlib-based Compression. -func NewZlibCompression() Compression { - return NewZlibCompressionLevel(flate.DefaultCompression) -} - -// NewZlibCompressionLevel returns a Zlib-based Compression with the given level. -func NewZlibCompressionLevel(level int) Compression { - return NewZlibCompressionLevelDict(level, nil) -} - -// NewZlibCompressionLevelDict returns a Zlib-based Compression with the given -// level, based on the given dictionary. -func NewZlibCompressionLevelDict(level int, dict []byte) Compression { - return &genericCompression{ - func(w io.Writer) (io.WriteCloser, error) { return zlib.NewWriterLevelDict(w, level, dict) }, - func(r io.Reader) (io.ReadCloser, error) { return zlib.NewReaderDict(r, dict) }, - } -} - -type genericCompression struct { - wf func(w io.Writer) (io.WriteCloser, error) - rf func(r io.Reader) (io.ReadCloser, error) -} - -func (g *genericCompression) Writer(dst io.Writer) (io.WriteCloser, error) { - return g.wf(dst) -} - -func (g *genericCompression) Reader(src io.Reader) (io.ReadCloser, error) { - return g.rf(src) -} diff --git a/vendor/github.com/peterbourgon/diskv/diskv.go b/vendor/github.com/peterbourgon/diskv/diskv.go deleted file mode 100644 index 524dc0a6e3f..00000000000 --- a/vendor/github.com/peterbourgon/diskv/diskv.go +++ /dev/null @@ -1,624 +0,0 @@ -// Diskv (disk-vee) is a simple, persistent, key-value store. -// It stores all data flatly on the filesystem. - -package diskv - -import ( - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - "sync" - "syscall" -) - -const ( - defaultBasePath = "diskv" - defaultFilePerm os.FileMode = 0666 - defaultPathPerm os.FileMode = 0777 -) - -var ( - defaultTransform = func(s string) []string { return []string{} } - errCanceled = errors.New("canceled") - errEmptyKey = errors.New("empty key") - errBadKey = errors.New("bad key") - errImportDirectory = errors.New("can't import a directory") -) - -// TransformFunction transforms a key into a slice of strings, with each -// element in the slice representing a directory in the file path where the -// key's entry will eventually be stored. -// -// For example, if TransformFunc transforms "abcdef" to ["ab", "cde", "f"], -// the final location of the data file will be /ab/cde/f/abcdef -type TransformFunction func(s string) []string - -// Options define a set of properties that dictate Diskv behavior. -// All values are optional. -type Options struct { - BasePath string - Transform TransformFunction - CacheSizeMax uint64 // bytes - PathPerm os.FileMode - FilePerm os.FileMode - // If TempDir is set, it will enable filesystem atomic writes by - // writing temporary files to that location before being moved - // to BasePath. - // Note that TempDir MUST be on the same device/partition as - // BasePath. - TempDir string - - Index Index - IndexLess LessFunction - - Compression Compression -} - -// Diskv implements the Diskv interface. You shouldn't construct Diskv -// structures directly; instead, use the New constructor. -type Diskv struct { - Options - mu sync.RWMutex - cache map[string][]byte - cacheSize uint64 -} - -// New returns an initialized Diskv structure, ready to use. -// If the path identified by baseDir already contains data, -// it will be accessible, but not yet cached. -func New(o Options) *Diskv { - if o.BasePath == "" { - o.BasePath = defaultBasePath - } - if o.Transform == nil { - o.Transform = defaultTransform - } - if o.PathPerm == 0 { - o.PathPerm = defaultPathPerm - } - if o.FilePerm == 0 { - o.FilePerm = defaultFilePerm - } - - d := &Diskv{ - Options: o, - cache: map[string][]byte{}, - cacheSize: 0, - } - - if d.Index != nil && d.IndexLess != nil { - d.Index.Initialize(d.IndexLess, d.Keys(nil)) - } - - return d -} - -// Write synchronously writes the key-value pair to disk, making it immediately -// available for reads. Write relies on the filesystem to perform an eventual -// sync to physical media. If you need stronger guarantees, see WriteStream. -func (d *Diskv) Write(key string, val []byte) error { - return d.WriteStream(key, bytes.NewBuffer(val), false) -} - -// WriteStream writes the data represented by the io.Reader to the disk, under -// the provided key. If sync is true, WriteStream performs an explicit sync on -// the file as soon as it's written. -// -// bytes.Buffer provides io.Reader semantics for basic data types. -func (d *Diskv) WriteStream(key string, r io.Reader, sync bool) error { - if len(key) <= 0 { - return errEmptyKey - } - - d.mu.Lock() - defer d.mu.Unlock() - - return d.writeStreamWithLock(key, r, sync) -} - -// createKeyFileWithLock either creates the key file directly, or -// creates a temporary file in TempDir if it is set. -func (d *Diskv) createKeyFileWithLock(key string) (*os.File, error) { - if d.TempDir != "" { - if err := os.MkdirAll(d.TempDir, d.PathPerm); err != nil { - return nil, fmt.Errorf("temp mkdir: %s", err) - } - f, err := ioutil.TempFile(d.TempDir, "") - if err != nil { - return nil, fmt.Errorf("temp file: %s", err) - } - - if err := f.Chmod(d.FilePerm); err != nil { - f.Close() // error deliberately ignored - os.Remove(f.Name()) // error deliberately ignored - return nil, fmt.Errorf("chmod: %s", err) - } - return f, nil - } - - mode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC // overwrite if exists - f, err := os.OpenFile(d.completeFilename(key), mode, d.FilePerm) - if err != nil { - return nil, fmt.Errorf("open file: %s", err) - } - return f, nil -} - -// writeStream does no input validation checking. -func (d *Diskv) writeStreamWithLock(key string, r io.Reader, sync bool) error { - if err := d.ensurePathWithLock(key); err != nil { - return fmt.Errorf("ensure path: %s", err) - } - - f, err := d.createKeyFileWithLock(key) - if err != nil { - return fmt.Errorf("create key file: %s", err) - } - - wc := io.WriteCloser(&nopWriteCloser{f}) - if d.Compression != nil { - wc, err = d.Compression.Writer(f) - if err != nil { - f.Close() // error deliberately ignored - os.Remove(f.Name()) // error deliberately ignored - return fmt.Errorf("compression writer: %s", err) - } - } - - if _, err := io.Copy(wc, r); err != nil { - f.Close() // error deliberately ignored - os.Remove(f.Name()) // error deliberately ignored - return fmt.Errorf("i/o copy: %s", err) - } - - if err := wc.Close(); err != nil { - f.Close() // error deliberately ignored - os.Remove(f.Name()) // error deliberately ignored - return fmt.Errorf("compression close: %s", err) - } - - if sync { - if err := f.Sync(); err != nil { - f.Close() // error deliberately ignored - os.Remove(f.Name()) // error deliberately ignored - return fmt.Errorf("file sync: %s", err) - } - } - - if err := f.Close(); err != nil { - return fmt.Errorf("file close: %s", err) - } - - if f.Name() != d.completeFilename(key) { - if err := os.Rename(f.Name(), d.completeFilename(key)); err != nil { - os.Remove(f.Name()) // error deliberately ignored - return fmt.Errorf("rename: %s", err) - } - } - - if d.Index != nil { - d.Index.Insert(key) - } - - d.bustCacheWithLock(key) // cache only on read - - return nil -} - -// Import imports the source file into diskv under the destination key. If the -// destination key already exists, it's overwritten. If move is true, the -// source file is removed after a successful import. -func (d *Diskv) Import(srcFilename, dstKey string, move bool) (err error) { - if dstKey == "" { - return errEmptyKey - } - - if fi, err := os.Stat(srcFilename); err != nil { - return err - } else if fi.IsDir() { - return errImportDirectory - } - - d.mu.Lock() - defer d.mu.Unlock() - - if err := d.ensurePathWithLock(dstKey); err != nil { - return fmt.Errorf("ensure path: %s", err) - } - - if move { - if err := syscall.Rename(srcFilename, d.completeFilename(dstKey)); err == nil { - d.bustCacheWithLock(dstKey) - return nil - } else if err != syscall.EXDEV { - // If it failed due to being on a different device, fall back to copying - return err - } - } - - f, err := os.Open(srcFilename) - if err != nil { - return err - } - defer f.Close() - err = d.writeStreamWithLock(dstKey, f, false) - if err == nil && move { - err = os.Remove(srcFilename) - } - return err -} - -// Read reads the key and returns the value. -// If the key is available in the cache, Read won't touch the disk. -// If the key is not in the cache, Read will have the side-effect of -// lazily caching the value. -func (d *Diskv) Read(key string) ([]byte, error) { - rc, err := d.ReadStream(key, false) - if err != nil { - return []byte{}, err - } - defer rc.Close() - return ioutil.ReadAll(rc) -} - -// ReadStream reads the key and returns the value (data) as an io.ReadCloser. -// If the value is cached from a previous read, and direct is false, -// ReadStream will use the cached value. Otherwise, it will return a handle to -// the file on disk, and cache the data on read. -// -// If direct is true, ReadStream will lazily delete any cached value for the -// key, and return a direct handle to the file on disk. -// -// If compression is enabled, ReadStream taps into the io.Reader stream prior -// to decompression, and caches the compressed data. -func (d *Diskv) ReadStream(key string, direct bool) (io.ReadCloser, error) { - d.mu.RLock() - defer d.mu.RUnlock() - - if val, ok := d.cache[key]; ok { - if !direct { - buf := bytes.NewBuffer(val) - if d.Compression != nil { - return d.Compression.Reader(buf) - } - return ioutil.NopCloser(buf), nil - } - - go func() { - d.mu.Lock() - defer d.mu.Unlock() - d.uncacheWithLock(key, uint64(len(val))) - }() - } - - return d.readWithRLock(key) -} - -// read ignores the cache, and returns an io.ReadCloser representing the -// decompressed data for the given key, streamed from the disk. Clients should -// acquire a read lock on the Diskv and check the cache themselves before -// calling read. -func (d *Diskv) readWithRLock(key string) (io.ReadCloser, error) { - filename := d.completeFilename(key) - - fi, err := os.Stat(filename) - if err != nil { - return nil, err - } - if fi.IsDir() { - return nil, os.ErrNotExist - } - - f, err := os.Open(filename) - if err != nil { - return nil, err - } - - var r io.Reader - if d.CacheSizeMax > 0 { - r = newSiphon(f, d, key) - } else { - r = &closingReader{f} - } - - var rc = io.ReadCloser(ioutil.NopCloser(r)) - if d.Compression != nil { - rc, err = d.Compression.Reader(r) - if err != nil { - return nil, err - } - } - - return rc, nil -} - -// closingReader provides a Reader that automatically closes the -// embedded ReadCloser when it reaches EOF -type closingReader struct { - rc io.ReadCloser -} - -func (cr closingReader) Read(p []byte) (int, error) { - n, err := cr.rc.Read(p) - if err == io.EOF { - if closeErr := cr.rc.Close(); closeErr != nil { - return n, closeErr // close must succeed for Read to succeed - } - } - return n, err -} - -// siphon is like a TeeReader: it copies all data read through it to an -// internal buffer, and moves that buffer to the cache at EOF. -type siphon struct { - f *os.File - d *Diskv - key string - buf *bytes.Buffer -} - -// newSiphon constructs a siphoning reader that represents the passed file. -// When a successful series of reads ends in an EOF, the siphon will write -// the buffered data to Diskv's cache under the given key. -func newSiphon(f *os.File, d *Diskv, key string) io.Reader { - return &siphon{ - f: f, - d: d, - key: key, - buf: &bytes.Buffer{}, - } -} - -// Read implements the io.Reader interface for siphon. -func (s *siphon) Read(p []byte) (int, error) { - n, err := s.f.Read(p) - - if err == nil { - return s.buf.Write(p[0:n]) // Write must succeed for Read to succeed - } - - if err == io.EOF { - s.d.cacheWithoutLock(s.key, s.buf.Bytes()) // cache may fail - if closeErr := s.f.Close(); closeErr != nil { - return n, closeErr // close must succeed for Read to succeed - } - return n, err - } - - return n, err -} - -// Erase synchronously erases the given key from the disk and the cache. -func (d *Diskv) Erase(key string) error { - d.mu.Lock() - defer d.mu.Unlock() - - d.bustCacheWithLock(key) - - // erase from index - if d.Index != nil { - d.Index.Delete(key) - } - - // erase from disk - filename := d.completeFilename(key) - if s, err := os.Stat(filename); err == nil { - if s.IsDir() { - return errBadKey - } - if err = os.Remove(filename); err != nil { - return err - } - } else { - // Return err as-is so caller can do os.IsNotExist(err). - return err - } - - // clean up and return - d.pruneDirsWithLock(key) - return nil -} - -// EraseAll will delete all of the data from the store, both in the cache and on -// the disk. Note that EraseAll doesn't distinguish diskv-related data from non- -// diskv-related data. Care should be taken to always specify a diskv base -// directory that is exclusively for diskv data. -func (d *Diskv) EraseAll() error { - d.mu.Lock() - defer d.mu.Unlock() - d.cache = make(map[string][]byte) - d.cacheSize = 0 - if d.TempDir != "" { - os.RemoveAll(d.TempDir) // errors ignored - } - return os.RemoveAll(d.BasePath) -} - -// Has returns true if the given key exists. -func (d *Diskv) Has(key string) bool { - d.mu.Lock() - defer d.mu.Unlock() - - if _, ok := d.cache[key]; ok { - return true - } - - filename := d.completeFilename(key) - s, err := os.Stat(filename) - if err != nil { - return false - } - if s.IsDir() { - return false - } - - return true -} - -// Keys returns a channel that will yield every key accessible by the store, -// in undefined order. If a cancel channel is provided, closing it will -// terminate and close the keys channel. -func (d *Diskv) Keys(cancel <-chan struct{}) <-chan string { - return d.KeysPrefix("", cancel) -} - -// KeysPrefix returns a channel that will yield every key accessible by the -// store with the given prefix, in undefined order. If a cancel channel is -// provided, closing it will terminate and close the keys channel. If the -// provided prefix is the empty string, all keys will be yielded. -func (d *Diskv) KeysPrefix(prefix string, cancel <-chan struct{}) <-chan string { - var prepath string - if prefix == "" { - prepath = d.BasePath - } else { - prepath = d.pathFor(prefix) - } - c := make(chan string) - go func() { - filepath.Walk(prepath, walker(c, prefix, cancel)) - close(c) - }() - return c -} - -// walker returns a function which satisfies the filepath.WalkFunc interface. -// It sends every non-directory file entry down the channel c. -func walker(c chan<- string, prefix string, cancel <-chan struct{}) filepath.WalkFunc { - return func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - if info.IsDir() || !strings.HasPrefix(info.Name(), prefix) { - return nil // "pass" - } - - select { - case c <- info.Name(): - case <-cancel: - return errCanceled - } - - return nil - } -} - -// pathFor returns the absolute path for location on the filesystem where the -// data for the given key will be stored. -func (d *Diskv) pathFor(key string) string { - return filepath.Join(d.BasePath, filepath.Join(d.Transform(key)...)) -} - -// ensurePathWithLock is a helper function that generates all necessary -// directories on the filesystem for the given key. -func (d *Diskv) ensurePathWithLock(key string) error { - return os.MkdirAll(d.pathFor(key), d.PathPerm) -} - -// completeFilename returns the absolute path to the file for the given key. -func (d *Diskv) completeFilename(key string) string { - return filepath.Join(d.pathFor(key), key) -} - -// cacheWithLock attempts to cache the given key-value pair in the store's -// cache. It can fail if the value is larger than the cache's maximum size. -func (d *Diskv) cacheWithLock(key string, val []byte) error { - valueSize := uint64(len(val)) - if err := d.ensureCacheSpaceWithLock(valueSize); err != nil { - return fmt.Errorf("%s; not caching", err) - } - - // be very strict about memory guarantees - if (d.cacheSize + valueSize) > d.CacheSizeMax { - panic(fmt.Sprintf("failed to make room for value (%d/%d)", valueSize, d.CacheSizeMax)) - } - - d.cache[key] = val - d.cacheSize += valueSize - return nil -} - -// cacheWithoutLock acquires the store's (write) mutex and calls cacheWithLock. -func (d *Diskv) cacheWithoutLock(key string, val []byte) error { - d.mu.Lock() - defer d.mu.Unlock() - return d.cacheWithLock(key, val) -} - -func (d *Diskv) bustCacheWithLock(key string) { - if val, ok := d.cache[key]; ok { - d.uncacheWithLock(key, uint64(len(val))) - } -} - -func (d *Diskv) uncacheWithLock(key string, sz uint64) { - d.cacheSize -= sz - delete(d.cache, key) -} - -// pruneDirsWithLock deletes empty directories in the path walk leading to the -// key k. Typically this function is called after an Erase is made. -func (d *Diskv) pruneDirsWithLock(key string) error { - pathlist := d.Transform(key) - for i := range pathlist { - dir := filepath.Join(d.BasePath, filepath.Join(pathlist[:len(pathlist)-i]...)) - - // thanks to Steven Blenkinsop for this snippet - switch fi, err := os.Stat(dir); true { - case err != nil: - return err - case !fi.IsDir(): - panic(fmt.Sprintf("corrupt dirstate at %s", dir)) - } - - nlinks, err := filepath.Glob(filepath.Join(dir, "*")) - if err != nil { - return err - } else if len(nlinks) > 0 { - return nil // has subdirs -- do not prune - } - if err = os.Remove(dir); err != nil { - return err - } - } - - return nil -} - -// ensureCacheSpaceWithLock deletes entries from the cache in arbitrary order -// until the cache has at least valueSize bytes available. -func (d *Diskv) ensureCacheSpaceWithLock(valueSize uint64) error { - if valueSize > d.CacheSizeMax { - return fmt.Errorf("value size (%d bytes) too large for cache (%d bytes)", valueSize, d.CacheSizeMax) - } - - safe := func() bool { return (d.cacheSize + valueSize) <= d.CacheSizeMax } - - for key, val := range d.cache { - if safe() { - break - } - - d.uncacheWithLock(key, uint64(len(val))) - } - - if !safe() { - panic(fmt.Sprintf("%d bytes still won't fit in the cache! (max %d bytes)", valueSize, d.CacheSizeMax)) - } - - return nil -} - -// nopWriteCloser wraps an io.Writer and provides a no-op Close method to -// satisfy the io.WriteCloser interface. -type nopWriteCloser struct { - io.Writer -} - -func (wc *nopWriteCloser) Write(p []byte) (int, error) { return wc.Writer.Write(p) } -func (wc *nopWriteCloser) Close() error { return nil } diff --git a/vendor/github.com/peterbourgon/diskv/index.go b/vendor/github.com/peterbourgon/diskv/index.go deleted file mode 100644 index 96fee5152b1..00000000000 --- a/vendor/github.com/peterbourgon/diskv/index.go +++ /dev/null @@ -1,115 +0,0 @@ -package diskv - -import ( - "sync" - - "github.com/google/btree" -) - -// Index is a generic interface for things that can -// provide an ordered list of keys. -type Index interface { - Initialize(less LessFunction, keys <-chan string) - Insert(key string) - Delete(key string) - Keys(from string, n int) []string -} - -// LessFunction is used to initialize an Index of keys in a specific order. -type LessFunction func(string, string) bool - -// btreeString is a custom data type that satisfies the BTree Less interface, -// making the strings it wraps sortable by the BTree package. -type btreeString struct { - s string - l LessFunction -} - -// Less satisfies the BTree.Less interface using the btreeString's LessFunction. -func (s btreeString) Less(i btree.Item) bool { - return s.l(s.s, i.(btreeString).s) -} - -// BTreeIndex is an implementation of the Index interface using google/btree. -type BTreeIndex struct { - sync.RWMutex - LessFunction - *btree.BTree -} - -// Initialize populates the BTree tree with data from the keys channel, -// according to the passed less function. It's destructive to the BTreeIndex. -func (i *BTreeIndex) Initialize(less LessFunction, keys <-chan string) { - i.Lock() - defer i.Unlock() - i.LessFunction = less - i.BTree = rebuild(less, keys) -} - -// Insert inserts the given key (only) into the BTree tree. -func (i *BTreeIndex) Insert(key string) { - i.Lock() - defer i.Unlock() - if i.BTree == nil || i.LessFunction == nil { - panic("uninitialized index") - } - i.BTree.ReplaceOrInsert(btreeString{s: key, l: i.LessFunction}) -} - -// Delete removes the given key (only) from the BTree tree. -func (i *BTreeIndex) Delete(key string) { - i.Lock() - defer i.Unlock() - if i.BTree == nil || i.LessFunction == nil { - panic("uninitialized index") - } - i.BTree.Delete(btreeString{s: key, l: i.LessFunction}) -} - -// Keys yields a maximum of n keys in order. If the passed 'from' key is empty, -// Keys will return the first n keys. If the passed 'from' key is non-empty, the -// first key in the returned slice will be the key that immediately follows the -// passed key, in key order. -func (i *BTreeIndex) Keys(from string, n int) []string { - i.RLock() - defer i.RUnlock() - - if i.BTree == nil || i.LessFunction == nil { - panic("uninitialized index") - } - - if i.BTree.Len() <= 0 { - return []string{} - } - - btreeFrom := btreeString{s: from, l: i.LessFunction} - skipFirst := true - if len(from) <= 0 || !i.BTree.Has(btreeFrom) { - // no such key, so fabricate an always-smallest item - btreeFrom = btreeString{s: "", l: func(string, string) bool { return true }} - skipFirst = false - } - - keys := []string{} - iterator := func(i btree.Item) bool { - keys = append(keys, i.(btreeString).s) - return len(keys) < n - } - i.BTree.AscendGreaterOrEqual(btreeFrom, iterator) - - if skipFirst && len(keys) > 0 { - keys = keys[1:] - } - - return keys -} - -// rebuildIndex does the work of regenerating the index -// with the given keys. -func rebuild(less LessFunction, keys <-chan string) *btree.BTree { - tree := btree.New(2) - for key := range keys { - tree.ReplaceOrInsert(btreeString{s: key, l: less}) - } - return tree -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collectors/collectors.go b/vendor/github.com/prometheus/client_golang/prometheus/collectors/collectors.go new file mode 100644 index 00000000000..c4d0f5c35b7 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/collectors/collectors.go @@ -0,0 +1,16 @@ +// Copyright 2021 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package collectors provides implementations of prometheus.Collector to +// conveniently collect process and Go-related metrics. +package collectors diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collectors/dbstats_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/collectors/dbstats_collector.go new file mode 100644 index 00000000000..e09f149d761 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/collectors/dbstats_collector.go @@ -0,0 +1,119 @@ +// Copyright 2021 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package collectors + +import ( + "database/sql" + + "github.com/prometheus/client_golang/prometheus" +) + +type dbStatsCollector struct { + db *sql.DB + + maxOpenConnections *prometheus.Desc + + openConnections *prometheus.Desc + inUseConnections *prometheus.Desc + idleConnections *prometheus.Desc + + waitCount *prometheus.Desc + waitDuration *prometheus.Desc + maxIdleClosed *prometheus.Desc + maxIdleTimeClosed *prometheus.Desc + maxLifetimeClosed *prometheus.Desc +} + +// NewDBStatsCollector returns a collector that exports metrics about the given *sql.DB. +// See https://golang.org/pkg/database/sql/#DBStats for more information on stats. +func NewDBStatsCollector(db *sql.DB, dbName string) prometheus.Collector { + fqName := func(name string) string { + return "go_sql_" + name + } + return &dbStatsCollector{ + db: db, + maxOpenConnections: prometheus.NewDesc( + fqName("max_open_connections"), + "Maximum number of open connections to the database.", + nil, prometheus.Labels{"db_name": dbName}, + ), + openConnections: prometheus.NewDesc( + fqName("open_connections"), + "The number of established connections both in use and idle.", + nil, prometheus.Labels{"db_name": dbName}, + ), + inUseConnections: prometheus.NewDesc( + fqName("in_use_connections"), + "The number of connections currently in use.", + nil, prometheus.Labels{"db_name": dbName}, + ), + idleConnections: prometheus.NewDesc( + fqName("idle_connections"), + "The number of idle connections.", + nil, prometheus.Labels{"db_name": dbName}, + ), + waitCount: prometheus.NewDesc( + fqName("wait_count_total"), + "The total number of connections waited for.", + nil, prometheus.Labels{"db_name": dbName}, + ), + waitDuration: prometheus.NewDesc( + fqName("wait_duration_seconds_total"), + "The total time blocked waiting for a new connection.", + nil, prometheus.Labels{"db_name": dbName}, + ), + maxIdleClosed: prometheus.NewDesc( + fqName("max_idle_closed_total"), + "The total number of connections closed due to SetMaxIdleConns.", + nil, prometheus.Labels{"db_name": dbName}, + ), + maxIdleTimeClosed: prometheus.NewDesc( + fqName("max_idle_time_closed_total"), + "The total number of connections closed due to SetConnMaxIdleTime.", + nil, prometheus.Labels{"db_name": dbName}, + ), + maxLifetimeClosed: prometheus.NewDesc( + fqName("max_lifetime_closed_total"), + "The total number of connections closed due to SetConnMaxLifetime.", + nil, prometheus.Labels{"db_name": dbName}, + ), + } +} + +// Describe implements Collector. +func (c *dbStatsCollector) Describe(ch chan<- *prometheus.Desc) { + ch <- c.maxOpenConnections + ch <- c.openConnections + ch <- c.inUseConnections + ch <- c.idleConnections + ch <- c.waitCount + ch <- c.waitDuration + ch <- c.maxIdleClosed + ch <- c.maxLifetimeClosed + c.describeNewInGo115(ch) +} + +// Collect implements Collector. +func (c *dbStatsCollector) Collect(ch chan<- prometheus.Metric) { + stats := c.db.Stats() + ch <- prometheus.MustNewConstMetric(c.maxOpenConnections, prometheus.GaugeValue, float64(stats.MaxOpenConnections)) + ch <- prometheus.MustNewConstMetric(c.openConnections, prometheus.GaugeValue, float64(stats.OpenConnections)) + ch <- prometheus.MustNewConstMetric(c.inUseConnections, prometheus.GaugeValue, float64(stats.InUse)) + ch <- prometheus.MustNewConstMetric(c.idleConnections, prometheus.GaugeValue, float64(stats.Idle)) + ch <- prometheus.MustNewConstMetric(c.waitCount, prometheus.CounterValue, float64(stats.WaitCount)) + ch <- prometheus.MustNewConstMetric(c.waitDuration, prometheus.CounterValue, stats.WaitDuration.Seconds()) + ch <- prometheus.MustNewConstMetric(c.maxIdleClosed, prometheus.CounterValue, float64(stats.MaxIdleClosed)) + ch <- prometheus.MustNewConstMetric(c.maxLifetimeClosed, prometheus.CounterValue, float64(stats.MaxLifetimeClosed)) + c.collectNewInGo115(ch, stats) +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collectors/dbstats_collector_go115.go b/vendor/github.com/prometheus/client_golang/prometheus/collectors/dbstats_collector_go115.go new file mode 100644 index 00000000000..a6e6268ce37 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/collectors/dbstats_collector_go115.go @@ -0,0 +1,30 @@ +// Copyright 2021 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build go1.15 + +package collectors + +import ( + "database/sql" + + "github.com/prometheus/client_golang/prometheus" +) + +func (c *dbStatsCollector) describeNewInGo115(ch chan<- *prometheus.Desc) { + ch <- c.maxIdleTimeClosed +} + +func (c *dbStatsCollector) collectNewInGo115(ch chan<- prometheus.Metric, stats sql.DBStats) { + ch <- prometheus.MustNewConstMetric(c.maxIdleTimeClosed, prometheus.CounterValue, float64(stats.MaxIdleTimeClosed)) +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collectors/dbstats_collector_pre_go115.go b/vendor/github.com/prometheus/client_golang/prometheus/collectors/dbstats_collector_pre_go115.go new file mode 100644 index 00000000000..0568affe297 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/collectors/dbstats_collector_pre_go115.go @@ -0,0 +1,26 @@ +// Copyright 2021 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build !go1.15 + +package collectors + +import ( + "database/sql" + + "github.com/prometheus/client_golang/prometheus" +) + +func (c *dbStatsCollector) describeNewInGo115(ch chan<- *prometheus.Desc) {} + +func (c *dbStatsCollector) collectNewInGo115(ch chan<- prometheus.Metric, stats sql.DBStats) {} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collectors/expvar_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/collectors/expvar_collector.go new file mode 100644 index 00000000000..3aa8d0590ba --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/collectors/expvar_collector.go @@ -0,0 +1,57 @@ +// Copyright 2021 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package collectors + +import "github.com/prometheus/client_golang/prometheus" + +// NewExpvarCollector returns a newly allocated expvar Collector. +// +// An expvar Collector collects metrics from the expvar interface. It provides a +// quick way to expose numeric values that are already exported via expvar as +// Prometheus metrics. Note that the data models of expvar and Prometheus are +// fundamentally different, and that the expvar Collector is inherently slower +// than native Prometheus metrics. Thus, the expvar Collector is probably great +// for experiments and prototying, but you should seriously consider a more +// direct implementation of Prometheus metrics for monitoring production +// systems. +// +// The exports map has the following meaning: +// +// The keys in the map correspond to expvar keys, i.e. for every expvar key you +// want to export as Prometheus metric, you need an entry in the exports +// map. The descriptor mapped to each key describes how to export the expvar +// value. It defines the name and the help string of the Prometheus metric +// proxying the expvar value. The type will always be Untyped. +// +// For descriptors without variable labels, the expvar value must be a number or +// a bool. The number is then directly exported as the Prometheus sample +// value. (For a bool, 'false' translates to 0 and 'true' to 1). Expvar values +// that are not numbers or bools are silently ignored. +// +// If the descriptor has one variable label, the expvar value must be an expvar +// map. The keys in the expvar map become the various values of the one +// Prometheus label. The values in the expvar map must be numbers or bools again +// as above. +// +// For descriptors with more than one variable label, the expvar must be a +// nested expvar map, i.e. where the values of the topmost map are maps again +// etc. until a depth is reached that corresponds to the number of labels. The +// leaves of that structure must be numbers or bools as above to serve as the +// sample values. +// +// Anything that does not fit into the scheme above is silently ignored. +func NewExpvarCollector(exports map[string]*prometheus.Desc) prometheus.Collector { + //nolint:staticcheck // Ignore SA1019 until v2. + return prometheus.NewExpvarCollector(exports) +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector.go new file mode 100644 index 00000000000..edaa4e50b7e --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector.go @@ -0,0 +1,69 @@ +// Copyright 2021 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package collectors + +import "github.com/prometheus/client_golang/prometheus" + +// NewGoCollector returns a collector that exports metrics about the current Go +// process. This includes memory stats. To collect those, runtime.ReadMemStats +// is called. This requires to “stop the world”, which usually only happens for +// garbage collection (GC). Take the following implications into account when +// deciding whether to use the Go collector: +// +// 1. The performance impact of stopping the world is the more relevant the more +// frequently metrics are collected. However, with Go1.9 or later the +// stop-the-world time per metrics collection is very short (~25µs) so that the +// performance impact will only matter in rare cases. However, with older Go +// versions, the stop-the-world duration depends on the heap size and can be +// quite significant (~1.7 ms/GiB as per +// https://go-review.googlesource.com/c/go/+/34937). +// +// 2. During an ongoing GC, nothing else can stop the world. Therefore, if the +// metrics collection happens to coincide with GC, it will only complete after +// GC has finished. Usually, GC is fast enough to not cause problems. However, +// with a very large heap, GC might take multiple seconds, which is enough to +// cause scrape timeouts in common setups. To avoid this problem, the Go +// collector will use the memstats from a previous collection if +// runtime.ReadMemStats takes more than 1s. However, if there are no previously +// collected memstats, or their collection is more than 5m ago, the collection +// will block until runtime.ReadMemStats succeeds. +// +// NOTE: The problem is solved in Go 1.15, see +// https://github.com/golang/go/issues/19812 for the related Go issue. +func NewGoCollector() prometheus.Collector { + //nolint:staticcheck // Ignore SA1019 until v2. + return prometheus.NewGoCollector() +} + +// NewBuildInfoCollector returns a collector collecting a single metric +// "go_build_info" with the constant value 1 and three labels "path", "version", +// and "checksum". Their label values contain the main module path, version, and +// checksum, respectively. The labels will only have meaningful values if the +// binary is built with Go module support and from source code retrieved from +// the source repository (rather than the local file system). This is usually +// accomplished by building from outside of GOPATH, specifying the full address +// of the main package, e.g. "GO111MODULE=on go run +// github.com/prometheus/client_golang/examples/random". If built without Go +// module support, all label values will be "unknown". If built with Go module +// support but using the source code from the local file system, the "path" will +// be set appropriately, but "checksum" will be empty and "version" will be +// "(devel)". +// +// This collector uses only the build information for the main module. See +// https://github.com/povilasv/prommod for an example of a collector for the +// module dependencies. +func NewBuildInfoCollector() prometheus.Collector { + //nolint:staticcheck // Ignore SA1019 until v2. + return prometheus.NewBuildInfoCollector() +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collectors/process_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/collectors/process_collector.go new file mode 100644 index 00000000000..24558f50a76 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/collectors/process_collector.go @@ -0,0 +1,56 @@ +// Copyright 2021 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package collectors + +import "github.com/prometheus/client_golang/prometheus" + +// ProcessCollectorOpts defines the behavior of a process metrics collector +// created with NewProcessCollector. +type ProcessCollectorOpts struct { + // PidFn returns the PID of the process the collector collects metrics + // for. It is called upon each collection. By default, the PID of the + // current process is used, as determined on construction time by + // calling os.Getpid(). + PidFn func() (int, error) + // If non-empty, each of the collected metrics is prefixed by the + // provided string and an underscore ("_"). + Namespace string + // If true, any error encountered during collection is reported as an + // invalid metric (see NewInvalidMetric). Otherwise, errors are ignored + // and the collected metrics will be incomplete. (Possibly, no metrics + // will be collected at all.) While that's usually not desired, it is + // appropriate for the common "mix-in" of process metrics, where process + // metrics are nice to have, but failing to collect them should not + // disrupt the collection of the remaining metrics. + ReportErrors bool +} + +// NewProcessCollector returns a collector which exports the current state of +// process metrics including CPU, memory and file descriptor usage as well as +// the process start time. The detailed behavior is defined by the provided +// ProcessCollectorOpts. The zero value of ProcessCollectorOpts creates a +// collector for the current process with an empty namespace string and no error +// reporting. +// +// The collector only works on operating systems with a Linux-style proc +// filesystem and on Microsoft Windows. On other operating systems, it will not +// collect any metrics. +func NewProcessCollector(opts ProcessCollectorOpts) prometheus.Collector { + //nolint:staticcheck // Ignore SA1019 until v2. + return prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{ + PidFn: opts.PidFn, + Namespace: opts.Namespace, + ReportErrors: opts.ReportErrors, + }) +} diff --git a/vendor/github.com/robfig/cron/.gitignore b/vendor/github.com/robfig/cron/.gitignore deleted file mode 100644 index 00268614f04..00000000000 --- a/vendor/github.com/robfig/cron/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe diff --git a/vendor/github.com/robfig/cron/.travis.yml b/vendor/github.com/robfig/cron/.travis.yml deleted file mode 100644 index 4f2ee4d9733..00000000000 --- a/vendor/github.com/robfig/cron/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: go diff --git a/vendor/github.com/robfig/cron/LICENSE b/vendor/github.com/robfig/cron/LICENSE deleted file mode 100644 index 3a0f627ffeb..00000000000 --- a/vendor/github.com/robfig/cron/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (C) 2012 Rob Figueiredo -All Rights Reserved. - -MIT LICENSE - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/robfig/cron/README.md b/vendor/github.com/robfig/cron/README.md deleted file mode 100644 index ec40c95fcb9..00000000000 --- a/vendor/github.com/robfig/cron/README.md +++ /dev/null @@ -1,6 +0,0 @@ -[![GoDoc](http://godoc.org/github.com/robfig/cron?status.png)](http://godoc.org/github.com/robfig/cron) -[![Build Status](https://travis-ci.org/robfig/cron.svg?branch=master)](https://travis-ci.org/robfig/cron) - -# cron - -Documentation here: https://godoc.org/github.com/robfig/cron diff --git a/vendor/github.com/robfig/cron/constantdelay.go b/vendor/github.com/robfig/cron/constantdelay.go deleted file mode 100644 index cd6e7b1be91..00000000000 --- a/vendor/github.com/robfig/cron/constantdelay.go +++ /dev/null @@ -1,27 +0,0 @@ -package cron - -import "time" - -// ConstantDelaySchedule represents a simple recurring duty cycle, e.g. "Every 5 minutes". -// It does not support jobs more frequent than once a second. -type ConstantDelaySchedule struct { - Delay time.Duration -} - -// Every returns a crontab Schedule that activates once every duration. -// Delays of less than a second are not supported (will round up to 1 second). -// Any fields less than a Second are truncated. -func Every(duration time.Duration) ConstantDelaySchedule { - if duration < time.Second { - duration = time.Second - } - return ConstantDelaySchedule{ - Delay: duration - time.Duration(duration.Nanoseconds())%time.Second, - } -} - -// Next returns the next time this should be run. -// This rounds so that the next activation time will be on the second. -func (schedule ConstantDelaySchedule) Next(t time.Time) time.Time { - return t.Add(schedule.Delay - time.Duration(t.Nanosecond())*time.Nanosecond) -} diff --git a/vendor/github.com/robfig/cron/cron.go b/vendor/github.com/robfig/cron/cron.go deleted file mode 100644 index 2318aeb2e7d..00000000000 --- a/vendor/github.com/robfig/cron/cron.go +++ /dev/null @@ -1,259 +0,0 @@ -package cron - -import ( - "log" - "runtime" - "sort" - "time" -) - -// Cron keeps track of any number of entries, invoking the associated func as -// specified by the schedule. It may be started, stopped, and the entries may -// be inspected while running. -type Cron struct { - entries []*Entry - stop chan struct{} - add chan *Entry - snapshot chan []*Entry - running bool - ErrorLog *log.Logger - location *time.Location -} - -// Job is an interface for submitted cron jobs. -type Job interface { - Run() -} - -// The Schedule describes a job's duty cycle. -type Schedule interface { - // Return the next activation time, later than the given time. - // Next is invoked initially, and then each time the job is run. - Next(time.Time) time.Time -} - -// Entry consists of a schedule and the func to execute on that schedule. -type Entry struct { - // The schedule on which this job should be run. - Schedule Schedule - - // The next time the job will run. This is the zero time if Cron has not been - // started or this entry's schedule is unsatisfiable - Next time.Time - - // The last time this job was run. This is the zero time if the job has never - // been run. - Prev time.Time - - // The Job to run. - Job Job -} - -// byTime is a wrapper for sorting the entry array by time -// (with zero time at the end). -type byTime []*Entry - -func (s byTime) Len() int { return len(s) } -func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s byTime) Less(i, j int) bool { - // Two zero times should return false. - // Otherwise, zero is "greater" than any other time. - // (To sort it at the end of the list.) - if s[i].Next.IsZero() { - return false - } - if s[j].Next.IsZero() { - return true - } - return s[i].Next.Before(s[j].Next) -} - -// New returns a new Cron job runner, in the Local time zone. -func New() *Cron { - return NewWithLocation(time.Now().Location()) -} - -// NewWithLocation returns a new Cron job runner. -func NewWithLocation(location *time.Location) *Cron { - return &Cron{ - entries: nil, - add: make(chan *Entry), - stop: make(chan struct{}), - snapshot: make(chan []*Entry), - running: false, - ErrorLog: nil, - location: location, - } -} - -// A wrapper that turns a func() into a cron.Job -type FuncJob func() - -func (f FuncJob) Run() { f() } - -// AddFunc adds a func to the Cron to be run on the given schedule. -func (c *Cron) AddFunc(spec string, cmd func()) error { - return c.AddJob(spec, FuncJob(cmd)) -} - -// AddJob adds a Job to the Cron to be run on the given schedule. -func (c *Cron) AddJob(spec string, cmd Job) error { - schedule, err := Parse(spec) - if err != nil { - return err - } - c.Schedule(schedule, cmd) - return nil -} - -// Schedule adds a Job to the Cron to be run on the given schedule. -func (c *Cron) Schedule(schedule Schedule, cmd Job) { - entry := &Entry{ - Schedule: schedule, - Job: cmd, - } - if !c.running { - c.entries = append(c.entries, entry) - return - } - - c.add <- entry -} - -// Entries returns a snapshot of the cron entries. -func (c *Cron) Entries() []*Entry { - if c.running { - c.snapshot <- nil - x := <-c.snapshot - return x - } - return c.entrySnapshot() -} - -// Location gets the time zone location -func (c *Cron) Location() *time.Location { - return c.location -} - -// Start the cron scheduler in its own go-routine, or no-op if already started. -func (c *Cron) Start() { - if c.running { - return - } - c.running = true - go c.run() -} - -// Run the cron scheduler, or no-op if already running. -func (c *Cron) Run() { - if c.running { - return - } - c.running = true - c.run() -} - -func (c *Cron) runWithRecovery(j Job) { - defer func() { - if r := recover(); r != nil { - const size = 64 << 10 - buf := make([]byte, size) - buf = buf[:runtime.Stack(buf, false)] - c.logf("cron: panic running job: %v\n%s", r, buf) - } - }() - j.Run() -} - -// Run the scheduler. this is private just due to the need to synchronize -// access to the 'running' state variable. -func (c *Cron) run() { - // Figure out the next activation times for each entry. - now := c.now() - for _, entry := range c.entries { - entry.Next = entry.Schedule.Next(now) - } - - for { - // Determine the next entry to run. - sort.Sort(byTime(c.entries)) - - var timer *time.Timer - if len(c.entries) == 0 || c.entries[0].Next.IsZero() { - // If there are no entries yet, just sleep - it still handles new entries - // and stop requests. - timer = time.NewTimer(100000 * time.Hour) - } else { - timer = time.NewTimer(c.entries[0].Next.Sub(now)) - } - - for { - select { - case now = <-timer.C: - now = now.In(c.location) - // Run every entry whose next time was less than now - for _, e := range c.entries { - if e.Next.After(now) || e.Next.IsZero() { - break - } - go c.runWithRecovery(e.Job) - e.Prev = e.Next - e.Next = e.Schedule.Next(now) - } - - case newEntry := <-c.add: - timer.Stop() - now = c.now() - newEntry.Next = newEntry.Schedule.Next(now) - c.entries = append(c.entries, newEntry) - - case <-c.snapshot: - c.snapshot <- c.entrySnapshot() - continue - - case <-c.stop: - timer.Stop() - return - } - - break - } - } -} - -// Logs an error to stderr or to the configured error log -func (c *Cron) logf(format string, args ...interface{}) { - if c.ErrorLog != nil { - c.ErrorLog.Printf(format, args...) - } else { - log.Printf(format, args...) - } -} - -// Stop stops the cron scheduler if it is running; otherwise it does nothing. -func (c *Cron) Stop() { - if !c.running { - return - } - c.stop <- struct{}{} - c.running = false -} - -// entrySnapshot returns a copy of the current cron entry list. -func (c *Cron) entrySnapshot() []*Entry { - entries := []*Entry{} - for _, e := range c.entries { - entries = append(entries, &Entry{ - Schedule: e.Schedule, - Next: e.Next, - Prev: e.Prev, - Job: e.Job, - }) - } - return entries -} - -// now returns current time in c location -func (c *Cron) now() time.Time { - return time.Now().In(c.location) -} diff --git a/vendor/github.com/robfig/cron/doc.go b/vendor/github.com/robfig/cron/doc.go deleted file mode 100644 index d02ec2f3b56..00000000000 --- a/vendor/github.com/robfig/cron/doc.go +++ /dev/null @@ -1,129 +0,0 @@ -/* -Package cron implements a cron spec parser and job runner. - -Usage - -Callers may register Funcs to be invoked on a given schedule. Cron will run -them in their own goroutines. - - c := cron.New() - c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") }) - c.AddFunc("@hourly", func() { fmt.Println("Every hour") }) - c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") }) - c.Start() - .. - // Funcs are invoked in their own goroutine, asynchronously. - ... - // Funcs may also be added to a running Cron - c.AddFunc("@daily", func() { fmt.Println("Every day") }) - .. - // Inspect the cron job entries' next and previous run times. - inspect(c.Entries()) - .. - c.Stop() // Stop the scheduler (does not stop any jobs already running). - -CRON Expression Format - -A cron expression represents a set of times, using 6 space-separated fields. - - Field name | Mandatory? | Allowed values | Allowed special characters - ---------- | ---------- | -------------- | -------------------------- - Seconds | Yes | 0-59 | * / , - - Minutes | Yes | 0-59 | * / , - - Hours | Yes | 0-23 | * / , - - Day of month | Yes | 1-31 | * / , - ? - Month | Yes | 1-12 or JAN-DEC | * / , - - Day of week | Yes | 0-6 or SUN-SAT | * / , - ? - -Note: Month and Day-of-week field values are case insensitive. "SUN", "Sun", -and "sun" are equally accepted. - -Special Characters - -Asterisk ( * ) - -The asterisk indicates that the cron expression will match for all values of the -field; e.g., using an asterisk in the 5th field (month) would indicate every -month. - -Slash ( / ) - -Slashes are used to describe increments of ranges. For example 3-59/15 in the -1st field (minutes) would indicate the 3rd minute of the hour and every 15 -minutes thereafter. The form "*\/..." is equivalent to the form "first-last/...", -that is, an increment over the largest possible range of the field. The form -"N/..." is accepted as meaning "N-MAX/...", that is, starting at N, use the -increment until the end of that specific range. It does not wrap around. - -Comma ( , ) - -Commas are used to separate items of a list. For example, using "MON,WED,FRI" in -the 5th field (day of week) would mean Mondays, Wednesdays and Fridays. - -Hyphen ( - ) - -Hyphens are used to define ranges. For example, 9-17 would indicate every -hour between 9am and 5pm inclusive. - -Question mark ( ? ) - -Question mark may be used instead of '*' for leaving either day-of-month or -day-of-week blank. - -Predefined schedules - -You may use one of several pre-defined schedules in place of a cron expression. - - Entry | Description | Equivalent To - ----- | ----------- | ------------- - @yearly (or @annually) | Run once a year, midnight, Jan. 1st | 0 0 0 1 1 * - @monthly | Run once a month, midnight, first of month | 0 0 0 1 * * - @weekly | Run once a week, midnight between Sat/Sun | 0 0 0 * * 0 - @daily (or @midnight) | Run once a day, midnight | 0 0 0 * * * - @hourly | Run once an hour, beginning of hour | 0 0 * * * * - -Intervals - -You may also schedule a job to execute at fixed intervals, starting at the time it's added -or cron is run. This is supported by formatting the cron spec like this: - - @every - -where "duration" is a string accepted by time.ParseDuration -(http://golang.org/pkg/time/#ParseDuration). - -For example, "@every 1h30m10s" would indicate a schedule that activates after -1 hour, 30 minutes, 10 seconds, and then every interval after that. - -Note: The interval does not take the job runtime into account. For example, -if a job takes 3 minutes to run, and it is scheduled to run every 5 minutes, -it will have only 2 minutes of idle time between each run. - -Time zones - -All interpretation and scheduling is done in the machine's local time zone (as -provided by the Go time package (http://www.golang.org/pkg/time). - -Be aware that jobs scheduled during daylight-savings leap-ahead transitions will -not be run! - -Thread safety - -Since the Cron service runs concurrently with the calling code, some amount of -care must be taken to ensure proper synchronization. - -All cron methods are designed to be correctly synchronized as long as the caller -ensures that invocations have a clear happens-before ordering between them. - -Implementation - -Cron entries are stored in an array, sorted by their next activation time. Cron -sleeps until the next job is due to be run. - -Upon waking: - - it runs each entry that is active on that second - - it calculates the next run times for the jobs that were run - - it re-sorts the array of entries by next activation time. - - it goes to sleep until the soonest job. -*/ -package cron diff --git a/vendor/github.com/robfig/cron/parser.go b/vendor/github.com/robfig/cron/parser.go deleted file mode 100644 index a5e83c0a8dc..00000000000 --- a/vendor/github.com/robfig/cron/parser.go +++ /dev/null @@ -1,380 +0,0 @@ -package cron - -import ( - "fmt" - "math" - "strconv" - "strings" - "time" -) - -// Configuration options for creating a parser. Most options specify which -// fields should be included, while others enable features. If a field is not -// included the parser will assume a default value. These options do not change -// the order fields are parse in. -type ParseOption int - -const ( - Second ParseOption = 1 << iota // Seconds field, default 0 - Minute // Minutes field, default 0 - Hour // Hours field, default 0 - Dom // Day of month field, default * - Month // Month field, default * - Dow // Day of week field, default * - DowOptional // Optional day of week field, default * - Descriptor // Allow descriptors such as @monthly, @weekly, etc. -) - -var places = []ParseOption{ - Second, - Minute, - Hour, - Dom, - Month, - Dow, -} - -var defaults = []string{ - "0", - "0", - "0", - "*", - "*", - "*", -} - -// A custom Parser that can be configured. -type Parser struct { - options ParseOption - optionals int -} - -// Creates a custom Parser with custom options. -// -// // Standard parser without descriptors -// specParser := NewParser(Minute | Hour | Dom | Month | Dow) -// sched, err := specParser.Parse("0 0 15 */3 *") -// -// // Same as above, just excludes time fields -// subsParser := NewParser(Dom | Month | Dow) -// sched, err := specParser.Parse("15 */3 *") -// -// // Same as above, just makes Dow optional -// subsParser := NewParser(Dom | Month | DowOptional) -// sched, err := specParser.Parse("15 */3") -// -func NewParser(options ParseOption) Parser { - optionals := 0 - if options&DowOptional > 0 { - options |= Dow - optionals++ - } - return Parser{options, optionals} -} - -// Parse returns a new crontab schedule representing the given spec. -// It returns a descriptive error if the spec is not valid. -// It accepts crontab specs and features configured by NewParser. -func (p Parser) Parse(spec string) (Schedule, error) { - if len(spec) == 0 { - return nil, fmt.Errorf("Empty spec string") - } - if spec[0] == '@' && p.options&Descriptor > 0 { - return parseDescriptor(spec) - } - - // Figure out how many fields we need - max := 0 - for _, place := range places { - if p.options&place > 0 { - max++ - } - } - min := max - p.optionals - - // Split fields on whitespace - fields := strings.Fields(spec) - - // Validate number of fields - if count := len(fields); count < min || count > max { - if min == max { - return nil, fmt.Errorf("Expected exactly %d fields, found %d: %s", min, count, spec) - } - return nil, fmt.Errorf("Expected %d to %d fields, found %d: %s", min, max, count, spec) - } - - // Fill in missing fields - fields = expandFields(fields, p.options) - - var err error - field := func(field string, r bounds) uint64 { - if err != nil { - return 0 - } - var bits uint64 - bits, err = getField(field, r) - return bits - } - - var ( - second = field(fields[0], seconds) - minute = field(fields[1], minutes) - hour = field(fields[2], hours) - dayofmonth = field(fields[3], dom) - month = field(fields[4], months) - dayofweek = field(fields[5], dow) - ) - if err != nil { - return nil, err - } - - return &SpecSchedule{ - Second: second, - Minute: minute, - Hour: hour, - Dom: dayofmonth, - Month: month, - Dow: dayofweek, - }, nil -} - -func expandFields(fields []string, options ParseOption) []string { - n := 0 - count := len(fields) - expFields := make([]string, len(places)) - copy(expFields, defaults) - for i, place := range places { - if options&place > 0 { - expFields[i] = fields[n] - n++ - } - if n == count { - break - } - } - return expFields -} - -var standardParser = NewParser( - Minute | Hour | Dom | Month | Dow | Descriptor, -) - -// ParseStandard returns a new crontab schedule representing the given standardSpec -// (https://en.wikipedia.org/wiki/Cron). It differs from Parse requiring to always -// pass 5 entries representing: minute, hour, day of month, month and day of week, -// in that order. It returns a descriptive error if the spec is not valid. -// -// It accepts -// - Standard crontab specs, e.g. "* * * * ?" -// - Descriptors, e.g. "@midnight", "@every 1h30m" -func ParseStandard(standardSpec string) (Schedule, error) { - return standardParser.Parse(standardSpec) -} - -var defaultParser = NewParser( - Second | Minute | Hour | Dom | Month | DowOptional | Descriptor, -) - -// Parse returns a new crontab schedule representing the given spec. -// It returns a descriptive error if the spec is not valid. -// -// It accepts -// - Full crontab specs, e.g. "* * * * * ?" -// - Descriptors, e.g. "@midnight", "@every 1h30m" -func Parse(spec string) (Schedule, error) { - return defaultParser.Parse(spec) -} - -// getField returns an Int with the bits set representing all of the times that -// the field represents or error parsing field value. A "field" is a comma-separated -// list of "ranges". -func getField(field string, r bounds) (uint64, error) { - var bits uint64 - ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' }) - for _, expr := range ranges { - bit, err := getRange(expr, r) - if err != nil { - return bits, err - } - bits |= bit - } - return bits, nil -} - -// getRange returns the bits indicated by the given expression: -// number | number "-" number [ "/" number ] -// or error parsing range. -func getRange(expr string, r bounds) (uint64, error) { - var ( - start, end, step uint - rangeAndStep = strings.Split(expr, "/") - lowAndHigh = strings.Split(rangeAndStep[0], "-") - singleDigit = len(lowAndHigh) == 1 - err error - ) - - var extra uint64 - if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" { - start = r.min - end = r.max - extra = starBit - } else { - start, err = parseIntOrName(lowAndHigh[0], r.names) - if err != nil { - return 0, err - } - switch len(lowAndHigh) { - case 1: - end = start - case 2: - end, err = parseIntOrName(lowAndHigh[1], r.names) - if err != nil { - return 0, err - } - default: - return 0, fmt.Errorf("Too many hyphens: %s", expr) - } - } - - switch len(rangeAndStep) { - case 1: - step = 1 - case 2: - step, err = mustParseInt(rangeAndStep[1]) - if err != nil { - return 0, err - } - - // Special handling: "N/step" means "N-max/step". - if singleDigit { - end = r.max - } - default: - return 0, fmt.Errorf("Too many slashes: %s", expr) - } - - if start < r.min { - return 0, fmt.Errorf("Beginning of range (%d) below minimum (%d): %s", start, r.min, expr) - } - if end > r.max { - return 0, fmt.Errorf("End of range (%d) above maximum (%d): %s", end, r.max, expr) - } - if start > end { - return 0, fmt.Errorf("Beginning of range (%d) beyond end of range (%d): %s", start, end, expr) - } - if step == 0 { - return 0, fmt.Errorf("Step of range should be a positive number: %s", expr) - } - - return getBits(start, end, step) | extra, nil -} - -// parseIntOrName returns the (possibly-named) integer contained in expr. -func parseIntOrName(expr string, names map[string]uint) (uint, error) { - if names != nil { - if namedInt, ok := names[strings.ToLower(expr)]; ok { - return namedInt, nil - } - } - return mustParseInt(expr) -} - -// mustParseInt parses the given expression as an int or returns an error. -func mustParseInt(expr string) (uint, error) { - num, err := strconv.Atoi(expr) - if err != nil { - return 0, fmt.Errorf("Failed to parse int from %s: %s", expr, err) - } - if num < 0 { - return 0, fmt.Errorf("Negative number (%d) not allowed: %s", num, expr) - } - - return uint(num), nil -} - -// getBits sets all bits in the range [min, max], modulo the given step size. -func getBits(min, max, step uint) uint64 { - var bits uint64 - - // If step is 1, use shifts. - if step == 1 { - return ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min) - } - - // Else, use a simple loop. - for i := min; i <= max; i += step { - bits |= 1 << i - } - return bits -} - -// all returns all bits within the given bounds. (plus the star bit) -func all(r bounds) uint64 { - return getBits(r.min, r.max, 1) | starBit -} - -// parseDescriptor returns a predefined schedule for the expression, or error if none matches. -func parseDescriptor(descriptor string) (Schedule, error) { - switch descriptor { - case "@yearly", "@annually": - return &SpecSchedule{ - Second: 1 << seconds.min, - Minute: 1 << minutes.min, - Hour: 1 << hours.min, - Dom: 1 << dom.min, - Month: 1 << months.min, - Dow: all(dow), - }, nil - - case "@monthly": - return &SpecSchedule{ - Second: 1 << seconds.min, - Minute: 1 << minutes.min, - Hour: 1 << hours.min, - Dom: 1 << dom.min, - Month: all(months), - Dow: all(dow), - }, nil - - case "@weekly": - return &SpecSchedule{ - Second: 1 << seconds.min, - Minute: 1 << minutes.min, - Hour: 1 << hours.min, - Dom: all(dom), - Month: all(months), - Dow: 1 << dow.min, - }, nil - - case "@daily", "@midnight": - return &SpecSchedule{ - Second: 1 << seconds.min, - Minute: 1 << minutes.min, - Hour: 1 << hours.min, - Dom: all(dom), - Month: all(months), - Dow: all(dow), - }, nil - - case "@hourly": - return &SpecSchedule{ - Second: 1 << seconds.min, - Minute: 1 << minutes.min, - Hour: all(hours), - Dom: all(dom), - Month: all(months), - Dow: all(dow), - }, nil - } - - const every = "@every " - if strings.HasPrefix(descriptor, every) { - duration, err := time.ParseDuration(descriptor[len(every):]) - if err != nil { - return nil, fmt.Errorf("Failed to parse duration %s: %s", descriptor, err) - } - return Every(duration), nil - } - - return nil, fmt.Errorf("Unrecognized descriptor: %s", descriptor) -} diff --git a/vendor/github.com/robfig/cron/spec.go b/vendor/github.com/robfig/cron/spec.go deleted file mode 100644 index aac9a60b954..00000000000 --- a/vendor/github.com/robfig/cron/spec.go +++ /dev/null @@ -1,158 +0,0 @@ -package cron - -import "time" - -// SpecSchedule specifies a duty cycle (to the second granularity), based on a -// traditional crontab specification. It is computed initially and stored as bit sets. -type SpecSchedule struct { - Second, Minute, Hour, Dom, Month, Dow uint64 -} - -// bounds provides a range of acceptable values (plus a map of name to value). -type bounds struct { - min, max uint - names map[string]uint -} - -// The bounds for each field. -var ( - seconds = bounds{0, 59, nil} - minutes = bounds{0, 59, nil} - hours = bounds{0, 23, nil} - dom = bounds{1, 31, nil} - months = bounds{1, 12, map[string]uint{ - "jan": 1, - "feb": 2, - "mar": 3, - "apr": 4, - "may": 5, - "jun": 6, - "jul": 7, - "aug": 8, - "sep": 9, - "oct": 10, - "nov": 11, - "dec": 12, - }} - dow = bounds{0, 6, map[string]uint{ - "sun": 0, - "mon": 1, - "tue": 2, - "wed": 3, - "thu": 4, - "fri": 5, - "sat": 6, - }} -) - -const ( - // Set the top bit if a star was included in the expression. - starBit = 1 << 63 -) - -// Next returns the next time this schedule is activated, greater than the given -// time. If no time can be found to satisfy the schedule, return the zero time. -func (s *SpecSchedule) Next(t time.Time) time.Time { - // General approach: - // For Month, Day, Hour, Minute, Second: - // Check if the time value matches. If yes, continue to the next field. - // If the field doesn't match the schedule, then increment the field until it matches. - // While incrementing the field, a wrap-around brings it back to the beginning - // of the field list (since it is necessary to re-verify previous field - // values) - - // Start at the earliest possible time (the upcoming second). - t = t.Add(1*time.Second - time.Duration(t.Nanosecond())*time.Nanosecond) - - // This flag indicates whether a field has been incremented. - added := false - - // If no time is found within five years, return zero. - yearLimit := t.Year() + 5 - -WRAP: - if t.Year() > yearLimit { - return time.Time{} - } - - // Find the first applicable month. - // If it's this month, then do nothing. - for 1< 0 - dowMatch bool = 1< 0 - ) - if s.Dom&starBit > 0 || s.Dow&starBit > 0 { - return domMatch && dowMatch - } - return domMatch || dowMatch -} diff --git a/vendor/github.com/russross/blackfriday/.gitignore b/vendor/github.com/russross/blackfriday/.gitignore deleted file mode 100644 index 75623dcccbb..00000000000 --- a/vendor/github.com/russross/blackfriday/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -*.out -*.swp -*.8 -*.6 -_obj -_test* -markdown -tags diff --git a/vendor/github.com/russross/blackfriday/.travis.yml b/vendor/github.com/russross/blackfriday/.travis.yml deleted file mode 100644 index 2f3351d7ae5..00000000000 --- a/vendor/github.com/russross/blackfriday/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -sudo: false -language: go -go: - - "1.9.x" - - "1.10.x" - - tip -matrix: - fast_finish: true - allow_failures: - - go: tip -install: - - # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step). -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d -s .) - - go tool vet . - - go test -v -race ./... diff --git a/vendor/github.com/russross/blackfriday/LICENSE.txt b/vendor/github.com/russross/blackfriday/LICENSE.txt deleted file mode 100644 index 2885af3602d..00000000000 --- a/vendor/github.com/russross/blackfriday/LICENSE.txt +++ /dev/null @@ -1,29 +0,0 @@ -Blackfriday is distributed under the Simplified BSD License: - -> Copyright © 2011 Russ Ross -> All rights reserved. -> -> Redistribution and use in source and binary forms, with or without -> modification, are permitted provided that the following conditions -> are met: -> -> 1. Redistributions of source code must retain the above copyright -> notice, this list of conditions and the following disclaimer. -> -> 2. Redistributions in binary form must reproduce the above -> copyright notice, this list of conditions and the following -> disclaimer in the documentation and/or other materials provided with -> the distribution. -> -> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -> "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -> LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -> FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -> COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -> INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -> BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -> LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -> LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -> ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -> POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/russross/blackfriday/README.md b/vendor/github.com/russross/blackfriday/README.md deleted file mode 100644 index 3c62e137533..00000000000 --- a/vendor/github.com/russross/blackfriday/README.md +++ /dev/null @@ -1,369 +0,0 @@ -Blackfriday -[![Build Status][BuildSVG]][BuildURL] -[![Godoc][GodocV2SVG]][GodocV2URL] -=========== - -Blackfriday is a [Markdown][1] processor implemented in [Go][2]. It -is paranoid about its input (so you can safely feed it user-supplied -data), it is fast, it supports common extensions (tables, smart -punctuation substitutions, etc.), and it is safe for all utf-8 -(unicode) input. - -HTML output is currently supported, along with Smartypants -extensions. - -It started as a translation from C of [Sundown][3]. - - -Installation ------------- - -Blackfriday is compatible with any modern Go release. With Go and git installed: - - go get -u gopkg.in/russross/blackfriday.v2 - -will download, compile, and install the package into your `$GOPATH` directory -hierarchy. - - -Versions --------- - -Currently maintained and recommended version of Blackfriday is `v2`. It's being -developed on its own branch: https://github.com/russross/blackfriday/tree/v2 and the -documentation is available at -https://godoc.org/gopkg.in/russross/blackfriday.v2. - -It is `go get`-able via [gopkg.in][6] at `gopkg.in/russross/blackfriday.v2`, -but we highly recommend using package management tool like [dep][7] or -[Glide][8] and make use of semantic versioning. With package management you -should import `github.com/russross/blackfriday` and specify that you're using -version 2.0.0. - -Version 2 offers a number of improvements over v1: - -* Cleaned up API -* A separate call to [`Parse`][4], which produces an abstract syntax tree for - the document -* Latest bug fixes -* Flexibility to easily add your own rendering extensions - -Potential drawbacks: - -* Our benchmarks show v2 to be slightly slower than v1. Currently in the - ballpark of around 15%. -* API breakage. If you can't afford modifying your code to adhere to the new API - and don't care too much about the new features, v2 is probably not for you. -* Several bug fixes are trailing behind and still need to be forward-ported to - v2. See issue [#348](https://github.com/russross/blackfriday/issues/348) for - tracking. - -If you are still interested in the legacy `v1`, you can import it from -`github.com/russross/blackfriday`. Documentation for the legacy v1 can be found -here: https://godoc.org/github.com/russross/blackfriday - -### Known issue with `dep` - -There is a known problem with using Blackfriday v1 _transitively_ and `dep`. -Currently `dep` prioritizes semver versions over anything else, and picks the -latest one, plus it does not apply a `[[constraint]]` specifier to transitively -pulled in packages. So if you're using something that uses Blackfriday v1, but -that something does not use `dep` yet, you will get Blackfriday v2 pulled in and -your first dependency will fail to build. - -There are couple of fixes for it, documented here: -https://github.com/golang/dep/blob/master/docs/FAQ.md#how-do-i-constrain-a-transitive-dependencys-version - -Meanwhile, `dep` team is working on a more general solution to the constraints -on transitive dependencies problem: https://github.com/golang/dep/issues/1124. - - -Usage ------ - -### v1 - -For basic usage, it is as simple as getting your input into a byte -slice and calling: - - output := blackfriday.MarkdownBasic(input) - -This renders it with no extensions enabled. To get a more useful -feature set, use this instead: - - output := blackfriday.MarkdownCommon(input) - -### v2 - -For the most sensible markdown processing, it is as simple as getting your input -into a byte slice and calling: - -```go -output := blackfriday.Run(input) -``` - -Your input will be parsed and the output rendered with a set of most popular -extensions enabled. If you want the most basic feature set, corresponding with -the bare Markdown specification, use: - -```go -output := blackfriday.Run(input, blackfriday.WithNoExtensions()) -``` - -### Sanitize untrusted content - -Blackfriday itself does nothing to protect against malicious content. If you are -dealing with user-supplied markdown, we recommend running Blackfriday's output -through HTML sanitizer such as [Bluemonday][5]. - -Here's an example of simple usage of Blackfriday together with Bluemonday: - -```go -import ( - "github.com/microcosm-cc/bluemonday" - "gopkg.in/russross/blackfriday.v2" -) - -// ... -unsafe := blackfriday.Run(input) -html := bluemonday.UGCPolicy().SanitizeBytes(unsafe) -``` - -### Custom options, v1 - -If you want to customize the set of options, first get a renderer -(currently only the HTML output engine), then use it to -call the more general `Markdown` function. For examples, see the -implementations of `MarkdownBasic` and `MarkdownCommon` in -`markdown.go`. - -### Custom options, v2 - -If you want to customize the set of options, use `blackfriday.WithExtensions`, -`blackfriday.WithRenderer` and `blackfriday.WithRefOverride`. - -### `blackfriday-tool` - -You can also check out `blackfriday-tool` for a more complete example -of how to use it. Download and install it using: - - go get github.com/russross/blackfriday-tool - -This is a simple command-line tool that allows you to process a -markdown file using a standalone program. You can also browse the -source directly on github if you are just looking for some example -code: - -* - -Note that if you have not already done so, installing -`blackfriday-tool` will be sufficient to download and install -blackfriday in addition to the tool itself. The tool binary will be -installed in `$GOPATH/bin`. This is a statically-linked binary that -can be copied to wherever you need it without worrying about -dependencies and library versions. - -### Sanitized anchor names - -Blackfriday includes an algorithm for creating sanitized anchor names -corresponding to a given input text. This algorithm is used to create -anchors for headings when `EXTENSION_AUTO_HEADER_IDS` is enabled. The -algorithm has a specification, so that other packages can create -compatible anchor names and links to those anchors. - -The specification is located at https://godoc.org/github.com/russross/blackfriday#hdr-Sanitized_Anchor_Names. - -[`SanitizedAnchorName`](https://godoc.org/github.com/russross/blackfriday#SanitizedAnchorName) exposes this functionality, and can be used to -create compatible links to the anchor names generated by blackfriday. -This algorithm is also implemented in a small standalone package at -[`github.com/shurcooL/sanitized_anchor_name`](https://godoc.org/github.com/shurcooL/sanitized_anchor_name). It can be useful for clients -that want a small package and don't need full functionality of blackfriday. - - -Features --------- - -All features of Sundown are supported, including: - -* **Compatibility**. The Markdown v1.0.3 test suite passes with - the `--tidy` option. Without `--tidy`, the differences are - mostly in whitespace and entity escaping, where blackfriday is - more consistent and cleaner. - -* **Common extensions**, including table support, fenced code - blocks, autolinks, strikethroughs, non-strict emphasis, etc. - -* **Safety**. Blackfriday is paranoid when parsing, making it safe - to feed untrusted user input without fear of bad things - happening. The test suite stress tests this and there are no - known inputs that make it crash. If you find one, please let me - know and send me the input that does it. - - NOTE: "safety" in this context means *runtime safety only*. In order to - protect yourself against JavaScript injection in untrusted content, see - [this example](https://github.com/russross/blackfriday#sanitize-untrusted-content). - -* **Fast processing**. It is fast enough to render on-demand in - most web applications without having to cache the output. - -* **Thread safety**. You can run multiple parsers in different - goroutines without ill effect. There is no dependence on global - shared state. - -* **Minimal dependencies**. Blackfriday only depends on standard - library packages in Go. The source code is pretty - self-contained, so it is easy to add to any project, including - Google App Engine projects. - -* **Standards compliant**. Output successfully validates using the - W3C validation tool for HTML 4.01 and XHTML 1.0 Transitional. - - -Extensions ----------- - -In addition to the standard markdown syntax, this package -implements the following extensions: - -* **Intra-word emphasis supression**. The `_` character is - commonly used inside words when discussing code, so having - markdown interpret it as an emphasis command is usually the - wrong thing. Blackfriday lets you treat all emphasis markers as - normal characters when they occur inside a word. - -* **Tables**. Tables can be created by drawing them in the input - using a simple syntax: - - ``` - Name | Age - --------|------ - Bob | 27 - Alice | 23 - ``` - -* **Fenced code blocks**. In addition to the normal 4-space - indentation to mark code blocks, you can explicitly mark them - and supply a language (to make syntax highlighting simple). Just - mark it like this: - - ``` go - func getTrue() bool { - return true - } - ``` - - You can use 3 or more backticks to mark the beginning of the - block, and the same number to mark the end of the block. - - To preserve classes of fenced code blocks while using the bluemonday - HTML sanitizer, use the following policy: - - ``` go - p := bluemonday.UGCPolicy() - p.AllowAttrs("class").Matching(regexp.MustCompile("^language-[a-zA-Z0-9]+$")).OnElements("code") - html := p.SanitizeBytes(unsafe) - ``` - -* **Definition lists**. A simple definition list is made of a single-line - term followed by a colon and the definition for that term. - - Cat - : Fluffy animal everyone likes - - Internet - : Vector of transmission for pictures of cats - - Terms must be separated from the previous definition by a blank line. - -* **Footnotes**. A marker in the text that will become a superscript number; - a footnote definition that will be placed in a list of footnotes at the - end of the document. A footnote looks like this: - - This is a footnote.[^1] - - [^1]: the footnote text. - -* **Autolinking**. Blackfriday can find URLs that have not been - explicitly marked as links and turn them into links. - -* **Strikethrough**. Use two tildes (`~~`) to mark text that - should be crossed out. - -* **Hard line breaks**. With this extension enabled (it is off by - default in the `MarkdownBasic` and `MarkdownCommon` convenience - functions), newlines in the input translate into line breaks in - the output. - -* **Smart quotes**. Smartypants-style punctuation substitution is - supported, turning normal double- and single-quote marks into - curly quotes, etc. - -* **LaTeX-style dash parsing** is an additional option, where `--` - is translated into `–`, and `---` is translated into - `—`. This differs from most smartypants processors, which - turn a single hyphen into an ndash and a double hyphen into an - mdash. - -* **Smart fractions**, where anything that looks like a fraction - is translated into suitable HTML (instead of just a few special - cases like most smartypant processors). For example, `4/5` - becomes `45`, which renders as - 45. - - -Other renderers ---------------- - -Blackfriday is structured to allow alternative rendering engines. Here -are a few of note: - -* [github_flavored_markdown](https://godoc.org/github.com/shurcooL/github_flavored_markdown): - provides a GitHub Flavored Markdown renderer with fenced code block - highlighting, clickable heading anchor links. - - It's not customizable, and its goal is to produce HTML output - equivalent to the [GitHub Markdown API endpoint](https://developer.github.com/v3/markdown/#render-a-markdown-document-in-raw-mode), - except the rendering is performed locally. - -* [markdownfmt](https://github.com/shurcooL/markdownfmt): like gofmt, - but for markdown. - -* [LaTeX output](https://bitbucket.org/ambrevar/blackfriday-latex): - renders output as LaTeX. - -* [bfchroma](https://github.com/Depado/bfchroma/): provides convenience - integration with the [Chroma](https://github.com/alecthomas/chroma) code - highlighting library. bfchroma is only compatible with v2 of Blackfriday and - provides a drop-in renderer ready to use with Blackfriday, as well as - options and means for further customization. - - -TODO ----- - -* More unit testing -* Improve Unicode support. It does not understand all Unicode - rules (about what constitutes a letter, a punctuation symbol, - etc.), so it may fail to detect word boundaries correctly in - some instances. It is safe on all UTF-8 input. - - -License -------- - -[Blackfriday is distributed under the Simplified BSD License](LICENSE.txt) - - - [1]: https://daringfireball.net/projects/markdown/ "Markdown" - [2]: https://golang.org/ "Go Language" - [3]: https://github.com/vmg/sundown "Sundown" - [4]: https://godoc.org/gopkg.in/russross/blackfriday.v2#Parse "Parse func" - [5]: https://github.com/microcosm-cc/bluemonday "Bluemonday" - [6]: https://labix.org/gopkg.in "gopkg.in" - [7]: https://github.com/golang/dep/ "dep" - [8]: https://github.com/Masterminds/glide "Glide" - - [BuildSVG]: https://travis-ci.org/russross/blackfriday.svg?branch=master - [BuildURL]: https://travis-ci.org/russross/blackfriday - [GodocV2SVG]: https://godoc.org/gopkg.in/russross/blackfriday.v2?status.svg - [GodocV2URL]: https://godoc.org/gopkg.in/russross/blackfriday.v2 diff --git a/vendor/github.com/russross/blackfriday/block.go b/vendor/github.com/russross/blackfriday/block.go deleted file mode 100644 index 45c21a6c267..00000000000 --- a/vendor/github.com/russross/blackfriday/block.go +++ /dev/null @@ -1,1474 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// Functions to parse block-level elements. -// - -package blackfriday - -import ( - "bytes" - "strings" - "unicode" -) - -// Parse block-level data. -// Note: this function and many that it calls assume that -// the input buffer ends with a newline. -func (p *parser) block(out *bytes.Buffer, data []byte) { - if len(data) == 0 || data[len(data)-1] != '\n' { - panic("block input is missing terminating newline") - } - - // this is called recursively: enforce a maximum depth - if p.nesting >= p.maxNesting { - return - } - p.nesting++ - - // parse out one block-level construct at a time - for len(data) > 0 { - // prefixed header: - // - // # Header 1 - // ## Header 2 - // ... - // ###### Header 6 - if p.isPrefixHeader(data) { - data = data[p.prefixHeader(out, data):] - continue - } - - // block of preformatted HTML: - // - //
- // ... - //
- if data[0] == '<' { - if i := p.html(out, data, true); i > 0 { - data = data[i:] - continue - } - } - - // title block - // - // % stuff - // % more stuff - // % even more stuff - if p.flags&EXTENSION_TITLEBLOCK != 0 { - if data[0] == '%' { - if i := p.titleBlock(out, data, true); i > 0 { - data = data[i:] - continue - } - } - } - - // blank lines. note: returns the # of bytes to skip - if i := p.isEmpty(data); i > 0 { - data = data[i:] - continue - } - - // indented code block: - // - // func max(a, b int) int { - // if a > b { - // return a - // } - // return b - // } - if p.codePrefix(data) > 0 { - data = data[p.code(out, data):] - continue - } - - // fenced code block: - // - // ``` go info string here - // func fact(n int) int { - // if n <= 1 { - // return n - // } - // return n * fact(n-1) - // } - // ``` - if p.flags&EXTENSION_FENCED_CODE != 0 { - if i := p.fencedCodeBlock(out, data, true); i > 0 { - data = data[i:] - continue - } - } - - // horizontal rule: - // - // ------ - // or - // ****** - // or - // ______ - if p.isHRule(data) { - p.r.HRule(out) - var i int - for i = 0; data[i] != '\n'; i++ { - } - data = data[i:] - continue - } - - // block quote: - // - // > A big quote I found somewhere - // > on the web - if p.quotePrefix(data) > 0 { - data = data[p.quote(out, data):] - continue - } - - // table: - // - // Name | Age | Phone - // ------|-----|--------- - // Bob | 31 | 555-1234 - // Alice | 27 | 555-4321 - if p.flags&EXTENSION_TABLES != 0 { - if i := p.table(out, data); i > 0 { - data = data[i:] - continue - } - } - - // an itemized/unordered list: - // - // * Item 1 - // * Item 2 - // - // also works with + or - - if p.uliPrefix(data) > 0 { - data = data[p.list(out, data, 0):] - continue - } - - // a numbered/ordered list: - // - // 1. Item 1 - // 2. Item 2 - if p.oliPrefix(data) > 0 { - data = data[p.list(out, data, LIST_TYPE_ORDERED):] - continue - } - - // definition lists: - // - // Term 1 - // : Definition a - // : Definition b - // - // Term 2 - // : Definition c - if p.flags&EXTENSION_DEFINITION_LISTS != 0 { - if p.dliPrefix(data) > 0 { - data = data[p.list(out, data, LIST_TYPE_DEFINITION):] - continue - } - } - - // anything else must look like a normal paragraph - // note: this finds underlined headers, too - data = data[p.paragraph(out, data):] - } - - p.nesting-- -} - -func (p *parser) isPrefixHeader(data []byte) bool { - if data[0] != '#' { - return false - } - - if p.flags&EXTENSION_SPACE_HEADERS != 0 { - level := 0 - for level < 6 && data[level] == '#' { - level++ - } - if data[level] != ' ' { - return false - } - } - return true -} - -func (p *parser) prefixHeader(out *bytes.Buffer, data []byte) int { - level := 0 - for level < 6 && data[level] == '#' { - level++ - } - i := skipChar(data, level, ' ') - end := skipUntilChar(data, i, '\n') - skip := end - id := "" - if p.flags&EXTENSION_HEADER_IDS != 0 { - j, k := 0, 0 - // find start/end of header id - for j = i; j < end-1 && (data[j] != '{' || data[j+1] != '#'); j++ { - } - for k = j + 1; k < end && data[k] != '}'; k++ { - } - // extract header id iff found - if j < end && k < end { - id = string(data[j+2 : k]) - end = j - skip = k + 1 - for end > 0 && data[end-1] == ' ' { - end-- - } - } - } - for end > 0 && data[end-1] == '#' { - if isBackslashEscaped(data, end-1) { - break - } - end-- - } - for end > 0 && data[end-1] == ' ' { - end-- - } - if end > i { - if id == "" && p.flags&EXTENSION_AUTO_HEADER_IDS != 0 { - id = SanitizedAnchorName(string(data[i:end])) - } - work := func() bool { - p.inline(out, data[i:end]) - return true - } - p.r.Header(out, work, level, id) - } - return skip -} - -func (p *parser) isUnderlinedHeader(data []byte) int { - // test of level 1 header - if data[0] == '=' { - i := skipChar(data, 1, '=') - i = skipChar(data, i, ' ') - if data[i] == '\n' { - return 1 - } else { - return 0 - } - } - - // test of level 2 header - if data[0] == '-' { - i := skipChar(data, 1, '-') - i = skipChar(data, i, ' ') - if data[i] == '\n' { - return 2 - } else { - return 0 - } - } - - return 0 -} - -func (p *parser) titleBlock(out *bytes.Buffer, data []byte, doRender bool) int { - if data[0] != '%' { - return 0 - } - splitData := bytes.Split(data, []byte("\n")) - var i int - for idx, b := range splitData { - if !bytes.HasPrefix(b, []byte("%")) { - i = idx // - 1 - break - } - } - - data = bytes.Join(splitData[0:i], []byte("\n")) - p.r.TitleBlock(out, data) - - return len(data) -} - -func (p *parser) html(out *bytes.Buffer, data []byte, doRender bool) int { - var i, j int - - // identify the opening tag - if data[0] != '<' { - return 0 - } - curtag, tagfound := p.htmlFindTag(data[1:]) - - // handle special cases - if !tagfound { - // check for an HTML comment - if size := p.htmlComment(out, data, doRender); size > 0 { - return size - } - - // check for an
tag - if size := p.htmlHr(out, data, doRender); size > 0 { - return size - } - - // check for HTML CDATA - if size := p.htmlCDATA(out, data, doRender); size > 0 { - return size - } - - // no special case recognized - return 0 - } - - // look for an unindented matching closing tag - // followed by a blank line - found := false - /* - closetag := []byte("\n") - j = len(curtag) + 1 - for !found { - // scan for a closing tag at the beginning of a line - if skip := bytes.Index(data[j:], closetag); skip >= 0 { - j += skip + len(closetag) - } else { - break - } - - // see if it is the only thing on the line - if skip := p.isEmpty(data[j:]); skip > 0 { - // see if it is followed by a blank line/eof - j += skip - if j >= len(data) { - found = true - i = j - } else { - if skip := p.isEmpty(data[j:]); skip > 0 { - j += skip - found = true - i = j - } - } - } - } - */ - - // if not found, try a second pass looking for indented match - // but not if tag is "ins" or "del" (following original Markdown.pl) - if !found && curtag != "ins" && curtag != "del" { - i = 1 - for i < len(data) { - i++ - for i < len(data) && !(data[i-1] == '<' && data[i] == '/') { - i++ - } - - if i+2+len(curtag) >= len(data) { - break - } - - j = p.htmlFindEnd(curtag, data[i-1:]) - - if j > 0 { - i += j - 1 - found = true - break - } - } - } - - if !found { - return 0 - } - - // the end of the block has been found - if doRender { - // trim newlines - end := i - for end > 0 && data[end-1] == '\n' { - end-- - } - p.r.BlockHtml(out, data[:end]) - } - - return i -} - -func (p *parser) renderHTMLBlock(out *bytes.Buffer, data []byte, start int, doRender bool) int { - // html block needs to end with a blank line - if i := p.isEmpty(data[start:]); i > 0 { - size := start + i - if doRender { - // trim trailing newlines - end := size - for end > 0 && data[end-1] == '\n' { - end-- - } - p.r.BlockHtml(out, data[:end]) - } - return size - } - return 0 -} - -// HTML comment, lax form -func (p *parser) htmlComment(out *bytes.Buffer, data []byte, doRender bool) int { - i := p.inlineHTMLComment(out, data) - return p.renderHTMLBlock(out, data, i, doRender) -} - -// HTML CDATA section -func (p *parser) htmlCDATA(out *bytes.Buffer, data []byte, doRender bool) int { - const cdataTag = "') { - i++ - } - i++ - // no end-of-comment marker - if i >= len(data) { - return 0 - } - return p.renderHTMLBlock(out, data, i, doRender) -} - -// HR, which is the only self-closing block tag considered -func (p *parser) htmlHr(out *bytes.Buffer, data []byte, doRender bool) int { - if data[0] != '<' || (data[1] != 'h' && data[1] != 'H') || (data[2] != 'r' && data[2] != 'R') { - return 0 - } - if data[3] != ' ' && data[3] != '/' && data[3] != '>' { - // not an
tag after all; at least not a valid one - return 0 - } - - i := 3 - for data[i] != '>' && data[i] != '\n' { - i++ - } - - if data[i] == '>' { - return p.renderHTMLBlock(out, data, i+1, doRender) - } - - return 0 -} - -func (p *parser) htmlFindTag(data []byte) (string, bool) { - i := 0 - for isalnum(data[i]) { - i++ - } - key := string(data[:i]) - if _, ok := blockTags[key]; ok { - return key, true - } - return "", false -} - -func (p *parser) htmlFindEnd(tag string, data []byte) int { - // assume data[0] == '<' && data[1] == '/' already tested - - // check if tag is a match - closetag := []byte("") - if !bytes.HasPrefix(data, closetag) { - return 0 - } - i := len(closetag) - - // check that the rest of the line is blank - skip := 0 - if skip = p.isEmpty(data[i:]); skip == 0 { - return 0 - } - i += skip - skip = 0 - - if i >= len(data) { - return i - } - - if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 { - return i - } - if skip = p.isEmpty(data[i:]); skip == 0 { - // following line must be blank - return 0 - } - - return i + skip -} - -func (*parser) isEmpty(data []byte) int { - // it is okay to call isEmpty on an empty buffer - if len(data) == 0 { - return 0 - } - - var i int - for i = 0; i < len(data) && data[i] != '\n'; i++ { - if data[i] != ' ' && data[i] != '\t' { - return 0 - } - } - return i + 1 -} - -func (*parser) isHRule(data []byte) bool { - i := 0 - - // skip up to three spaces - for i < 3 && data[i] == ' ' { - i++ - } - - // look at the hrule char - if data[i] != '*' && data[i] != '-' && data[i] != '_' { - return false - } - c := data[i] - - // the whole line must be the char or whitespace - n := 0 - for data[i] != '\n' { - switch { - case data[i] == c: - n++ - case data[i] != ' ': - return false - } - i++ - } - - return n >= 3 -} - -// isFenceLine checks if there's a fence line (e.g., ``` or ``` go) at the beginning of data, -// and returns the end index if so, or 0 otherwise. It also returns the marker found. -// If syntax is not nil, it gets set to the syntax specified in the fence line. -// A final newline is mandatory to recognize the fence line, unless newlineOptional is true. -func isFenceLine(data []byte, info *string, oldmarker string, newlineOptional bool) (end int, marker string) { - i, size := 0, 0 - - // skip up to three spaces - for i < len(data) && i < 3 && data[i] == ' ' { - i++ - } - - // check for the marker characters: ~ or ` - if i >= len(data) { - return 0, "" - } - if data[i] != '~' && data[i] != '`' { - return 0, "" - } - - c := data[i] - - // the whole line must be the same char or whitespace - for i < len(data) && data[i] == c { - size++ - i++ - } - - // the marker char must occur at least 3 times - if size < 3 { - return 0, "" - } - marker = string(data[i-size : i]) - - // if this is the end marker, it must match the beginning marker - if oldmarker != "" && marker != oldmarker { - return 0, "" - } - - // TODO(shurcooL): It's probably a good idea to simplify the 2 code paths here - // into one, always get the info string, and discard it if the caller doesn't care. - if info != nil { - infoLength := 0 - i = skipChar(data, i, ' ') - - if i >= len(data) { - if newlineOptional && i == len(data) { - return i, marker - } - return 0, "" - } - - infoStart := i - - if data[i] == '{' { - i++ - infoStart++ - - for i < len(data) && data[i] != '}' && data[i] != '\n' { - infoLength++ - i++ - } - - if i >= len(data) || data[i] != '}' { - return 0, "" - } - - // strip all whitespace at the beginning and the end - // of the {} block - for infoLength > 0 && isspace(data[infoStart]) { - infoStart++ - infoLength-- - } - - for infoLength > 0 && isspace(data[infoStart+infoLength-1]) { - infoLength-- - } - - i++ - } else { - for i < len(data) && !isverticalspace(data[i]) { - infoLength++ - i++ - } - } - - *info = strings.TrimSpace(string(data[infoStart : infoStart+infoLength])) - } - - i = skipChar(data, i, ' ') - if i >= len(data) || data[i] != '\n' { - if newlineOptional && i == len(data) { - return i, marker - } - return 0, "" - } - - return i + 1, marker // Take newline into account. -} - -// fencedCodeBlock returns the end index if data contains a fenced code block at the beginning, -// or 0 otherwise. It writes to out if doRender is true, otherwise it has no side effects. -// If doRender is true, a final newline is mandatory to recognize the fenced code block. -func (p *parser) fencedCodeBlock(out *bytes.Buffer, data []byte, doRender bool) int { - var infoString string - beg, marker := isFenceLine(data, &infoString, "", false) - if beg == 0 || beg >= len(data) { - return 0 - } - - var work bytes.Buffer - - for { - // safe to assume beg < len(data) - - // check for the end of the code block - newlineOptional := !doRender - fenceEnd, _ := isFenceLine(data[beg:], nil, marker, newlineOptional) - if fenceEnd != 0 { - beg += fenceEnd - break - } - - // copy the current line - end := skipUntilChar(data, beg, '\n') + 1 - - // did we reach the end of the buffer without a closing marker? - if end >= len(data) { - return 0 - } - - // verbatim copy to the working buffer - if doRender { - work.Write(data[beg:end]) - } - beg = end - } - - if doRender { - p.r.BlockCode(out, work.Bytes(), infoString) - } - - return beg -} - -func (p *parser) table(out *bytes.Buffer, data []byte) int { - var header bytes.Buffer - i, columns := p.tableHeader(&header, data) - if i == 0 { - return 0 - } - - var body bytes.Buffer - - for i < len(data) { - pipes, rowStart := 0, i - for ; data[i] != '\n'; i++ { - if data[i] == '|' { - pipes++ - } - } - - if pipes == 0 { - i = rowStart - break - } - - // include the newline in data sent to tableRow - i++ - p.tableRow(&body, data[rowStart:i], columns, false) - } - - p.r.Table(out, header.Bytes(), body.Bytes(), columns) - - return i -} - -// check if the specified position is preceded by an odd number of backslashes -func isBackslashEscaped(data []byte, i int) bool { - backslashes := 0 - for i-backslashes-1 >= 0 && data[i-backslashes-1] == '\\' { - backslashes++ - } - return backslashes&1 == 1 -} - -func (p *parser) tableHeader(out *bytes.Buffer, data []byte) (size int, columns []int) { - i := 0 - colCount := 1 - for i = 0; data[i] != '\n'; i++ { - if data[i] == '|' && !isBackslashEscaped(data, i) { - colCount++ - } - } - - // doesn't look like a table header - if colCount == 1 { - return - } - - // include the newline in the data sent to tableRow - header := data[:i+1] - - // column count ignores pipes at beginning or end of line - if data[0] == '|' { - colCount-- - } - if i > 2 && data[i-1] == '|' && !isBackslashEscaped(data, i-1) { - colCount-- - } - - columns = make([]int, colCount) - - // move on to the header underline - i++ - if i >= len(data) { - return - } - - if data[i] == '|' && !isBackslashEscaped(data, i) { - i++ - } - i = skipChar(data, i, ' ') - - // each column header is of form: / *:?-+:? *|/ with # dashes + # colons >= 3 - // and trailing | optional on last column - col := 0 - for data[i] != '\n' { - dashes := 0 - - if data[i] == ':' { - i++ - columns[col] |= TABLE_ALIGNMENT_LEFT - dashes++ - } - for data[i] == '-' { - i++ - dashes++ - } - if data[i] == ':' { - i++ - columns[col] |= TABLE_ALIGNMENT_RIGHT - dashes++ - } - for data[i] == ' ' { - i++ - } - - // end of column test is messy - switch { - case dashes < 3: - // not a valid column - return - - case data[i] == '|' && !isBackslashEscaped(data, i): - // marker found, now skip past trailing whitespace - col++ - i++ - for data[i] == ' ' { - i++ - } - - // trailing junk found after last column - if col >= colCount && data[i] != '\n' { - return - } - - case (data[i] != '|' || isBackslashEscaped(data, i)) && col+1 < colCount: - // something else found where marker was required - return - - case data[i] == '\n': - // marker is optional for the last column - col++ - - default: - // trailing junk found after last column - return - } - } - if col != colCount { - return - } - - p.tableRow(out, header, columns, true) - size = i + 1 - return -} - -func (p *parser) tableRow(out *bytes.Buffer, data []byte, columns []int, header bool) { - i, col := 0, 0 - var rowWork bytes.Buffer - - if data[i] == '|' && !isBackslashEscaped(data, i) { - i++ - } - - for col = 0; col < len(columns) && i < len(data); col++ { - for data[i] == ' ' { - i++ - } - - cellStart := i - - for (data[i] != '|' || isBackslashEscaped(data, i)) && data[i] != '\n' { - i++ - } - - cellEnd := i - - // skip the end-of-cell marker, possibly taking us past end of buffer - i++ - - for cellEnd > cellStart && data[cellEnd-1] == ' ' { - cellEnd-- - } - - var cellWork bytes.Buffer - p.inline(&cellWork, data[cellStart:cellEnd]) - - if header { - p.r.TableHeaderCell(&rowWork, cellWork.Bytes(), columns[col]) - } else { - p.r.TableCell(&rowWork, cellWork.Bytes(), columns[col]) - } - } - - // pad it out with empty columns to get the right number - for ; col < len(columns); col++ { - if header { - p.r.TableHeaderCell(&rowWork, nil, columns[col]) - } else { - p.r.TableCell(&rowWork, nil, columns[col]) - } - } - - // silently ignore rows with too many cells - - p.r.TableRow(out, rowWork.Bytes()) -} - -// returns blockquote prefix length -func (p *parser) quotePrefix(data []byte) int { - i := 0 - for i < 3 && data[i] == ' ' { - i++ - } - if data[i] == '>' { - if data[i+1] == ' ' { - return i + 2 - } - return i + 1 - } - return 0 -} - -// blockquote ends with at least one blank line -// followed by something without a blockquote prefix -func (p *parser) terminateBlockquote(data []byte, beg, end int) bool { - if p.isEmpty(data[beg:]) <= 0 { - return false - } - if end >= len(data) { - return true - } - return p.quotePrefix(data[end:]) == 0 && p.isEmpty(data[end:]) == 0 -} - -// parse a blockquote fragment -func (p *parser) quote(out *bytes.Buffer, data []byte) int { - var raw bytes.Buffer - beg, end := 0, 0 - for beg < len(data) { - end = beg - // Step over whole lines, collecting them. While doing that, check for - // fenced code and if one's found, incorporate it altogether, - // irregardless of any contents inside it - for data[end] != '\n' { - if p.flags&EXTENSION_FENCED_CODE != 0 { - if i := p.fencedCodeBlock(out, data[end:], false); i > 0 { - // -1 to compensate for the extra end++ after the loop: - end += i - 1 - break - } - } - end++ - } - end++ - - if pre := p.quotePrefix(data[beg:]); pre > 0 { - // skip the prefix - beg += pre - } else if p.terminateBlockquote(data, beg, end) { - break - } - - // this line is part of the blockquote - raw.Write(data[beg:end]) - beg = end - } - - var cooked bytes.Buffer - p.block(&cooked, raw.Bytes()) - p.r.BlockQuote(out, cooked.Bytes()) - return end -} - -// returns prefix length for block code -func (p *parser) codePrefix(data []byte) int { - if data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ' { - return 4 - } - return 0 -} - -func (p *parser) code(out *bytes.Buffer, data []byte) int { - var work bytes.Buffer - - i := 0 - for i < len(data) { - beg := i - for data[i] != '\n' { - i++ - } - i++ - - blankline := p.isEmpty(data[beg:i]) > 0 - if pre := p.codePrefix(data[beg:i]); pre > 0 { - beg += pre - } else if !blankline { - // non-empty, non-prefixed line breaks the pre - i = beg - break - } - - // verbatim copy to the working buffeu - if blankline { - work.WriteByte('\n') - } else { - work.Write(data[beg:i]) - } - } - - // trim all the \n off the end of work - workbytes := work.Bytes() - eol := len(workbytes) - for eol > 0 && workbytes[eol-1] == '\n' { - eol-- - } - if eol != len(workbytes) { - work.Truncate(eol) - } - - work.WriteByte('\n') - - p.r.BlockCode(out, work.Bytes(), "") - - return i -} - -// returns unordered list item prefix -func (p *parser) uliPrefix(data []byte) int { - i := 0 - - // start with up to 3 spaces - for i < 3 && data[i] == ' ' { - i++ - } - - // need a *, +, or - followed by a space - if (data[i] != '*' && data[i] != '+' && data[i] != '-') || - data[i+1] != ' ' { - return 0 - } - return i + 2 -} - -// returns ordered list item prefix -func (p *parser) oliPrefix(data []byte) int { - i := 0 - - // start with up to 3 spaces - for i < 3 && data[i] == ' ' { - i++ - } - - // count the digits - start := i - for data[i] >= '0' && data[i] <= '9' { - i++ - } - - // we need >= 1 digits followed by a dot and a space - if start == i || data[i] != '.' || data[i+1] != ' ' { - return 0 - } - return i + 2 -} - -// returns definition list item prefix -func (p *parser) dliPrefix(data []byte) int { - i := 0 - - // need a : followed by a spaces - if data[i] != ':' || data[i+1] != ' ' { - return 0 - } - for data[i] == ' ' { - i++ - } - return i + 2 -} - -// parse ordered or unordered list block -func (p *parser) list(out *bytes.Buffer, data []byte, flags int) int { - i := 0 - flags |= LIST_ITEM_BEGINNING_OF_LIST - work := func() bool { - for i < len(data) { - skip := p.listItem(out, data[i:], &flags) - i += skip - - if skip == 0 || flags&LIST_ITEM_END_OF_LIST != 0 { - break - } - flags &= ^LIST_ITEM_BEGINNING_OF_LIST - } - return true - } - - p.r.List(out, work, flags) - return i -} - -// Parse a single list item. -// Assumes initial prefix is already removed if this is a sublist. -func (p *parser) listItem(out *bytes.Buffer, data []byte, flags *int) int { - // keep track of the indentation of the first line - itemIndent := 0 - for itemIndent < 3 && data[itemIndent] == ' ' { - itemIndent++ - } - - i := p.uliPrefix(data) - if i == 0 { - i = p.oliPrefix(data) - } - if i == 0 { - i = p.dliPrefix(data) - // reset definition term flag - if i > 0 { - *flags &= ^LIST_TYPE_TERM - } - } - if i == 0 { - // if in defnition list, set term flag and continue - if *flags&LIST_TYPE_DEFINITION != 0 { - *flags |= LIST_TYPE_TERM - } else { - return 0 - } - } - - // skip leading whitespace on first line - for data[i] == ' ' { - i++ - } - - // find the end of the line - line := i - for i > 0 && data[i-1] != '\n' { - i++ - } - - // get working buffer - var raw bytes.Buffer - - // put the first line into the working buffer - raw.Write(data[line:i]) - line = i - - // process the following lines - containsBlankLine := false - sublist := 0 - codeBlockMarker := "" - -gatherlines: - for line < len(data) { - i++ - - // find the end of this line - for data[i-1] != '\n' { - i++ - } - - // if it is an empty line, guess that it is part of this item - // and move on to the next line - if p.isEmpty(data[line:i]) > 0 { - containsBlankLine = true - raw.Write(data[line:i]) - line = i - continue - } - - // calculate the indentation - indent := 0 - for indent < 4 && line+indent < i && data[line+indent] == ' ' { - indent++ - } - - chunk := data[line+indent : i] - - if p.flags&EXTENSION_FENCED_CODE != 0 { - // determine if in or out of codeblock - // if in codeblock, ignore normal list processing - _, marker := isFenceLine(chunk, nil, codeBlockMarker, false) - if marker != "" { - if codeBlockMarker == "" { - // start of codeblock - codeBlockMarker = marker - } else { - // end of codeblock. - *flags |= LIST_ITEM_CONTAINS_BLOCK - codeBlockMarker = "" - } - } - // we are in a codeblock, write line, and continue - if codeBlockMarker != "" || marker != "" { - raw.Write(data[line+indent : i]) - line = i - continue gatherlines - } - } - - // evaluate how this line fits in - switch { - // is this a nested list item? - case (p.uliPrefix(chunk) > 0 && !p.isHRule(chunk)) || - p.oliPrefix(chunk) > 0 || - p.dliPrefix(chunk) > 0: - - if containsBlankLine { - // end the list if the type changed after a blank line - if indent <= itemIndent && - ((*flags&LIST_TYPE_ORDERED != 0 && p.uliPrefix(chunk) > 0) || - (*flags&LIST_TYPE_ORDERED == 0 && p.oliPrefix(chunk) > 0)) { - - *flags |= LIST_ITEM_END_OF_LIST - break gatherlines - } - *flags |= LIST_ITEM_CONTAINS_BLOCK - } - - // to be a nested list, it must be indented more - // if not, it is the next item in the same list - if indent <= itemIndent { - break gatherlines - } - - // is this the first item in the nested list? - if sublist == 0 { - sublist = raw.Len() - } - - // is this a nested prefix header? - case p.isPrefixHeader(chunk): - // if the header is not indented, it is not nested in the list - // and thus ends the list - if containsBlankLine && indent < 4 { - *flags |= LIST_ITEM_END_OF_LIST - break gatherlines - } - *flags |= LIST_ITEM_CONTAINS_BLOCK - - // anything following an empty line is only part - // of this item if it is indented 4 spaces - // (regardless of the indentation of the beginning of the item) - case containsBlankLine && indent < 4: - if *flags&LIST_TYPE_DEFINITION != 0 && i < len(data)-1 { - // is the next item still a part of this list? - next := i - for data[next] != '\n' { - next++ - } - for next < len(data)-1 && data[next] == '\n' { - next++ - } - if i < len(data)-1 && data[i] != ':' && data[next] != ':' { - *flags |= LIST_ITEM_END_OF_LIST - } - } else { - *flags |= LIST_ITEM_END_OF_LIST - } - break gatherlines - - // a blank line means this should be parsed as a block - case containsBlankLine: - *flags |= LIST_ITEM_CONTAINS_BLOCK - } - - containsBlankLine = false - - // add the line into the working buffer without prefix - raw.Write(data[line+indent : i]) - - line = i - } - - // If reached end of data, the Renderer.ListItem call we're going to make below - // is definitely the last in the list. - if line >= len(data) { - *flags |= LIST_ITEM_END_OF_LIST - } - - rawBytes := raw.Bytes() - - // render the contents of the list item - var cooked bytes.Buffer - if *flags&LIST_ITEM_CONTAINS_BLOCK != 0 && *flags&LIST_TYPE_TERM == 0 { - // intermediate render of block item, except for definition term - if sublist > 0 { - p.block(&cooked, rawBytes[:sublist]) - p.block(&cooked, rawBytes[sublist:]) - } else { - p.block(&cooked, rawBytes) - } - } else { - // intermediate render of inline item - if sublist > 0 { - p.inline(&cooked, rawBytes[:sublist]) - p.block(&cooked, rawBytes[sublist:]) - } else { - p.inline(&cooked, rawBytes) - } - } - - // render the actual list item - cookedBytes := cooked.Bytes() - parsedEnd := len(cookedBytes) - - // strip trailing newlines - for parsedEnd > 0 && cookedBytes[parsedEnd-1] == '\n' { - parsedEnd-- - } - p.r.ListItem(out, cookedBytes[:parsedEnd], *flags) - - return line -} - -// render a single paragraph that has already been parsed out -func (p *parser) renderParagraph(out *bytes.Buffer, data []byte) { - if len(data) == 0 { - return - } - - // trim leading spaces - beg := 0 - for data[beg] == ' ' { - beg++ - } - - // trim trailing newline - end := len(data) - 1 - - // trim trailing spaces - for end > beg && data[end-1] == ' ' { - end-- - } - - work := func() bool { - p.inline(out, data[beg:end]) - return true - } - p.r.Paragraph(out, work) -} - -func (p *parser) paragraph(out *bytes.Buffer, data []byte) int { - // prev: index of 1st char of previous line - // line: index of 1st char of current line - // i: index of cursor/end of current line - var prev, line, i int - - // keep going until we find something to mark the end of the paragraph - for i < len(data) { - // mark the beginning of the current line - prev = line - current := data[i:] - line = i - - // did we find a blank line marking the end of the paragraph? - if n := p.isEmpty(current); n > 0 { - // did this blank line followed by a definition list item? - if p.flags&EXTENSION_DEFINITION_LISTS != 0 { - if i < len(data)-1 && data[i+1] == ':' { - return p.list(out, data[prev:], LIST_TYPE_DEFINITION) - } - } - - p.renderParagraph(out, data[:i]) - return i + n - } - - // an underline under some text marks a header, so our paragraph ended on prev line - if i > 0 { - if level := p.isUnderlinedHeader(current); level > 0 { - // render the paragraph - p.renderParagraph(out, data[:prev]) - - // ignore leading and trailing whitespace - eol := i - 1 - for prev < eol && data[prev] == ' ' { - prev++ - } - for eol > prev && data[eol-1] == ' ' { - eol-- - } - - // render the header - // this ugly double closure avoids forcing variables onto the heap - work := func(o *bytes.Buffer, pp *parser, d []byte) func() bool { - return func() bool { - pp.inline(o, d) - return true - } - }(out, p, data[prev:eol]) - - id := "" - if p.flags&EXTENSION_AUTO_HEADER_IDS != 0 { - id = SanitizedAnchorName(string(data[prev:eol])) - } - - p.r.Header(out, work, level, id) - - // find the end of the underline - for data[i] != '\n' { - i++ - } - return i - } - } - - // if the next line starts a block of HTML, then the paragraph ends here - if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 { - if data[i] == '<' && p.html(out, current, false) > 0 { - // rewind to before the HTML block - p.renderParagraph(out, data[:i]) - return i - } - } - - // if there's a prefixed header or a horizontal rule after this, paragraph is over - if p.isPrefixHeader(current) || p.isHRule(current) { - p.renderParagraph(out, data[:i]) - return i - } - - // if there's a fenced code block, paragraph is over - if p.flags&EXTENSION_FENCED_CODE != 0 { - if p.fencedCodeBlock(out, current, false) > 0 { - p.renderParagraph(out, data[:i]) - return i - } - } - - // if there's a definition list item, prev line is a definition term - if p.flags&EXTENSION_DEFINITION_LISTS != 0 { - if p.dliPrefix(current) != 0 { - return p.list(out, data[prev:], LIST_TYPE_DEFINITION) - } - } - - // if there's a list after this, paragraph is over - if p.flags&EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK != 0 { - if p.uliPrefix(current) != 0 || - p.oliPrefix(current) != 0 || - p.quotePrefix(current) != 0 || - p.codePrefix(current) != 0 { - p.renderParagraph(out, data[:i]) - return i - } - } - - // otherwise, scan to the beginning of the next line - for data[i] != '\n' { - i++ - } - i++ - } - - p.renderParagraph(out, data[:i]) - return i -} - -// SanitizedAnchorName returns a sanitized anchor name for the given text. -// -// It implements the algorithm specified in the package comment. -func SanitizedAnchorName(text string) string { - var anchorName []rune - futureDash := false - for _, r := range text { - switch { - case unicode.IsLetter(r) || unicode.IsNumber(r): - if futureDash && len(anchorName) > 0 { - anchorName = append(anchorName, '-') - } - futureDash = false - anchorName = append(anchorName, unicode.ToLower(r)) - default: - futureDash = true - } - } - return string(anchorName) -} diff --git a/vendor/github.com/russross/blackfriday/doc.go b/vendor/github.com/russross/blackfriday/doc.go deleted file mode 100644 index 9656c42a191..00000000000 --- a/vendor/github.com/russross/blackfriday/doc.go +++ /dev/null @@ -1,32 +0,0 @@ -// Package blackfriday is a Markdown processor. -// -// It translates plain text with simple formatting rules into HTML or LaTeX. -// -// Sanitized Anchor Names -// -// Blackfriday includes an algorithm for creating sanitized anchor names -// corresponding to a given input text. This algorithm is used to create -// anchors for headings when EXTENSION_AUTO_HEADER_IDS is enabled. The -// algorithm is specified below, so that other packages can create -// compatible anchor names and links to those anchors. -// -// The algorithm iterates over the input text, interpreted as UTF-8, -// one Unicode code point (rune) at a time. All runes that are letters (category L) -// or numbers (category N) are considered valid characters. They are mapped to -// lower case, and included in the output. All other runes are considered -// invalid characters. Invalid characters that preceed the first valid character, -// as well as invalid character that follow the last valid character -// are dropped completely. All other sequences of invalid characters -// between two valid characters are replaced with a single dash character '-'. -// -// SanitizedAnchorName exposes this functionality, and can be used to -// create compatible links to the anchor names generated by blackfriday. -// This algorithm is also implemented in a small standalone package at -// github.com/shurcooL/sanitized_anchor_name. It can be useful for clients -// that want a small package and don't need full functionality of blackfriday. -package blackfriday - -// NOTE: Keep Sanitized Anchor Name algorithm in sync with package -// github.com/shurcooL/sanitized_anchor_name. -// Otherwise, users of sanitized_anchor_name will get anchor names -// that are incompatible with those generated by blackfriday. diff --git a/vendor/github.com/russross/blackfriday/html.go b/vendor/github.com/russross/blackfriday/html.go deleted file mode 100644 index e0a6c69c96d..00000000000 --- a/vendor/github.com/russross/blackfriday/html.go +++ /dev/null @@ -1,938 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// -// HTML rendering backend -// -// - -package blackfriday - -import ( - "bytes" - "fmt" - "regexp" - "strconv" - "strings" -) - -// Html renderer configuration options. -const ( - HTML_SKIP_HTML = 1 << iota // skip preformatted HTML blocks - HTML_SKIP_STYLE // skip embedded