summaryrefslogtreecommitdiff
path: root/vendor/k8s.io
diff options
context:
space:
mode:
authorbaude <bbaude@redhat.com>2021-02-25 09:25:28 -0600
committerbaude <bbaude@redhat.com>2021-02-25 10:02:41 -0600
commit24d9bda7ff8a3e6a9f249401e05e35e73284ae61 (patch)
tree6777cc2c23306d1a6b87ef40b9fe4eab2764b7dd /vendor/k8s.io
parent9ec8106841c55bc085012727748e2d73826be97d (diff)
downloadpodman-24d9bda7ff8a3e6a9f249401e05e35e73284ae61.tar.gz
podman-24d9bda7ff8a3e6a9f249401e05e35e73284ae61.tar.bz2
podman-24d9bda7ff8a3e6a9f249401e05e35e73284ae61.zip
prune remotecommand dependency
prune a dependency that was only being used for a simple struct. Should correct checksum issue on tarballs [NO TESTS NEEDED] Fixes: #9355 Signed-off-by: baude <bbaude@redhat.com>
Diffstat (limited to 'vendor/k8s.io')
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS23
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/errors/doc.go18
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/errors/errors.go697
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go500
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go496
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go210
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/zz_generated.deepcopy.go55
-rw-r--r--vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go322
-rw-r--r--vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go389
-rw-r--r--vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/meta.go63
-rw-r--r--vendor/k8s.io/apimachinery/pkg/runtime/serializer/negotiated_codec.go43
-rw-r--r--vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/doc.go18
-rw-r--r--vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go476
-rw-r--r--vendor/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/recognizer.go127
-rw-r--r--vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go137
-rw-r--r--vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go250
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/clock/clock.go407
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/framer/framer.go170
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/httpstream/doc.go19
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/httpstream/httpstream.go157
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go187
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go369
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade.go120
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/remotecommand/constants.go53
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go379
-rw-r--r--vendor/k8s.io/apimachinery/pkg/version/doc.go20
-rw-r--r--vendor/k8s.io/apimachinery/pkg/version/helpers.go88
-rw-r--r--vendor/k8s.io/apimachinery/pkg/version/types.go37
-rw-r--r--vendor/k8s.io/apimachinery/third_party/forked/golang/netutil/addr.go27
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/OWNERS9
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/doc.go20
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/register.go50
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/types.go77
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/doc.go24
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/register.go55
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/types.go78
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.conversion.go176
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.deepcopy.go128
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.defaults.go32
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/conversion.go26
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/doc.go24
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/register.go55
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/types.go59
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.conversion.go142
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.deepcopy.go92
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.defaults.go32
-rw-r--r--vendor/k8s.io/client-go/pkg/apis/clientauthentication/zz_generated.deepcopy.go128
-rw-r--r--vendor/k8s.io/client-go/pkg/version/.gitattributes1
-rw-r--r--vendor/k8s.io/client-go/pkg/version/base.go63
-rw-r--r--vendor/k8s.io/client-go/pkg/version/def.bzl38
-rw-r--r--vendor/k8s.io/client-go/pkg/version/doc.go21
-rw-r--r--vendor/k8s.io/client-go/pkg/version/version.go42
-rw-r--r--vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go360
-rw-r--r--vendor/k8s.io/client-go/rest/OWNERS26
-rw-r--r--vendor/k8s.io/client-go/rest/client.go258
-rw-r--r--vendor/k8s.io/client-go/rest/config.go549
-rw-r--r--vendor/k8s.io/client-go/rest/plugin.go73
-rw-r--r--vendor/k8s.io/client-go/rest/request.go1206
-rw-r--r--vendor/k8s.io/client-go/rest/transport.go118
-rw-r--r--vendor/k8s.io/client-go/rest/url_utils.go97
-rw-r--r--vendor/k8s.io/client-go/rest/urlbackoff.go107
-rw-r--r--vendor/k8s.io/client-go/rest/watch/decoder.go72
-rw-r--r--vendor/k8s.io/client-go/rest/watch/encoder.go56
-rw-r--r--vendor/k8s.io/client-go/rest/zz_generated.deepcopy.go52
-rw-r--r--vendor/k8s.io/client-go/tools/clientcmd/api/doc.go19
-rw-r--r--vendor/k8s.io/client-go/tools/clientcmd/api/helpers.go188
-rw-r--r--vendor/k8s.io/client-go/tools/clientcmd/api/register.go46
-rw-r--r--vendor/k8s.io/client-go/tools/clientcmd/api/types.go262
-rw-r--r--vendor/k8s.io/client-go/tools/clientcmd/api/zz_generated.deepcopy.go324
-rw-r--r--vendor/k8s.io/client-go/tools/metrics/OWNERS9
-rw-r--r--vendor/k8s.io/client-go/tools/metrics/metrics.go61
-rw-r--r--vendor/k8s.io/client-go/tools/remotecommand/doc.go20
-rw-r--r--vendor/k8s.io/client-go/tools/remotecommand/errorstream.go55
-rw-r--r--vendor/k8s.io/client-go/tools/remotecommand/reader.go41
-rw-r--r--vendor/k8s.io/client-go/tools/remotecommand/remotecommand.go142
-rw-r--r--vendor/k8s.io/client-go/tools/remotecommand/resize.go33
-rw-r--r--vendor/k8s.io/client-go/tools/remotecommand/v1.go160
-rw-r--r--vendor/k8s.io/client-go/tools/remotecommand/v2.go195
-rw-r--r--vendor/k8s.io/client-go/tools/remotecommand/v3.go111
-rw-r--r--vendor/k8s.io/client-go/tools/remotecommand/v4.go119
-rw-r--r--vendor/k8s.io/client-go/transport/OWNERS9
-rw-r--r--vendor/k8s.io/client-go/transport/cache.go117
-rw-r--r--vendor/k8s.io/client-go/transport/config.go126
-rw-r--r--vendor/k8s.io/client-go/transport/round_trippers.go564
-rw-r--r--vendor/k8s.io/client-go/transport/spdy/spdy.go94
-rw-r--r--vendor/k8s.io/client-go/transport/token_source.go149
-rw-r--r--vendor/k8s.io/client-go/transport/transport.go227
-rw-r--r--vendor/k8s.io/client-go/util/cert/OWNERS9
-rw-r--r--vendor/k8s.io/client-go/util/cert/cert.go206
-rw-r--r--vendor/k8s.io/client-go/util/cert/csr.go75
-rw-r--r--vendor/k8s.io/client-go/util/cert/io.go98
-rw-r--r--vendor/k8s.io/client-go/util/cert/pem.go61
-rw-r--r--vendor/k8s.io/client-go/util/connrotation/connrotation.go105
-rw-r--r--vendor/k8s.io/client-go/util/exec/exec.go52
-rw-r--r--vendor/k8s.io/client-go/util/flowcontrol/backoff.go149
-rw-r--r--vendor/k8s.io/client-go/util/flowcontrol/throttle.go143
-rw-r--r--vendor/k8s.io/client-go/util/keyutil/OWNERS7
-rw-r--r--vendor/k8s.io/client-go/util/keyutil/key.go323
-rw-r--r--vendor/k8s.io/klog/.travis.yml16
-rw-r--r--vendor/k8s.io/klog/CONTRIBUTING.md22
-rw-r--r--vendor/k8s.io/klog/LICENSE191
-rw-r--r--vendor/k8s.io/klog/OWNERS19
-rw-r--r--vendor/k8s.io/klog/README.md97
-rw-r--r--vendor/k8s.io/klog/RELEASE.md9
-rw-r--r--vendor/k8s.io/klog/SECURITY_CONTACTS20
-rw-r--r--vendor/k8s.io/klog/code-of-conduct.md3
-rw-r--r--vendor/k8s.io/klog/go.mod5
-rw-r--r--vendor/k8s.io/klog/go.sum2
-rw-r--r--vendor/k8s.io/klog/klog.go1308
-rw-r--r--vendor/k8s.io/klog/klog_file.go139
-rw-r--r--vendor/k8s.io/utils/LICENSE202
-rw-r--r--vendor/k8s.io/utils/integer/integer.go73
112 files changed, 0 insertions, 16608 deletions
diff --git a/vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS b/vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS
deleted file mode 100644
index d18a17885..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS
+++ /dev/null
@@ -1,23 +0,0 @@
-# See the OWNERS docs at https://go.k8s.io/owners
-
-reviewers:
-- thockin
-- lavalamp
-- smarterclayton
-- wojtek-t
-- deads2k
-- brendandburns
-- derekwaynecarr
-- caesarxuchao
-- mikedanese
-- liggitt
-- nikhiljindal
-- gmarek
-- erictune
-- saad-ali
-- janetkuo
-- tallclair
-- dims
-- hongchaodeng
-- krousey
-- cjcullen
diff --git a/vendor/k8s.io/apimachinery/pkg/api/errors/doc.go b/vendor/k8s.io/apimachinery/pkg/api/errors/doc.go
deleted file mode 100644
index 167baf680..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/errors/doc.go
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package errors provides detailed error types for api field validation.
-package errors // import "k8s.io/apimachinery/pkg/api/errors"
diff --git a/vendor/k8s.io/apimachinery/pkg/api/errors/errors.go b/vendor/k8s.io/apimachinery/pkg/api/errors/errors.go
deleted file mode 100644
index d3927d817..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/errors/errors.go
+++ /dev/null
@@ -1,697 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package errors
-
-import (
- "encoding/json"
- "errors"
- "fmt"
- "net/http"
- "reflect"
- "strings"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/util/validation/field"
-)
-
-// StatusError is an error intended for consumption by a REST API server; it can also be
-// reconstructed by clients from a REST response. Public to allow easy type switches.
-type StatusError struct {
- ErrStatus metav1.Status
-}
-
-// APIStatus is exposed by errors that can be converted to an api.Status object
-// for finer grained details.
-type APIStatus interface {
- Status() metav1.Status
-}
-
-var _ error = &StatusError{}
-
-// Error implements the Error interface.
-func (e *StatusError) Error() string {
- return e.ErrStatus.Message
-}
-
-// Status allows access to e's status without having to know the detailed workings
-// of StatusError.
-func (e *StatusError) Status() metav1.Status {
- return e.ErrStatus
-}
-
-// DebugError reports extended info about the error to debug output.
-func (e *StatusError) DebugError() (string, []interface{}) {
- if out, err := json.MarshalIndent(e.ErrStatus, "", " "); err == nil {
- return "server response object: %s", []interface{}{string(out)}
- }
- return "server response object: %#v", []interface{}{e.ErrStatus}
-}
-
-// HasStatusCause returns true if the provided error has a details cause
-// with the provided type name.
-func HasStatusCause(err error, name metav1.CauseType) bool {
- _, ok := StatusCause(err, name)
- return ok
-}
-
-// StatusCause returns the named cause from the provided error if it exists and
-// the error is of the type APIStatus. Otherwise it returns false.
-func StatusCause(err error, name metav1.CauseType) (metav1.StatusCause, bool) {
- apierr, ok := err.(APIStatus)
- if !ok || apierr == nil || apierr.Status().Details == nil {
- return metav1.StatusCause{}, false
- }
- for _, cause := range apierr.Status().Details.Causes {
- if cause.Type == name {
- return cause, true
- }
- }
- return metav1.StatusCause{}, false
-}
-
-// UnexpectedObjectError can be returned by FromObject if it's passed a non-status object.
-type UnexpectedObjectError struct {
- Object runtime.Object
-}
-
-// Error returns an error message describing 'u'.
-func (u *UnexpectedObjectError) Error() string {
- return fmt.Sprintf("unexpected object: %v", u.Object)
-}
-
-// FromObject generates an StatusError from an metav1.Status, if that is the type of obj; otherwise,
-// returns an UnexpecteObjectError.
-func FromObject(obj runtime.Object) error {
- switch t := obj.(type) {
- case *metav1.Status:
- return &StatusError{ErrStatus: *t}
- case runtime.Unstructured:
- var status metav1.Status
- obj := t.UnstructuredContent()
- if !reflect.DeepEqual(obj["kind"], "Status") {
- break
- }
- if err := runtime.DefaultUnstructuredConverter.FromUnstructured(t.UnstructuredContent(), &status); err != nil {
- return err
- }
- if status.APIVersion != "v1" && status.APIVersion != "meta.k8s.io/v1" {
- break
- }
- return &StatusError{ErrStatus: status}
- }
- return &UnexpectedObjectError{obj}
-}
-
-// NewNotFound returns a new error which indicates that the resource of the kind and the name was not found.
-func NewNotFound(qualifiedResource schema.GroupResource, name string) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusNotFound,
- Reason: metav1.StatusReasonNotFound,
- Details: &metav1.StatusDetails{
- Group: qualifiedResource.Group,
- Kind: qualifiedResource.Resource,
- Name: name,
- },
- Message: fmt.Sprintf("%s %q not found", qualifiedResource.String(), name),
- }}
-}
-
-// NewAlreadyExists returns an error indicating the item requested exists by that identifier.
-func NewAlreadyExists(qualifiedResource schema.GroupResource, name string) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusConflict,
- Reason: metav1.StatusReasonAlreadyExists,
- Details: &metav1.StatusDetails{
- Group: qualifiedResource.Group,
- Kind: qualifiedResource.Resource,
- Name: name,
- },
- Message: fmt.Sprintf("%s %q already exists", qualifiedResource.String(), name),
- }}
-}
-
-// NewUnauthorized returns an error indicating the client is not authorized to perform the requested
-// action.
-func NewUnauthorized(reason string) *StatusError {
- message := reason
- if len(message) == 0 {
- message = "not authorized"
- }
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusUnauthorized,
- Reason: metav1.StatusReasonUnauthorized,
- Message: message,
- }}
-}
-
-// NewForbidden returns an error indicating the requested action was forbidden
-func NewForbidden(qualifiedResource schema.GroupResource, name string, err error) *StatusError {
- var message string
- if qualifiedResource.Empty() {
- message = fmt.Sprintf("forbidden: %v", err)
- } else if name == "" {
- message = fmt.Sprintf("%s is forbidden: %v", qualifiedResource.String(), err)
- } else {
- message = fmt.Sprintf("%s %q is forbidden: %v", qualifiedResource.String(), name, err)
- }
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusForbidden,
- Reason: metav1.StatusReasonForbidden,
- Details: &metav1.StatusDetails{
- Group: qualifiedResource.Group,
- Kind: qualifiedResource.Resource,
- Name: name,
- },
- Message: message,
- }}
-}
-
-// NewConflict returns an error indicating the item can't be updated as provided.
-func NewConflict(qualifiedResource schema.GroupResource, name string, err error) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusConflict,
- Reason: metav1.StatusReasonConflict,
- Details: &metav1.StatusDetails{
- Group: qualifiedResource.Group,
- Kind: qualifiedResource.Resource,
- Name: name,
- },
- Message: fmt.Sprintf("Operation cannot be fulfilled on %s %q: %v", qualifiedResource.String(), name, err),
- }}
-}
-
-// NewApplyConflict returns an error including details on the requests apply conflicts
-func NewApplyConflict(causes []metav1.StatusCause, message string) *StatusError {
- return &StatusError{ErrStatus: metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusConflict,
- Reason: metav1.StatusReasonConflict,
- Details: &metav1.StatusDetails{
- // TODO: Get obj details here?
- Causes: causes,
- },
- Message: message,
- }}
-}
-
-// NewGone returns an error indicating the item no longer available at the server and no forwarding address is known.
-// DEPRECATED: Please use NewResourceExpired instead.
-func NewGone(message string) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusGone,
- Reason: metav1.StatusReasonGone,
- Message: message,
- }}
-}
-
-// NewResourceExpired creates an error that indicates that the requested resource content has expired from
-// the server (usually due to a resourceVersion that is too old).
-func NewResourceExpired(message string) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusGone,
- Reason: metav1.StatusReasonExpired,
- Message: message,
- }}
-}
-
-// NewInvalid returns an error indicating the item is invalid and cannot be processed.
-func NewInvalid(qualifiedKind schema.GroupKind, name string, errs field.ErrorList) *StatusError {
- causes := make([]metav1.StatusCause, 0, len(errs))
- for i := range errs {
- err := errs[i]
- causes = append(causes, metav1.StatusCause{
- Type: metav1.CauseType(err.Type),
- Message: err.ErrorBody(),
- Field: err.Field,
- })
- }
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusUnprocessableEntity,
- Reason: metav1.StatusReasonInvalid,
- Details: &metav1.StatusDetails{
- Group: qualifiedKind.Group,
- Kind: qualifiedKind.Kind,
- Name: name,
- Causes: causes,
- },
- Message: fmt.Sprintf("%s %q is invalid: %v", qualifiedKind.String(), name, errs.ToAggregate()),
- }}
-}
-
-// NewBadRequest creates an error that indicates that the request is invalid and can not be processed.
-func NewBadRequest(reason string) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusBadRequest,
- Reason: metav1.StatusReasonBadRequest,
- Message: reason,
- }}
-}
-
-// NewTooManyRequests creates an error that indicates that the client must try again later because
-// the specified endpoint is not accepting requests. More specific details should be provided
-// if client should know why the failure was limited4.
-func NewTooManyRequests(message string, retryAfterSeconds int) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusTooManyRequests,
- Reason: metav1.StatusReasonTooManyRequests,
- Message: message,
- Details: &metav1.StatusDetails{
- RetryAfterSeconds: int32(retryAfterSeconds),
- },
- }}
-}
-
-// NewServiceUnavailable creates an error that indicates that the requested service is unavailable.
-func NewServiceUnavailable(reason string) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusServiceUnavailable,
- Reason: metav1.StatusReasonServiceUnavailable,
- Message: reason,
- }}
-}
-
-// NewMethodNotSupported returns an error indicating the requested action is not supported on this kind.
-func NewMethodNotSupported(qualifiedResource schema.GroupResource, action string) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusMethodNotAllowed,
- Reason: metav1.StatusReasonMethodNotAllowed,
- Details: &metav1.StatusDetails{
- Group: qualifiedResource.Group,
- Kind: qualifiedResource.Resource,
- },
- Message: fmt.Sprintf("%s is not supported on resources of kind %q", action, qualifiedResource.String()),
- }}
-}
-
-// NewServerTimeout returns an error indicating the requested action could not be completed due to a
-// transient error, and the client should try again.
-func NewServerTimeout(qualifiedResource schema.GroupResource, operation string, retryAfterSeconds int) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusInternalServerError,
- Reason: metav1.StatusReasonServerTimeout,
- Details: &metav1.StatusDetails{
- Group: qualifiedResource.Group,
- Kind: qualifiedResource.Resource,
- Name: operation,
- RetryAfterSeconds: int32(retryAfterSeconds),
- },
- Message: fmt.Sprintf("The %s operation against %s could not be completed at this time, please try again.", operation, qualifiedResource.String()),
- }}
-}
-
-// NewServerTimeoutForKind should not exist. Server timeouts happen when accessing resources, the Kind is just what we
-// happened to be looking at when the request failed. This delegates to keep code sane, but we should work towards removing this.
-func NewServerTimeoutForKind(qualifiedKind schema.GroupKind, operation string, retryAfterSeconds int) *StatusError {
- return NewServerTimeout(schema.GroupResource{Group: qualifiedKind.Group, Resource: qualifiedKind.Kind}, operation, retryAfterSeconds)
-}
-
-// NewInternalError returns an error indicating the item is invalid and cannot be processed.
-func NewInternalError(err error) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusInternalServerError,
- Reason: metav1.StatusReasonInternalError,
- Details: &metav1.StatusDetails{
- Causes: []metav1.StatusCause{{Message: err.Error()}},
- },
- Message: fmt.Sprintf("Internal error occurred: %v", err),
- }}
-}
-
-// NewTimeoutError returns an error indicating that a timeout occurred before the request
-// could be completed. Clients may retry, but the operation may still complete.
-func NewTimeoutError(message string, retryAfterSeconds int) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusGatewayTimeout,
- Reason: metav1.StatusReasonTimeout,
- Message: fmt.Sprintf("Timeout: %s", message),
- Details: &metav1.StatusDetails{
- RetryAfterSeconds: int32(retryAfterSeconds),
- },
- }}
-}
-
-// NewTooManyRequestsError returns an error indicating that the request was rejected because
-// the server has received too many requests. Client should wait and retry. But if the request
-// is perishable, then the client should not retry the request.
-func NewTooManyRequestsError(message string) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusTooManyRequests,
- Reason: metav1.StatusReasonTooManyRequests,
- Message: fmt.Sprintf("Too many requests: %s", message),
- }}
-}
-
-// NewRequestEntityTooLargeError returns an error indicating that the request
-// entity was too large.
-func NewRequestEntityTooLargeError(message string) *StatusError {
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusRequestEntityTooLarge,
- Reason: metav1.StatusReasonRequestEntityTooLarge,
- Message: fmt.Sprintf("Request entity too large: %s", message),
- }}
-}
-
-// NewGenericServerResponse returns a new error for server responses that are not in a recognizable form.
-func NewGenericServerResponse(code int, verb string, qualifiedResource schema.GroupResource, name, serverMessage string, retryAfterSeconds int, isUnexpectedResponse bool) *StatusError {
- reason := metav1.StatusReasonUnknown
- message := fmt.Sprintf("the server responded with the status code %d but did not return more information", code)
- switch code {
- case http.StatusConflict:
- if verb == "POST" {
- reason = metav1.StatusReasonAlreadyExists
- } else {
- reason = metav1.StatusReasonConflict
- }
- message = "the server reported a conflict"
- case http.StatusNotFound:
- reason = metav1.StatusReasonNotFound
- message = "the server could not find the requested resource"
- case http.StatusBadRequest:
- reason = metav1.StatusReasonBadRequest
- message = "the server rejected our request for an unknown reason"
- case http.StatusUnauthorized:
- reason = metav1.StatusReasonUnauthorized
- message = "the server has asked for the client to provide credentials"
- case http.StatusForbidden:
- reason = metav1.StatusReasonForbidden
- // the server message has details about who is trying to perform what action. Keep its message.
- message = serverMessage
- case http.StatusNotAcceptable:
- reason = metav1.StatusReasonNotAcceptable
- // the server message has details about what types are acceptable
- if len(serverMessage) == 0 || serverMessage == "unknown" {
- message = "the server was unable to respond with a content type that the client supports"
- } else {
- message = serverMessage
- }
- case http.StatusUnsupportedMediaType:
- reason = metav1.StatusReasonUnsupportedMediaType
- // the server message has details about what types are acceptable
- message = serverMessage
- case http.StatusMethodNotAllowed:
- reason = metav1.StatusReasonMethodNotAllowed
- message = "the server does not allow this method on the requested resource"
- case http.StatusUnprocessableEntity:
- reason = metav1.StatusReasonInvalid
- message = "the server rejected our request due to an error in our request"
- case http.StatusServiceUnavailable:
- reason = metav1.StatusReasonServiceUnavailable
- message = "the server is currently unable to handle the request"
- case http.StatusGatewayTimeout:
- reason = metav1.StatusReasonTimeout
- message = "the server was unable to return a response in the time allotted, but may still be processing the request"
- case http.StatusTooManyRequests:
- reason = metav1.StatusReasonTooManyRequests
- message = "the server has received too many requests and has asked us to try again later"
- default:
- if code >= 500 {
- reason = metav1.StatusReasonInternalError
- message = fmt.Sprintf("an error on the server (%q) has prevented the request from succeeding", serverMessage)
- }
- }
- switch {
- case !qualifiedResource.Empty() && len(name) > 0:
- message = fmt.Sprintf("%s (%s %s %s)", message, strings.ToLower(verb), qualifiedResource.String(), name)
- case !qualifiedResource.Empty():
- message = fmt.Sprintf("%s (%s %s)", message, strings.ToLower(verb), qualifiedResource.String())
- }
- var causes []metav1.StatusCause
- if isUnexpectedResponse {
- causes = []metav1.StatusCause{
- {
- Type: metav1.CauseTypeUnexpectedServerResponse,
- Message: serverMessage,
- },
- }
- } else {
- causes = nil
- }
- return &StatusError{metav1.Status{
- Status: metav1.StatusFailure,
- Code: int32(code),
- Reason: reason,
- Details: &metav1.StatusDetails{
- Group: qualifiedResource.Group,
- Kind: qualifiedResource.Resource,
- Name: name,
-
- Causes: causes,
- RetryAfterSeconds: int32(retryAfterSeconds),
- },
- Message: message,
- }}
-}
-
-// IsNotFound returns true if the specified error was created by NewNotFound.
-// It supports wrapped errors.
-func IsNotFound(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonNotFound
-}
-
-// IsAlreadyExists determines if the err is an error which indicates that a specified resource already exists.
-// It supports wrapped errors.
-func IsAlreadyExists(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonAlreadyExists
-}
-
-// IsConflict determines if the err is an error which indicates the provided update conflicts.
-// It supports wrapped errors.
-func IsConflict(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonConflict
-}
-
-// IsInvalid determines if the err is an error which indicates the provided resource is not valid.
-// It supports wrapped errors.
-func IsInvalid(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonInvalid
-}
-
-// IsGone is true if the error indicates the requested resource is no longer available.
-// It supports wrapped errors.
-func IsGone(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonGone
-}
-
-// IsResourceExpired is true if the error indicates the resource has expired and the current action is
-// no longer possible.
-// It supports wrapped errors.
-func IsResourceExpired(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonExpired
-}
-
-// IsNotAcceptable determines if err is an error which indicates that the request failed due to an invalid Accept header
-// It supports wrapped errors.
-func IsNotAcceptable(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonNotAcceptable
-}
-
-// IsUnsupportedMediaType determines if err is an error which indicates that the request failed due to an invalid Content-Type header
-// It supports wrapped errors.
-func IsUnsupportedMediaType(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonUnsupportedMediaType
-}
-
-// IsMethodNotSupported determines if the err is an error which indicates the provided action could not
-// be performed because it is not supported by the server.
-// It supports wrapped errors.
-func IsMethodNotSupported(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonMethodNotAllowed
-}
-
-// IsServiceUnavailable is true if the error indicates the underlying service is no longer available.
-// It supports wrapped errors.
-func IsServiceUnavailable(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonServiceUnavailable
-}
-
-// IsBadRequest determines if err is an error which indicates that the request is invalid.
-// It supports wrapped errors.
-func IsBadRequest(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonBadRequest
-}
-
-// IsUnauthorized determines if err is an error which indicates that the request is unauthorized and
-// requires authentication by the user.
-// It supports wrapped errors.
-func IsUnauthorized(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonUnauthorized
-}
-
-// IsForbidden determines if err is an error which indicates that the request is forbidden and cannot
-// be completed as requested.
-// It supports wrapped errors.
-func IsForbidden(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonForbidden
-}
-
-// IsTimeout determines if err is an error which indicates that request times out due to long
-// processing.
-// It supports wrapped errors.
-func IsTimeout(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonTimeout
-}
-
-// IsServerTimeout determines if err is an error which indicates that the request needs to be retried
-// by the client.
-// It supports wrapped errors.
-func IsServerTimeout(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonServerTimeout
-}
-
-// IsInternalError determines if err is an error which indicates an internal server error.
-// It supports wrapped errors.
-func IsInternalError(err error) bool {
- return ReasonForError(err) == metav1.StatusReasonInternalError
-}
-
-// IsTooManyRequests determines if err is an error which indicates that there are too many requests
-// that the server cannot handle.
-// It supports wrapped errors.
-func IsTooManyRequests(err error) bool {
- if ReasonForError(err) == metav1.StatusReasonTooManyRequests {
- return true
- }
- if status := APIStatus(nil); errors.As(err, &status) {
- return status.Status().Code == http.StatusTooManyRequests
- }
- return false
-}
-
-// IsRequestEntityTooLargeError determines if err is an error which indicates
-// the request entity is too large.
-// It supports wrapped errors.
-func IsRequestEntityTooLargeError(err error) bool {
- if ReasonForError(err) == metav1.StatusReasonRequestEntityTooLarge {
- return true
- }
- if status := APIStatus(nil); errors.As(err, &status) {
- return status.Status().Code == http.StatusRequestEntityTooLarge
- }
- return false
-}
-
-// IsUnexpectedServerError returns true if the server response was not in the expected API format,
-// and may be the result of another HTTP actor.
-// It supports wrapped errors.
-func IsUnexpectedServerError(err error) bool {
- if status := APIStatus(nil); errors.As(err, &status) && status.Status().Details != nil {
- for _, cause := range status.Status().Details.Causes {
- if cause.Type == metav1.CauseTypeUnexpectedServerResponse {
- return true
- }
- }
- }
- return false
-}
-
-// IsUnexpectedObjectError determines if err is due to an unexpected object from the master.
-// It supports wrapped errors.
-func IsUnexpectedObjectError(err error) bool {
- uoe := &UnexpectedObjectError{}
- return err != nil && errors.As(err, &uoe)
-}
-
-// SuggestsClientDelay returns true if this error suggests a client delay as well as the
-// suggested seconds to wait, or false if the error does not imply a wait. It does not
-// address whether the error *should* be retried, since some errors (like a 3xx) may
-// request delay without retry.
-// It supports wrapped errors.
-func SuggestsClientDelay(err error) (int, bool) {
- if t := APIStatus(nil); errors.As(err, &t) && t.Status().Details != nil {
- switch t.Status().Reason {
- // this StatusReason explicitly requests the caller to delay the action
- case metav1.StatusReasonServerTimeout:
- return int(t.Status().Details.RetryAfterSeconds), true
- }
- // If the client requests that we retry after a certain number of seconds
- if t.Status().Details.RetryAfterSeconds > 0 {
- return int(t.Status().Details.RetryAfterSeconds), true
- }
- }
- return 0, false
-}
-
-// ReasonForError returns the HTTP status for a particular error.
-// It supports wrapped errors.
-func ReasonForError(err error) metav1.StatusReason {
- if status := APIStatus(nil); errors.As(err, &status) {
- return status.Status().Reason
- }
- return metav1.StatusReasonUnknown
-}
-
-// ErrorReporter converts generic errors into runtime.Object errors without
-// requiring the caller to take a dependency on meta/v1 (where Status lives).
-// This prevents circular dependencies in core watch code.
-type ErrorReporter struct {
- code int
- verb string
- reason string
-}
-
-// NewClientErrorReporter will respond with valid v1.Status objects that report
-// unexpected server responses. Primarily used by watch to report errors when
-// we attempt to decode a response from the server and it is not in the form
-// we expect. Because watch is a dependency of the core api, we can't return
-// meta/v1.Status in that package and so much inject this interface to convert a
-// generic error as appropriate. The reason is passed as a unique status cause
-// on the returned status, otherwise the generic "ClientError" is returned.
-func NewClientErrorReporter(code int, verb string, reason string) *ErrorReporter {
- return &ErrorReporter{
- code: code,
- verb: verb,
- reason: reason,
- }
-}
-
-// AsObject returns a valid error runtime.Object (a v1.Status) for the given
-// error, using the code and verb of the reporter type. The error is set to
-// indicate that this was an unexpected server response.
-func (r *ErrorReporter) AsObject(err error) runtime.Object {
- status := NewGenericServerResponse(r.code, r.verb, schema.GroupResource{}, "", err.Error(), 0, true)
- if status.ErrStatus.Details == nil {
- status.ErrStatus.Details = &metav1.StatusDetails{}
- }
- reason := r.reason
- if len(reason) == 0 {
- reason = "ClientError"
- }
- status.ErrStatus.Details.Causes = append(status.ErrStatus.Details.Causes, metav1.StatusCause{
- Type: metav1.CauseType(reason),
- Message: err.Error(),
- })
- return &status.ErrStatus
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go
deleted file mode 100644
index 7b101ea51..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go
+++ /dev/null
@@ -1,500 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package unstructured
-
-import (
- gojson "encoding/json"
- "fmt"
- "io"
- "strings"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/types"
- "k8s.io/apimachinery/pkg/util/json"
- "k8s.io/klog/v2"
-)
-
-// NestedFieldCopy returns a deep copy of the value of a nested field.
-// Returns false if the value is missing.
-// No error is returned for a nil field.
-//
-// Note: fields passed to this function are treated as keys within the passed
-// object; no array/slice syntax is supported.
-func NestedFieldCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error) {
- val, found, err := NestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- return runtime.DeepCopyJSONValue(val), true, nil
-}
-
-// NestedFieldNoCopy returns a reference to a nested field.
-// Returns false if value is not found and an error if unable
-// to traverse obj.
-//
-// Note: fields passed to this function are treated as keys within the passed
-// object; no array/slice syntax is supported.
-func NestedFieldNoCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error) {
- var val interface{} = obj
-
- for i, field := range fields {
- if val == nil {
- return nil, false, nil
- }
- if m, ok := val.(map[string]interface{}); ok {
- val, ok = m[field]
- if !ok {
- return nil, false, nil
- }
- } else {
- return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected map[string]interface{}", jsonPath(fields[:i+1]), val, val)
- }
- }
- return val, true, nil
-}
-
-// NestedString returns the string value of a nested field.
-// Returns false if value is not found and an error if not a string.
-func NestedString(obj map[string]interface{}, fields ...string) (string, bool, error) {
- val, found, err := NestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return "", found, err
- }
- s, ok := val.(string)
- if !ok {
- return "", false, fmt.Errorf("%v accessor error: %v is of the type %T, expected string", jsonPath(fields), val, val)
- }
- return s, true, nil
-}
-
-// NestedBool returns the bool value of a nested field.
-// Returns false if value is not found and an error if not a bool.
-func NestedBool(obj map[string]interface{}, fields ...string) (bool, bool, error) {
- val, found, err := NestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return false, found, err
- }
- b, ok := val.(bool)
- if !ok {
- return false, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected bool", jsonPath(fields), val, val)
- }
- return b, true, nil
-}
-
-// NestedFloat64 returns the float64 value of a nested field.
-// Returns false if value is not found and an error if not a float64.
-func NestedFloat64(obj map[string]interface{}, fields ...string) (float64, bool, error) {
- val, found, err := NestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return 0, found, err
- }
- f, ok := val.(float64)
- if !ok {
- return 0, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected float64", jsonPath(fields), val, val)
- }
- return f, true, nil
-}
-
-// NestedInt64 returns the int64 value of a nested field.
-// Returns false if value is not found and an error if not an int64.
-func NestedInt64(obj map[string]interface{}, fields ...string) (int64, bool, error) {
- val, found, err := NestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return 0, found, err
- }
- i, ok := val.(int64)
- if !ok {
- return 0, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected int64", jsonPath(fields), val, val)
- }
- return i, true, nil
-}
-
-// NestedStringSlice returns a copy of []string value of a nested field.
-// Returns false if value is not found and an error if not a []interface{} or contains non-string items in the slice.
-func NestedStringSlice(obj map[string]interface{}, fields ...string) ([]string, bool, error) {
- val, found, err := NestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- m, ok := val.([]interface{})
- if !ok {
- return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected []interface{}", jsonPath(fields), val, val)
- }
- strSlice := make([]string, 0, len(m))
- for _, v := range m {
- if str, ok := v.(string); ok {
- strSlice = append(strSlice, str)
- } else {
- return nil, false, fmt.Errorf("%v accessor error: contains non-string key in the slice: %v is of the type %T, expected string", jsonPath(fields), v, v)
- }
- }
- return strSlice, true, nil
-}
-
-// NestedSlice returns a deep copy of []interface{} value of a nested field.
-// Returns false if value is not found and an error if not a []interface{}.
-func NestedSlice(obj map[string]interface{}, fields ...string) ([]interface{}, bool, error) {
- val, found, err := NestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- _, ok := val.([]interface{})
- if !ok {
- return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected []interface{}", jsonPath(fields), val, val)
- }
- return runtime.DeepCopyJSONValue(val).([]interface{}), true, nil
-}
-
-// NestedStringMap returns a copy of map[string]string value of a nested field.
-// Returns false if value is not found and an error if not a map[string]interface{} or contains non-string values in the map.
-func NestedStringMap(obj map[string]interface{}, fields ...string) (map[string]string, bool, error) {
- m, found, err := nestedMapNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- strMap := make(map[string]string, len(m))
- for k, v := range m {
- if str, ok := v.(string); ok {
- strMap[k] = str
- } else {
- return nil, false, fmt.Errorf("%v accessor error: contains non-string key in the map: %v is of the type %T, expected string", jsonPath(fields), v, v)
- }
- }
- return strMap, true, nil
-}
-
-// NestedMap returns a deep copy of map[string]interface{} value of a nested field.
-// Returns false if value is not found and an error if not a map[string]interface{}.
-func NestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error) {
- m, found, err := nestedMapNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- return runtime.DeepCopyJSON(m), true, nil
-}
-
-// nestedMapNoCopy returns a map[string]interface{} value of a nested field.
-// Returns false if value is not found and an error if not a map[string]interface{}.
-func nestedMapNoCopy(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error) {
- val, found, err := NestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- m, ok := val.(map[string]interface{})
- if !ok {
- return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected map[string]interface{}", jsonPath(fields), val, val)
- }
- return m, true, nil
-}
-
-// SetNestedField sets the value of a nested field to a deep copy of the value provided.
-// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
-func SetNestedField(obj map[string]interface{}, value interface{}, fields ...string) error {
- return setNestedFieldNoCopy(obj, runtime.DeepCopyJSONValue(value), fields...)
-}
-
-func setNestedFieldNoCopy(obj map[string]interface{}, value interface{}, fields ...string) error {
- m := obj
-
- for i, field := range fields[:len(fields)-1] {
- if val, ok := m[field]; ok {
- if valMap, ok := val.(map[string]interface{}); ok {
- m = valMap
- } else {
- return fmt.Errorf("value cannot be set because %v is not a map[string]interface{}", jsonPath(fields[:i+1]))
- }
- } else {
- newVal := make(map[string]interface{})
- m[field] = newVal
- m = newVal
- }
- }
- m[fields[len(fields)-1]] = value
- return nil
-}
-
-// SetNestedStringSlice sets the string slice value of a nested field.
-// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
-func SetNestedStringSlice(obj map[string]interface{}, value []string, fields ...string) error {
- m := make([]interface{}, 0, len(value)) // convert []string into []interface{}
- for _, v := range value {
- m = append(m, v)
- }
- return setNestedFieldNoCopy(obj, m, fields...)
-}
-
-// SetNestedSlice sets the slice value of a nested field.
-// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
-func SetNestedSlice(obj map[string]interface{}, value []interface{}, fields ...string) error {
- return SetNestedField(obj, value, fields...)
-}
-
-// SetNestedStringMap sets the map[string]string value of a nested field.
-// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
-func SetNestedStringMap(obj map[string]interface{}, value map[string]string, fields ...string) error {
- m := make(map[string]interface{}, len(value)) // convert map[string]string into map[string]interface{}
- for k, v := range value {
- m[k] = v
- }
- return setNestedFieldNoCopy(obj, m, fields...)
-}
-
-// SetNestedMap sets the map[string]interface{} value of a nested field.
-// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
-func SetNestedMap(obj map[string]interface{}, value map[string]interface{}, fields ...string) error {
- return SetNestedField(obj, value, fields...)
-}
-
-// RemoveNestedField removes the nested field from the obj.
-func RemoveNestedField(obj map[string]interface{}, fields ...string) {
- m := obj
- for _, field := range fields[:len(fields)-1] {
- if x, ok := m[field].(map[string]interface{}); ok {
- m = x
- } else {
- return
- }
- }
- delete(m, fields[len(fields)-1])
-}
-
-func getNestedString(obj map[string]interface{}, fields ...string) string {
- val, found, err := NestedString(obj, fields...)
- if !found || err != nil {
- return ""
- }
- return val
-}
-
-func getNestedInt64Pointer(obj map[string]interface{}, fields ...string) *int64 {
- val, found, err := NestedInt64(obj, fields...)
- if !found || err != nil {
- return nil
- }
- return &val
-}
-
-func jsonPath(fields []string) string {
- return "." + strings.Join(fields, ".")
-}
-
-func extractOwnerReference(v map[string]interface{}) metav1.OwnerReference {
- // though this field is a *bool, but when decoded from JSON, it's
- // unmarshalled as bool.
- var controllerPtr *bool
- if controller, found, err := NestedBool(v, "controller"); err == nil && found {
- controllerPtr = &controller
- }
- var blockOwnerDeletionPtr *bool
- if blockOwnerDeletion, found, err := NestedBool(v, "blockOwnerDeletion"); err == nil && found {
- blockOwnerDeletionPtr = &blockOwnerDeletion
- }
- return metav1.OwnerReference{
- Kind: getNestedString(v, "kind"),
- Name: getNestedString(v, "name"),
- APIVersion: getNestedString(v, "apiVersion"),
- UID: types.UID(getNestedString(v, "uid")),
- Controller: controllerPtr,
- BlockOwnerDeletion: blockOwnerDeletionPtr,
- }
-}
-
-// UnstructuredJSONScheme is capable of converting JSON data into the Unstructured
-// type, which can be used for generic access to objects without a predefined scheme.
-// TODO: move into serializer/json.
-var UnstructuredJSONScheme runtime.Codec = unstructuredJSONScheme{}
-
-type unstructuredJSONScheme struct{}
-
-const unstructuredJSONSchemeIdentifier runtime.Identifier = "unstructuredJSON"
-
-func (s unstructuredJSONScheme) Decode(data []byte, _ *schema.GroupVersionKind, obj runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
- var err error
- if obj != nil {
- err = s.decodeInto(data, obj)
- } else {
- obj, err = s.decode(data)
- }
-
- if err != nil {
- return nil, nil, err
- }
-
- gvk := obj.GetObjectKind().GroupVersionKind()
- if len(gvk.Kind) == 0 {
- return nil, &gvk, runtime.NewMissingKindErr(string(data))
- }
-
- return obj, &gvk, nil
-}
-
-func (s unstructuredJSONScheme) Encode(obj runtime.Object, w io.Writer) error {
- if co, ok := obj.(runtime.CacheableObject); ok {
- return co.CacheEncode(s.Identifier(), s.doEncode, w)
- }
- return s.doEncode(obj, w)
-}
-
-func (unstructuredJSONScheme) doEncode(obj runtime.Object, w io.Writer) error {
- switch t := obj.(type) {
- case *Unstructured:
- return json.NewEncoder(w).Encode(t.Object)
- case *UnstructuredList:
- items := make([]interface{}, 0, len(t.Items))
- for _, i := range t.Items {
- items = append(items, i.Object)
- }
- listObj := make(map[string]interface{}, len(t.Object)+1)
- for k, v := range t.Object { // Make a shallow copy
- listObj[k] = v
- }
- listObj["items"] = items
- return json.NewEncoder(w).Encode(listObj)
- case *runtime.Unknown:
- // TODO: Unstructured needs to deal with ContentType.
- _, err := w.Write(t.Raw)
- return err
- default:
- return json.NewEncoder(w).Encode(t)
- }
-}
-
-// Identifier implements runtime.Encoder interface.
-func (unstructuredJSONScheme) Identifier() runtime.Identifier {
- return unstructuredJSONSchemeIdentifier
-}
-
-func (s unstructuredJSONScheme) decode(data []byte) (runtime.Object, error) {
- type detector struct {
- Items gojson.RawMessage
- }
- var det detector
- if err := json.Unmarshal(data, &det); err != nil {
- return nil, err
- }
-
- if det.Items != nil {
- list := &UnstructuredList{}
- err := s.decodeToList(data, list)
- return list, err
- }
-
- // No Items field, so it wasn't a list.
- unstruct := &Unstructured{}
- err := s.decodeToUnstructured(data, unstruct)
- return unstruct, err
-}
-
-func (s unstructuredJSONScheme) decodeInto(data []byte, obj runtime.Object) error {
- switch x := obj.(type) {
- case *Unstructured:
- return s.decodeToUnstructured(data, x)
- case *UnstructuredList:
- return s.decodeToList(data, x)
- default:
- return json.Unmarshal(data, x)
- }
-}
-
-func (unstructuredJSONScheme) decodeToUnstructured(data []byte, unstruct *Unstructured) error {
- m := make(map[string]interface{})
- if err := json.Unmarshal(data, &m); err != nil {
- return err
- }
-
- unstruct.Object = m
-
- return nil
-}
-
-func (s unstructuredJSONScheme) decodeToList(data []byte, list *UnstructuredList) error {
- type decodeList struct {
- Items []gojson.RawMessage
- }
-
- var dList decodeList
- if err := json.Unmarshal(data, &dList); err != nil {
- return err
- }
-
- if err := json.Unmarshal(data, &list.Object); err != nil {
- return err
- }
-
- // For typed lists, e.g., a PodList, API server doesn't set each item's
- // APIVersion and Kind. We need to set it.
- listAPIVersion := list.GetAPIVersion()
- listKind := list.GetKind()
- itemKind := strings.TrimSuffix(listKind, "List")
-
- delete(list.Object, "items")
- list.Items = make([]Unstructured, 0, len(dList.Items))
- for _, i := range dList.Items {
- unstruct := &Unstructured{}
- if err := s.decodeToUnstructured([]byte(i), unstruct); err != nil {
- return err
- }
- // This is hacky. Set the item's Kind and APIVersion to those inferred
- // from the List.
- if len(unstruct.GetKind()) == 0 && len(unstruct.GetAPIVersion()) == 0 {
- unstruct.SetKind(itemKind)
- unstruct.SetAPIVersion(listAPIVersion)
- }
- list.Items = append(list.Items, *unstruct)
- }
- return nil
-}
-
-type jsonFallbackEncoder struct {
- encoder runtime.Encoder
- identifier runtime.Identifier
-}
-
-func NewJSONFallbackEncoder(encoder runtime.Encoder) runtime.Encoder {
- result := map[string]string{
- "name": "fallback",
- "base": string(encoder.Identifier()),
- }
- identifier, err := gojson.Marshal(result)
- if err != nil {
- klog.Fatalf("Failed marshaling identifier for jsonFallbackEncoder: %v", err)
- }
- return &jsonFallbackEncoder{
- encoder: encoder,
- identifier: runtime.Identifier(identifier),
- }
-}
-
-func (c *jsonFallbackEncoder) Encode(obj runtime.Object, w io.Writer) error {
- // There is no need to handle runtime.CacheableObject, as we only
- // fallback to other encoders here.
- err := c.encoder.Encode(obj, w)
- if runtime.IsNotRegisteredError(err) {
- switch obj.(type) {
- case *Unstructured, *UnstructuredList:
- return UnstructuredJSONScheme.Encode(obj, w)
- }
- }
- return err
-}
-
-// Identifier implements runtime.Encoder interface.
-func (c *jsonFallbackEncoder) Identifier() runtime.Identifier {
- return c.identifier
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go
deleted file mode 100644
index d1903394d..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go
+++ /dev/null
@@ -1,496 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package unstructured
-
-import (
- "bytes"
- "errors"
- "fmt"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/types"
- utilruntime "k8s.io/apimachinery/pkg/util/runtime"
-)
-
-// Unstructured allows objects that do not have Golang structs registered to be manipulated
-// generically. This can be used to deal with the API objects from a plug-in. Unstructured
-// objects still have functioning TypeMeta features-- kind, version, etc.
-//
-// WARNING: This object has accessors for the v1 standard metadata. You *MUST NOT* use this
-// type if you are dealing with objects that are not in the server meta v1 schema.
-//
-// TODO: make the serialization part of this type distinct from the field accessors.
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-// +k8s:deepcopy-gen=true
-type Unstructured struct {
- // Object is a JSON compatible map with string, float, int, bool, []interface{}, or
- // map[string]interface{}
- // children.
- Object map[string]interface{}
-}
-
-var _ metav1.Object = &Unstructured{}
-var _ runtime.Unstructured = &Unstructured{}
-var _ metav1.ListInterface = &Unstructured{}
-
-func (obj *Unstructured) GetObjectKind() schema.ObjectKind { return obj }
-
-func (obj *Unstructured) IsList() bool {
- field, ok := obj.Object["items"]
- if !ok {
- return false
- }
- _, ok = field.([]interface{})
- return ok
-}
-func (obj *Unstructured) ToList() (*UnstructuredList, error) {
- if !obj.IsList() {
- // return an empty list back
- return &UnstructuredList{Object: obj.Object}, nil
- }
-
- ret := &UnstructuredList{}
- ret.Object = obj.Object
-
- err := obj.EachListItem(func(item runtime.Object) error {
- castItem := item.(*Unstructured)
- ret.Items = append(ret.Items, *castItem)
- return nil
- })
- if err != nil {
- return nil, err
- }
-
- return ret, nil
-}
-
-func (obj *Unstructured) EachListItem(fn func(runtime.Object) error) error {
- field, ok := obj.Object["items"]
- if !ok {
- return errors.New("content is not a list")
- }
- items, ok := field.([]interface{})
- if !ok {
- return fmt.Errorf("content is not a list: %T", field)
- }
- for _, item := range items {
- child, ok := item.(map[string]interface{})
- if !ok {
- return fmt.Errorf("items member is not an object: %T", child)
- }
- if err := fn(&Unstructured{Object: child}); err != nil {
- return err
- }
- }
- return nil
-}
-
-func (obj *Unstructured) UnstructuredContent() map[string]interface{} {
- if obj.Object == nil {
- return make(map[string]interface{})
- }
- return obj.Object
-}
-
-func (obj *Unstructured) SetUnstructuredContent(content map[string]interface{}) {
- obj.Object = content
-}
-
-// MarshalJSON ensures that the unstructured object produces proper
-// JSON when passed to Go's standard JSON library.
-func (u *Unstructured) MarshalJSON() ([]byte, error) {
- var buf bytes.Buffer
- err := UnstructuredJSONScheme.Encode(u, &buf)
- return buf.Bytes(), err
-}
-
-// UnmarshalJSON ensures that the unstructured object properly decodes
-// JSON when passed to Go's standard JSON library.
-func (u *Unstructured) UnmarshalJSON(b []byte) error {
- _, _, err := UnstructuredJSONScheme.Decode(b, nil, u)
- return err
-}
-
-// NewEmptyInstance returns a new instance of the concrete type containing only kind/apiVersion and no other data.
-// This should be called instead of reflect.New() for unstructured types because the go type alone does not preserve kind/apiVersion info.
-func (in *Unstructured) NewEmptyInstance() runtime.Unstructured {
- out := new(Unstructured)
- if in != nil {
- out.GetObjectKind().SetGroupVersionKind(in.GetObjectKind().GroupVersionKind())
- }
- return out
-}
-
-func (in *Unstructured) DeepCopy() *Unstructured {
- if in == nil {
- return nil
- }
- out := new(Unstructured)
- *out = *in
- out.Object = runtime.DeepCopyJSON(in.Object)
- return out
-}
-
-func (u *Unstructured) setNestedField(value interface{}, fields ...string) {
- if u.Object == nil {
- u.Object = make(map[string]interface{})
- }
- SetNestedField(u.Object, value, fields...)
-}
-
-func (u *Unstructured) setNestedStringSlice(value []string, fields ...string) {
- if u.Object == nil {
- u.Object = make(map[string]interface{})
- }
- SetNestedStringSlice(u.Object, value, fields...)
-}
-
-func (u *Unstructured) setNestedSlice(value []interface{}, fields ...string) {
- if u.Object == nil {
- u.Object = make(map[string]interface{})
- }
- SetNestedSlice(u.Object, value, fields...)
-}
-
-func (u *Unstructured) setNestedMap(value map[string]string, fields ...string) {
- if u.Object == nil {
- u.Object = make(map[string]interface{})
- }
- SetNestedStringMap(u.Object, value, fields...)
-}
-
-func (u *Unstructured) GetOwnerReferences() []metav1.OwnerReference {
- field, found, err := NestedFieldNoCopy(u.Object, "metadata", "ownerReferences")
- if !found || err != nil {
- return nil
- }
- original, ok := field.([]interface{})
- if !ok {
- return nil
- }
- ret := make([]metav1.OwnerReference, 0, len(original))
- for _, obj := range original {
- o, ok := obj.(map[string]interface{})
- if !ok {
- // expected map[string]interface{}, got something else
- return nil
- }
- ret = append(ret, extractOwnerReference(o))
- }
- return ret
-}
-
-func (u *Unstructured) SetOwnerReferences(references []metav1.OwnerReference) {
- if references == nil {
- RemoveNestedField(u.Object, "metadata", "ownerReferences")
- return
- }
-
- newReferences := make([]interface{}, 0, len(references))
- for _, reference := range references {
- out, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&reference)
- if err != nil {
- utilruntime.HandleError(fmt.Errorf("unable to convert Owner Reference: %v", err))
- continue
- }
- newReferences = append(newReferences, out)
- }
- u.setNestedField(newReferences, "metadata", "ownerReferences")
-}
-
-func (u *Unstructured) GetAPIVersion() string {
- return getNestedString(u.Object, "apiVersion")
-}
-
-func (u *Unstructured) SetAPIVersion(version string) {
- u.setNestedField(version, "apiVersion")
-}
-
-func (u *Unstructured) GetKind() string {
- return getNestedString(u.Object, "kind")
-}
-
-func (u *Unstructured) SetKind(kind string) {
- u.setNestedField(kind, "kind")
-}
-
-func (u *Unstructured) GetNamespace() string {
- return getNestedString(u.Object, "metadata", "namespace")
-}
-
-func (u *Unstructured) SetNamespace(namespace string) {
- if len(namespace) == 0 {
- RemoveNestedField(u.Object, "metadata", "namespace")
- return
- }
- u.setNestedField(namespace, "metadata", "namespace")
-}
-
-func (u *Unstructured) GetName() string {
- return getNestedString(u.Object, "metadata", "name")
-}
-
-func (u *Unstructured) SetName(name string) {
- if len(name) == 0 {
- RemoveNestedField(u.Object, "metadata", "name")
- return
- }
- u.setNestedField(name, "metadata", "name")
-}
-
-func (u *Unstructured) GetGenerateName() string {
- return getNestedString(u.Object, "metadata", "generateName")
-}
-
-func (u *Unstructured) SetGenerateName(generateName string) {
- if len(generateName) == 0 {
- RemoveNestedField(u.Object, "metadata", "generateName")
- return
- }
- u.setNestedField(generateName, "metadata", "generateName")
-}
-
-func (u *Unstructured) GetUID() types.UID {
- return types.UID(getNestedString(u.Object, "metadata", "uid"))
-}
-
-func (u *Unstructured) SetUID(uid types.UID) {
- if len(string(uid)) == 0 {
- RemoveNestedField(u.Object, "metadata", "uid")
- return
- }
- u.setNestedField(string(uid), "metadata", "uid")
-}
-
-func (u *Unstructured) GetResourceVersion() string {
- return getNestedString(u.Object, "metadata", "resourceVersion")
-}
-
-func (u *Unstructured) SetResourceVersion(resourceVersion string) {
- if len(resourceVersion) == 0 {
- RemoveNestedField(u.Object, "metadata", "resourceVersion")
- return
- }
- u.setNestedField(resourceVersion, "metadata", "resourceVersion")
-}
-
-func (u *Unstructured) GetGeneration() int64 {
- val, found, err := NestedInt64(u.Object, "metadata", "generation")
- if !found || err != nil {
- return 0
- }
- return val
-}
-
-func (u *Unstructured) SetGeneration(generation int64) {
- if generation == 0 {
- RemoveNestedField(u.Object, "metadata", "generation")
- return
- }
- u.setNestedField(generation, "metadata", "generation")
-}
-
-func (u *Unstructured) GetSelfLink() string {
- return getNestedString(u.Object, "metadata", "selfLink")
-}
-
-func (u *Unstructured) SetSelfLink(selfLink string) {
- if len(selfLink) == 0 {
- RemoveNestedField(u.Object, "metadata", "selfLink")
- return
- }
- u.setNestedField(selfLink, "metadata", "selfLink")
-}
-
-func (u *Unstructured) GetContinue() string {
- return getNestedString(u.Object, "metadata", "continue")
-}
-
-func (u *Unstructured) SetContinue(c string) {
- if len(c) == 0 {
- RemoveNestedField(u.Object, "metadata", "continue")
- return
- }
- u.setNestedField(c, "metadata", "continue")
-}
-
-func (u *Unstructured) GetRemainingItemCount() *int64 {
- return getNestedInt64Pointer(u.Object, "metadata", "remainingItemCount")
-}
-
-func (u *Unstructured) SetRemainingItemCount(c *int64) {
- if c == nil {
- RemoveNestedField(u.Object, "metadata", "remainingItemCount")
- } else {
- u.setNestedField(*c, "metadata", "remainingItemCount")
- }
-}
-
-func (u *Unstructured) GetCreationTimestamp() metav1.Time {
- var timestamp metav1.Time
- timestamp.UnmarshalQueryParameter(getNestedString(u.Object, "metadata", "creationTimestamp"))
- return timestamp
-}
-
-func (u *Unstructured) SetCreationTimestamp(timestamp metav1.Time) {
- ts, _ := timestamp.MarshalQueryParameter()
- if len(ts) == 0 || timestamp.Time.IsZero() {
- RemoveNestedField(u.Object, "metadata", "creationTimestamp")
- return
- }
- u.setNestedField(ts, "metadata", "creationTimestamp")
-}
-
-func (u *Unstructured) GetDeletionTimestamp() *metav1.Time {
- var timestamp metav1.Time
- timestamp.UnmarshalQueryParameter(getNestedString(u.Object, "metadata", "deletionTimestamp"))
- if timestamp.IsZero() {
- return nil
- }
- return &timestamp
-}
-
-func (u *Unstructured) SetDeletionTimestamp(timestamp *metav1.Time) {
- if timestamp == nil {
- RemoveNestedField(u.Object, "metadata", "deletionTimestamp")
- return
- }
- ts, _ := timestamp.MarshalQueryParameter()
- u.setNestedField(ts, "metadata", "deletionTimestamp")
-}
-
-func (u *Unstructured) GetDeletionGracePeriodSeconds() *int64 {
- val, found, err := NestedInt64(u.Object, "metadata", "deletionGracePeriodSeconds")
- if !found || err != nil {
- return nil
- }
- return &val
-}
-
-func (u *Unstructured) SetDeletionGracePeriodSeconds(deletionGracePeriodSeconds *int64) {
- if deletionGracePeriodSeconds == nil {
- RemoveNestedField(u.Object, "metadata", "deletionGracePeriodSeconds")
- return
- }
- u.setNestedField(*deletionGracePeriodSeconds, "metadata", "deletionGracePeriodSeconds")
-}
-
-func (u *Unstructured) GetLabels() map[string]string {
- m, _, _ := NestedStringMap(u.Object, "metadata", "labels")
- return m
-}
-
-func (u *Unstructured) SetLabels(labels map[string]string) {
- if labels == nil {
- RemoveNestedField(u.Object, "metadata", "labels")
- return
- }
- u.setNestedMap(labels, "metadata", "labels")
-}
-
-func (u *Unstructured) GetAnnotations() map[string]string {
- m, _, _ := NestedStringMap(u.Object, "metadata", "annotations")
- return m
-}
-
-func (u *Unstructured) SetAnnotations(annotations map[string]string) {
- if annotations == nil {
- RemoveNestedField(u.Object, "metadata", "annotations")
- return
- }
- u.setNestedMap(annotations, "metadata", "annotations")
-}
-
-func (u *Unstructured) SetGroupVersionKind(gvk schema.GroupVersionKind) {
- u.SetAPIVersion(gvk.GroupVersion().String())
- u.SetKind(gvk.Kind)
-}
-
-func (u *Unstructured) GroupVersionKind() schema.GroupVersionKind {
- gv, err := schema.ParseGroupVersion(u.GetAPIVersion())
- if err != nil {
- return schema.GroupVersionKind{}
- }
- gvk := gv.WithKind(u.GetKind())
- return gvk
-}
-
-func (u *Unstructured) GetFinalizers() []string {
- val, _, _ := NestedStringSlice(u.Object, "metadata", "finalizers")
- return val
-}
-
-func (u *Unstructured) SetFinalizers(finalizers []string) {
- if finalizers == nil {
- RemoveNestedField(u.Object, "metadata", "finalizers")
- return
- }
- u.setNestedStringSlice(finalizers, "metadata", "finalizers")
-}
-
-func (u *Unstructured) GetClusterName() string {
- return getNestedString(u.Object, "metadata", "clusterName")
-}
-
-func (u *Unstructured) SetClusterName(clusterName string) {
- if len(clusterName) == 0 {
- RemoveNestedField(u.Object, "metadata", "clusterName")
- return
- }
- u.setNestedField(clusterName, "metadata", "clusterName")
-}
-
-func (u *Unstructured) GetManagedFields() []metav1.ManagedFieldsEntry {
- items, found, err := NestedSlice(u.Object, "metadata", "managedFields")
- if !found || err != nil {
- return nil
- }
- managedFields := []metav1.ManagedFieldsEntry{}
- for _, item := range items {
- m, ok := item.(map[string]interface{})
- if !ok {
- utilruntime.HandleError(fmt.Errorf("unable to retrieve managedFields for object, item %v is not a map", item))
- return nil
- }
- out := metav1.ManagedFieldsEntry{}
- if err := runtime.DefaultUnstructuredConverter.FromUnstructured(m, &out); err != nil {
- utilruntime.HandleError(fmt.Errorf("unable to retrieve managedFields for object: %v", err))
- return nil
- }
- managedFields = append(managedFields, out)
- }
- return managedFields
-}
-
-func (u *Unstructured) SetManagedFields(managedFields []metav1.ManagedFieldsEntry) {
- if managedFields == nil {
- RemoveNestedField(u.Object, "metadata", "managedFields")
- return
- }
- items := []interface{}{}
- for _, managedFieldsEntry := range managedFields {
- out, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&managedFieldsEntry)
- if err != nil {
- utilruntime.HandleError(fmt.Errorf("unable to set managedFields for object: %v", err))
- return
- }
- items = append(items, out)
- }
- u.setNestedSlice(items, "metadata", "managedFields")
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go
deleted file mode 100644
index 5028f5fb5..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package unstructured
-
-import (
- "bytes"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-var _ runtime.Unstructured = &UnstructuredList{}
-var _ metav1.ListInterface = &UnstructuredList{}
-
-// UnstructuredList allows lists that do not have Golang structs
-// registered to be manipulated generically. This can be used to deal
-// with the API lists from a plug-in.
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-// +k8s:deepcopy-gen=true
-type UnstructuredList struct {
- Object map[string]interface{}
-
- // Items is a list of unstructured objects.
- Items []Unstructured `json:"items"`
-}
-
-func (u *UnstructuredList) GetObjectKind() schema.ObjectKind { return u }
-
-func (u *UnstructuredList) IsList() bool { return true }
-
-func (u *UnstructuredList) EachListItem(fn func(runtime.Object) error) error {
- for i := range u.Items {
- if err := fn(&u.Items[i]); err != nil {
- return err
- }
- }
- return nil
-}
-
-// NewEmptyInstance returns a new instance of the concrete type containing only kind/apiVersion and no other data.
-// This should be called instead of reflect.New() for unstructured types because the go type alone does not preserve kind/apiVersion info.
-func (u *UnstructuredList) NewEmptyInstance() runtime.Unstructured {
- out := new(UnstructuredList)
- if u != nil {
- out.SetGroupVersionKind(u.GroupVersionKind())
- }
- return out
-}
-
-// UnstructuredContent returns a map contain an overlay of the Items field onto
-// the Object field. Items always overwrites overlay.
-func (u *UnstructuredList) UnstructuredContent() map[string]interface{} {
- out := make(map[string]interface{}, len(u.Object)+1)
-
- // shallow copy every property
- for k, v := range u.Object {
- out[k] = v
- }
-
- items := make([]interface{}, len(u.Items))
- for i, item := range u.Items {
- items[i] = item.UnstructuredContent()
- }
- out["items"] = items
- return out
-}
-
-// SetUnstructuredContent obeys the conventions of List and keeps Items and the items
-// array in sync. If items is not an array of objects in the incoming map, then any
-// mismatched item will be removed.
-func (obj *UnstructuredList) SetUnstructuredContent(content map[string]interface{}) {
- obj.Object = content
- if content == nil {
- obj.Items = nil
- return
- }
- items, ok := obj.Object["items"].([]interface{})
- if !ok || items == nil {
- items = []interface{}{}
- }
- unstructuredItems := make([]Unstructured, 0, len(items))
- newItems := make([]interface{}, 0, len(items))
- for _, item := range items {
- o, ok := item.(map[string]interface{})
- if !ok {
- continue
- }
- unstructuredItems = append(unstructuredItems, Unstructured{Object: o})
- newItems = append(newItems, o)
- }
- obj.Items = unstructuredItems
- obj.Object["items"] = newItems
-}
-
-func (u *UnstructuredList) DeepCopy() *UnstructuredList {
- if u == nil {
- return nil
- }
- out := new(UnstructuredList)
- *out = *u
- out.Object = runtime.DeepCopyJSON(u.Object)
- out.Items = make([]Unstructured, len(u.Items))
- for i := range u.Items {
- u.Items[i].DeepCopyInto(&out.Items[i])
- }
- return out
-}
-
-// MarshalJSON ensures that the unstructured list object produces proper
-// JSON when passed to Go's standard JSON library.
-func (u *UnstructuredList) MarshalJSON() ([]byte, error) {
- var buf bytes.Buffer
- err := UnstructuredJSONScheme.Encode(u, &buf)
- return buf.Bytes(), err
-}
-
-// UnmarshalJSON ensures that the unstructured list object properly
-// decodes JSON when passed to Go's standard JSON library.
-func (u *UnstructuredList) UnmarshalJSON(b []byte) error {
- _, _, err := UnstructuredJSONScheme.Decode(b, nil, u)
- return err
-}
-
-func (u *UnstructuredList) GetAPIVersion() string {
- return getNestedString(u.Object, "apiVersion")
-}
-
-func (u *UnstructuredList) SetAPIVersion(version string) {
- u.setNestedField(version, "apiVersion")
-}
-
-func (u *UnstructuredList) GetKind() string {
- return getNestedString(u.Object, "kind")
-}
-
-func (u *UnstructuredList) SetKind(kind string) {
- u.setNestedField(kind, "kind")
-}
-
-func (u *UnstructuredList) GetResourceVersion() string {
- return getNestedString(u.Object, "metadata", "resourceVersion")
-}
-
-func (u *UnstructuredList) SetResourceVersion(version string) {
- u.setNestedField(version, "metadata", "resourceVersion")
-}
-
-func (u *UnstructuredList) GetSelfLink() string {
- return getNestedString(u.Object, "metadata", "selfLink")
-}
-
-func (u *UnstructuredList) SetSelfLink(selfLink string) {
- u.setNestedField(selfLink, "metadata", "selfLink")
-}
-
-func (u *UnstructuredList) GetContinue() string {
- return getNestedString(u.Object, "metadata", "continue")
-}
-
-func (u *UnstructuredList) SetContinue(c string) {
- u.setNestedField(c, "metadata", "continue")
-}
-
-func (u *UnstructuredList) GetRemainingItemCount() *int64 {
- return getNestedInt64Pointer(u.Object, "metadata", "remainingItemCount")
-}
-
-func (u *UnstructuredList) SetRemainingItemCount(c *int64) {
- if c == nil {
- RemoveNestedField(u.Object, "metadata", "remainingItemCount")
- } else {
- u.setNestedField(*c, "metadata", "remainingItemCount")
- }
-}
-
-func (u *UnstructuredList) SetGroupVersionKind(gvk schema.GroupVersionKind) {
- u.SetAPIVersion(gvk.GroupVersion().String())
- u.SetKind(gvk.Kind)
-}
-
-func (u *UnstructuredList) GroupVersionKind() schema.GroupVersionKind {
- gv, err := schema.ParseGroupVersion(u.GetAPIVersion())
- if err != nil {
- return schema.GroupVersionKind{}
- }
- gvk := gv.WithKind(u.GetKind())
- return gvk
-}
-
-func (u *UnstructuredList) setNestedField(value interface{}, fields ...string) {
- if u.Object == nil {
- u.Object = make(map[string]interface{})
- }
- SetNestedField(u.Object, value, fields...)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/zz_generated.deepcopy.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/zz_generated.deepcopy.go
deleted file mode 100644
index 9a9f25e8f..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/zz_generated.deepcopy.go
+++ /dev/null
@@ -1,55 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Code generated by deepcopy-gen. DO NOT EDIT.
-
-package unstructured
-
-import (
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *Unstructured) DeepCopyInto(out *Unstructured) {
- clone := in.DeepCopy()
- *out = *clone
- return
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *Unstructured) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- }
- return nil
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *UnstructuredList) DeepCopyInto(out *UnstructuredList) {
- clone := in.DeepCopy()
- *out = *clone
- return
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *UnstructuredList) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- }
- return nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go
deleted file mode 100644
index e55ab94d1..000000000
--- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go
+++ /dev/null
@@ -1,322 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package serializer
-
-import (
- "mime"
- "strings"
-
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/runtime/serializer/json"
- "k8s.io/apimachinery/pkg/runtime/serializer/protobuf"
- "k8s.io/apimachinery/pkg/runtime/serializer/recognizer"
- "k8s.io/apimachinery/pkg/runtime/serializer/versioning"
-)
-
-// serializerExtensions are for serializers that are conditionally compiled in
-var serializerExtensions = []func(*runtime.Scheme) (serializerType, bool){}
-
-type serializerType struct {
- AcceptContentTypes []string
- ContentType string
- FileExtensions []string
- // EncodesAsText should be true if this content type can be represented safely in UTF-8
- EncodesAsText bool
-
- Serializer runtime.Serializer
- PrettySerializer runtime.Serializer
-
- AcceptStreamContentTypes []string
- StreamContentType string
-
- Framer runtime.Framer
- StreamSerializer runtime.Serializer
-}
-
-func newSerializersForScheme(scheme *runtime.Scheme, mf json.MetaFactory, options CodecFactoryOptions) []serializerType {
- jsonSerializer := json.NewSerializerWithOptions(
- mf, scheme, scheme,
- json.SerializerOptions{Yaml: false, Pretty: false, Strict: options.Strict},
- )
- jsonSerializerType := serializerType{
- AcceptContentTypes: []string{runtime.ContentTypeJSON},
- ContentType: runtime.ContentTypeJSON,
- FileExtensions: []string{"json"},
- EncodesAsText: true,
- Serializer: jsonSerializer,
-
- Framer: json.Framer,
- StreamSerializer: jsonSerializer,
- }
- if options.Pretty {
- jsonSerializerType.PrettySerializer = json.NewSerializerWithOptions(
- mf, scheme, scheme,
- json.SerializerOptions{Yaml: false, Pretty: true, Strict: options.Strict},
- )
- }
-
- yamlSerializer := json.NewSerializerWithOptions(
- mf, scheme, scheme,
- json.SerializerOptions{Yaml: true, Pretty: false, Strict: options.Strict},
- )
- protoSerializer := protobuf.NewSerializer(scheme, scheme)
- protoRawSerializer := protobuf.NewRawSerializer(scheme, scheme)
-
- serializers := []serializerType{
- jsonSerializerType,
- {
- AcceptContentTypes: []string{runtime.ContentTypeYAML},
- ContentType: runtime.ContentTypeYAML,
- FileExtensions: []string{"yaml"},
- EncodesAsText: true,
- Serializer: yamlSerializer,
- },
- {
- AcceptContentTypes: []string{runtime.ContentTypeProtobuf},
- ContentType: runtime.ContentTypeProtobuf,
- FileExtensions: []string{"pb"},
- Serializer: protoSerializer,
-
- Framer: protobuf.LengthDelimitedFramer,
- StreamSerializer: protoRawSerializer,
- },
- }
-
- for _, fn := range serializerExtensions {
- if serializer, ok := fn(scheme); ok {
- serializers = append(serializers, serializer)
- }
- }
- return serializers
-}
-
-// CodecFactory provides methods for retrieving codecs and serializers for specific
-// versions and content types.
-type CodecFactory struct {
- scheme *runtime.Scheme
- universal runtime.Decoder
- accepts []runtime.SerializerInfo
-
- legacySerializer runtime.Serializer
-}
-
-// CodecFactoryOptions holds the options for configuring CodecFactory behavior
-type CodecFactoryOptions struct {
- // Strict configures all serializers in strict mode
- Strict bool
- // Pretty includes a pretty serializer along with the non-pretty one
- Pretty bool
-}
-
-// CodecFactoryOptionsMutator takes a pointer to an options struct and then modifies it.
-// Functions implementing this type can be passed to the NewCodecFactory() constructor.
-type CodecFactoryOptionsMutator func(*CodecFactoryOptions)
-
-// EnablePretty enables including a pretty serializer along with the non-pretty one
-func EnablePretty(options *CodecFactoryOptions) {
- options.Pretty = true
-}
-
-// DisablePretty disables including a pretty serializer along with the non-pretty one
-func DisablePretty(options *CodecFactoryOptions) {
- options.Pretty = false
-}
-
-// EnableStrict enables configuring all serializers in strict mode
-func EnableStrict(options *CodecFactoryOptions) {
- options.Strict = true
-}
-
-// DisableStrict disables configuring all serializers in strict mode
-func DisableStrict(options *CodecFactoryOptions) {
- options.Strict = false
-}
-
-// NewCodecFactory provides methods for retrieving serializers for the supported wire formats
-// and conversion wrappers to define preferred internal and external versions. In the future,
-// as the internal version is used less, callers may instead use a defaulting serializer and
-// only convert objects which are shared internally (Status, common API machinery).
-//
-// Mutators can be passed to change the CodecFactoryOptions before construction of the factory.
-// It is recommended to explicitly pass mutators instead of relying on defaults.
-// By default, Pretty is enabled -- this is conformant with previously supported behavior.
-//
-// TODO: allow other codecs to be compiled in?
-// TODO: accept a scheme interface
-func NewCodecFactory(scheme *runtime.Scheme, mutators ...CodecFactoryOptionsMutator) CodecFactory {
- options := CodecFactoryOptions{Pretty: true}
- for _, fn := range mutators {
- fn(&options)
- }
-
- serializers := newSerializersForScheme(scheme, json.DefaultMetaFactory, options)
- return newCodecFactory(scheme, serializers)
-}
-
-// newCodecFactory is a helper for testing that allows a different metafactory to be specified.
-func newCodecFactory(scheme *runtime.Scheme, serializers []serializerType) CodecFactory {
- decoders := make([]runtime.Decoder, 0, len(serializers))
- var accepts []runtime.SerializerInfo
- alreadyAccepted := make(map[string]struct{})
-
- var legacySerializer runtime.Serializer
- for _, d := range serializers {
- decoders = append(decoders, d.Serializer)
- for _, mediaType := range d.AcceptContentTypes {
- if _, ok := alreadyAccepted[mediaType]; ok {
- continue
- }
- alreadyAccepted[mediaType] = struct{}{}
- info := runtime.SerializerInfo{
- MediaType: d.ContentType,
- EncodesAsText: d.EncodesAsText,
- Serializer: d.Serializer,
- PrettySerializer: d.PrettySerializer,
- }
-
- mediaType, _, err := mime.ParseMediaType(info.MediaType)
- if err != nil {
- panic(err)
- }
- parts := strings.SplitN(mediaType, "/", 2)
- info.MediaTypeType = parts[0]
- info.MediaTypeSubType = parts[1]
-
- if d.StreamSerializer != nil {
- info.StreamSerializer = &runtime.StreamSerializerInfo{
- Serializer: d.StreamSerializer,
- EncodesAsText: d.EncodesAsText,
- Framer: d.Framer,
- }
- }
- accepts = append(accepts, info)
- if mediaType == runtime.ContentTypeJSON {
- legacySerializer = d.Serializer
- }
- }
- }
- if legacySerializer == nil {
- legacySerializer = serializers[0].Serializer
- }
-
- return CodecFactory{
- scheme: scheme,
- universal: recognizer.NewDecoder(decoders...),
-
- accepts: accepts,
-
- legacySerializer: legacySerializer,
- }
-}
-
-// WithoutConversion returns a NegotiatedSerializer that performs no conversion, even if the
-// caller requests it.
-func (f CodecFactory) WithoutConversion() runtime.NegotiatedSerializer {
- return WithoutConversionCodecFactory{f}
-}
-
-// SupportedMediaTypes returns the RFC2046 media types that this factory has serializers for.
-func (f CodecFactory) SupportedMediaTypes() []runtime.SerializerInfo {
- return f.accepts
-}
-
-// LegacyCodec encodes output to a given API versions, and decodes output into the internal form from
-// any recognized source. The returned codec will always encode output to JSON. If a type is not
-// found in the list of versions an error will be returned.
-//
-// This method is deprecated - clients and servers should negotiate a serializer by mime-type and
-// invoke CodecForVersions. Callers that need only to read data should use UniversalDecoder().
-//
-// TODO: make this call exist only in pkg/api, and initialize it with the set of default versions.
-// All other callers will be forced to request a Codec directly.
-func (f CodecFactory) LegacyCodec(version ...schema.GroupVersion) runtime.Codec {
- return versioning.NewDefaultingCodecForScheme(f.scheme, f.legacySerializer, f.universal, schema.GroupVersions(version), runtime.InternalGroupVersioner)
-}
-
-// UniversalDeserializer can convert any stored data recognized by this factory into a Go object that satisfies
-// runtime.Object. It does not perform conversion. It does not perform defaulting.
-func (f CodecFactory) UniversalDeserializer() runtime.Decoder {
- return f.universal
-}
-
-// UniversalDecoder returns a runtime.Decoder capable of decoding all known API objects in all known formats. Used
-// by clients that do not need to encode objects but want to deserialize API objects stored on disk. Only decodes
-// objects in groups registered with the scheme. The GroupVersions passed may be used to select alternate
-// versions of objects to return - by default, runtime.APIVersionInternal is used. If any versions are specified,
-// unrecognized groups will be returned in the version they are encoded as (no conversion). This decoder performs
-// defaulting.
-//
-// TODO: the decoder will eventually be removed in favor of dealing with objects in their versioned form
-// TODO: only accept a group versioner
-func (f CodecFactory) UniversalDecoder(versions ...schema.GroupVersion) runtime.Decoder {
- var versioner runtime.GroupVersioner
- if len(versions) == 0 {
- versioner = runtime.InternalGroupVersioner
- } else {
- versioner = schema.GroupVersions(versions)
- }
- return f.CodecForVersions(nil, f.universal, nil, versioner)
-}
-
-// CodecForVersions creates a codec with the provided serializer. If an object is decoded and its group is not in the list,
-// it will default to runtime.APIVersionInternal. If encode is not specified for an object's group, the object is not
-// converted. If encode or decode are nil, no conversion is performed.
-func (f CodecFactory) CodecForVersions(encoder runtime.Encoder, decoder runtime.Decoder, encode runtime.GroupVersioner, decode runtime.GroupVersioner) runtime.Codec {
- // TODO: these are for backcompat, remove them in the future
- if encode == nil {
- encode = runtime.DisabledGroupVersioner
- }
- if decode == nil {
- decode = runtime.InternalGroupVersioner
- }
- return versioning.NewDefaultingCodecForScheme(f.scheme, encoder, decoder, encode, decode)
-}
-
-// DecoderToVersion returns a decoder that targets the provided group version.
-func (f CodecFactory) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {
- return f.CodecForVersions(nil, decoder, nil, gv)
-}
-
-// EncoderForVersion returns an encoder that targets the provided group version.
-func (f CodecFactory) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {
- return f.CodecForVersions(encoder, nil, gv, nil)
-}
-
-// WithoutConversionCodecFactory is a CodecFactory that will explicitly ignore requests to perform conversion.
-// This wrapper is used while code migrates away from using conversion (such as external clients) and in the future
-// will be unnecessary when we change the signature of NegotiatedSerializer.
-type WithoutConversionCodecFactory struct {
- CodecFactory
-}
-
-// EncoderForVersion returns an encoder that does not do conversion, but does set the group version kind of the object
-// when serialized.
-func (f WithoutConversionCodecFactory) EncoderForVersion(serializer runtime.Encoder, version runtime.GroupVersioner) runtime.Encoder {
- return runtime.WithVersionEncoder{
- Version: version,
- Encoder: serializer,
- ObjectTyper: f.CodecFactory.scheme,
- }
-}
-
-// DecoderToVersion returns an decoder that does not do conversion.
-func (f WithoutConversionCodecFactory) DecoderToVersion(serializer runtime.Decoder, _ runtime.GroupVersioner) runtime.Decoder {
- return runtime.WithoutVersionDecoder{
- Decoder: serializer,
- }
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go
deleted file mode 100644
index 83b2e1393..000000000
--- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go
+++ /dev/null
@@ -1,389 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package json
-
-import (
- "encoding/json"
- "io"
- "strconv"
- "unsafe"
-
- jsoniter "github.com/json-iterator/go"
- "github.com/modern-go/reflect2"
- "sigs.k8s.io/yaml"
-
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/runtime/serializer/recognizer"
- "k8s.io/apimachinery/pkg/util/framer"
- utilyaml "k8s.io/apimachinery/pkg/util/yaml"
- "k8s.io/klog/v2"
-)
-
-// NewSerializer creates a JSON serializer that handles encoding versioned objects into the proper JSON form. If typer
-// is not nil, the object has the group, version, and kind fields set.
-// Deprecated: use NewSerializerWithOptions instead.
-func NewSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, pretty bool) *Serializer {
- return NewSerializerWithOptions(meta, creater, typer, SerializerOptions{false, pretty, false})
-}
-
-// NewYAMLSerializer creates a YAML serializer that handles encoding versioned objects into the proper YAML form. If typer
-// is not nil, the object has the group, version, and kind fields set. This serializer supports only the subset of YAML that
-// matches JSON, and will error if constructs are used that do not serialize to JSON.
-// Deprecated: use NewSerializerWithOptions instead.
-func NewYAMLSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper) *Serializer {
- return NewSerializerWithOptions(meta, creater, typer, SerializerOptions{true, false, false})
-}
-
-// NewSerializerWithOptions creates a JSON/YAML serializer that handles encoding versioned objects into the proper JSON/YAML
-// form. If typer is not nil, the object has the group, version, and kind fields set. Options are copied into the Serializer
-// and are immutable.
-func NewSerializerWithOptions(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, options SerializerOptions) *Serializer {
- return &Serializer{
- meta: meta,
- creater: creater,
- typer: typer,
- options: options,
- identifier: identifier(options),
- }
-}
-
-// identifier computes Identifier of Encoder based on the given options.
-func identifier(options SerializerOptions) runtime.Identifier {
- result := map[string]string{
- "name": "json",
- "yaml": strconv.FormatBool(options.Yaml),
- "pretty": strconv.FormatBool(options.Pretty),
- }
- identifier, err := json.Marshal(result)
- if err != nil {
- klog.Fatalf("Failed marshaling identifier for json Serializer: %v", err)
- }
- return runtime.Identifier(identifier)
-}
-
-// SerializerOptions holds the options which are used to configure a JSON/YAML serializer.
-// example:
-// (1) To configure a JSON serializer, set `Yaml` to `false`.
-// (2) To configure a YAML serializer, set `Yaml` to `true`.
-// (3) To configure a strict serializer that can return strictDecodingError, set `Strict` to `true`.
-type SerializerOptions struct {
- // Yaml: configures the Serializer to work with JSON(false) or YAML(true).
- // When `Yaml` is enabled, this serializer only supports the subset of YAML that
- // matches JSON, and will error if constructs are used that do not serialize to JSON.
- Yaml bool
-
- // Pretty: configures a JSON enabled Serializer(`Yaml: false`) to produce human-readable output.
- // This option is silently ignored when `Yaml` is `true`.
- Pretty bool
-
- // Strict: configures the Serializer to return strictDecodingError's when duplicate fields are present decoding JSON or YAML.
- // Note that enabling this option is not as performant as the non-strict variant, and should not be used in fast paths.
- Strict bool
-}
-
-// Serializer handles encoding versioned objects into the proper JSON form
-type Serializer struct {
- meta MetaFactory
- options SerializerOptions
- creater runtime.ObjectCreater
- typer runtime.ObjectTyper
-
- identifier runtime.Identifier
-}
-
-// Serializer implements Serializer
-var _ runtime.Serializer = &Serializer{}
-var _ recognizer.RecognizingDecoder = &Serializer{}
-
-type customNumberExtension struct {
- jsoniter.DummyExtension
-}
-
-func (cne *customNumberExtension) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {
- if typ.String() == "interface {}" {
- return customNumberDecoder{}
- }
- return nil
-}
-
-type customNumberDecoder struct {
-}
-
-func (customNumberDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
- switch iter.WhatIsNext() {
- case jsoniter.NumberValue:
- var number jsoniter.Number
- iter.ReadVal(&number)
- i64, err := strconv.ParseInt(string(number), 10, 64)
- if err == nil {
- *(*interface{})(ptr) = i64
- return
- }
- f64, err := strconv.ParseFloat(string(number), 64)
- if err == nil {
- *(*interface{})(ptr) = f64
- return
- }
- iter.ReportError("DecodeNumber", err.Error())
- default:
- *(*interface{})(ptr) = iter.Read()
- }
-}
-
-// CaseSensitiveJSONIterator returns a jsoniterator API that's configured to be
-// case-sensitive when unmarshalling, and otherwise compatible with
-// the encoding/json standard library.
-func CaseSensitiveJSONIterator() jsoniter.API {
- config := jsoniter.Config{
- EscapeHTML: true,
- SortMapKeys: true,
- ValidateJsonRawMessage: true,
- CaseSensitive: true,
- }.Froze()
- // Force jsoniter to decode number to interface{} via int64/float64, if possible.
- config.RegisterExtension(&customNumberExtension{})
- return config
-}
-
-// StrictCaseSensitiveJSONIterator returns a jsoniterator API that's configured to be
-// case-sensitive, but also disallows unknown fields when unmarshalling. It is compatible with
-// the encoding/json standard library.
-func StrictCaseSensitiveJSONIterator() jsoniter.API {
- config := jsoniter.Config{
- EscapeHTML: true,
- SortMapKeys: true,
- ValidateJsonRawMessage: true,
- CaseSensitive: true,
- DisallowUnknownFields: true,
- }.Froze()
- // Force jsoniter to decode number to interface{} via int64/float64, if possible.
- config.RegisterExtension(&customNumberExtension{})
- return config
-}
-
-// Private copies of jsoniter to try to shield against possible mutations
-// from outside. Still does not protect from package level jsoniter.Register*() functions - someone calling them
-// in some other library will mess with every usage of the jsoniter library in the whole program.
-// See https://github.com/json-iterator/go/issues/265
-var caseSensitiveJSONIterator = CaseSensitiveJSONIterator()
-var strictCaseSensitiveJSONIterator = StrictCaseSensitiveJSONIterator()
-
-// gvkWithDefaults returns group kind and version defaulting from provided default
-func gvkWithDefaults(actual, defaultGVK schema.GroupVersionKind) schema.GroupVersionKind {
- if len(actual.Kind) == 0 {
- actual.Kind = defaultGVK.Kind
- }
- if len(actual.Version) == 0 && len(actual.Group) == 0 {
- actual.Group = defaultGVK.Group
- actual.Version = defaultGVK.Version
- }
- if len(actual.Version) == 0 && actual.Group == defaultGVK.Group {
- actual.Version = defaultGVK.Version
- }
- return actual
-}
-
-// Decode attempts to convert the provided data into YAML or JSON, extract the stored schema kind, apply the provided default gvk, and then
-// load that data into an object matching the desired schema kind or the provided into.
-// If into is *runtime.Unknown, the raw data will be extracted and no decoding will be performed.
-// If into is not registered with the typer, then the object will be straight decoded using normal JSON/YAML unmarshalling.
-// If into is provided and the original data is not fully qualified with kind/version/group, the type of the into will be used to alter the returned gvk.
-// If into is nil or data's gvk different from into's gvk, it will generate a new Object with ObjectCreater.New(gvk)
-// On success or most errors, the method will return the calculated schema kind.
-// The gvk calculate priority will be originalData > default gvk > into
-func (s *Serializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
- data := originalData
- if s.options.Yaml {
- altered, err := yaml.YAMLToJSON(data)
- if err != nil {
- return nil, nil, err
- }
- data = altered
- }
-
- actual, err := s.meta.Interpret(data)
- if err != nil {
- return nil, nil, err
- }
-
- if gvk != nil {
- *actual = gvkWithDefaults(*actual, *gvk)
- }
-
- if unk, ok := into.(*runtime.Unknown); ok && unk != nil {
- unk.Raw = originalData
- unk.ContentType = runtime.ContentTypeJSON
- unk.GetObjectKind().SetGroupVersionKind(*actual)
- return unk, actual, nil
- }
-
- if into != nil {
- _, isUnstructured := into.(runtime.Unstructured)
- types, _, err := s.typer.ObjectKinds(into)
- switch {
- case runtime.IsNotRegisteredError(err), isUnstructured:
- if err := caseSensitiveJSONIterator.Unmarshal(data, into); err != nil {
- return nil, actual, err
- }
- return into, actual, nil
- case err != nil:
- return nil, actual, err
- default:
- *actual = gvkWithDefaults(*actual, types[0])
- }
- }
-
- if len(actual.Kind) == 0 {
- return nil, actual, runtime.NewMissingKindErr(string(originalData))
- }
- if len(actual.Version) == 0 {
- return nil, actual, runtime.NewMissingVersionErr(string(originalData))
- }
-
- // use the target if necessary
- obj, err := runtime.UseOrCreateObject(s.typer, s.creater, *actual, into)
- if err != nil {
- return nil, actual, err
- }
-
- if err := caseSensitiveJSONIterator.Unmarshal(data, obj); err != nil {
- return nil, actual, err
- }
-
- // If the deserializer is non-strict, return successfully here.
- if !s.options.Strict {
- return obj, actual, nil
- }
-
- // In strict mode pass the data trough the YAMLToJSONStrict converter.
- // This is done to catch duplicate fields regardless of encoding (JSON or YAML). For JSON data,
- // the output would equal the input, unless there is a parsing error such as duplicate fields.
- // As we know this was successful in the non-strict case, the only error that may be returned here
- // is because of the newly-added strictness. hence we know we can return the typed strictDecoderError
- // the actual error is that the object contains duplicate fields.
- altered, err := yaml.YAMLToJSONStrict(originalData)
- if err != nil {
- return nil, actual, runtime.NewStrictDecodingError(err.Error(), string(originalData))
- }
- // As performance is not an issue for now for the strict deserializer (one has regardless to do
- // the unmarshal twice), we take the sanitized, altered data that is guaranteed to have no duplicated
- // fields, and unmarshal this into a copy of the already-populated obj. Any error that occurs here is
- // due to that a matching field doesn't exist in the object. hence we can return a typed strictDecoderError,
- // the actual error is that the object contains unknown field.
- strictObj := obj.DeepCopyObject()
- if err := strictCaseSensitiveJSONIterator.Unmarshal(altered, strictObj); err != nil {
- return nil, actual, runtime.NewStrictDecodingError(err.Error(), string(originalData))
- }
- // Always return the same object as the non-strict serializer to avoid any deviations.
- return obj, actual, nil
-}
-
-// Encode serializes the provided object to the given writer.
-func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error {
- if co, ok := obj.(runtime.CacheableObject); ok {
- return co.CacheEncode(s.Identifier(), s.doEncode, w)
- }
- return s.doEncode(obj, w)
-}
-
-func (s *Serializer) doEncode(obj runtime.Object, w io.Writer) error {
- if s.options.Yaml {
- json, err := caseSensitiveJSONIterator.Marshal(obj)
- if err != nil {
- return err
- }
- data, err := yaml.JSONToYAML(json)
- if err != nil {
- return err
- }
- _, err = w.Write(data)
- return err
- }
-
- if s.options.Pretty {
- data, err := caseSensitiveJSONIterator.MarshalIndent(obj, "", " ")
- if err != nil {
- return err
- }
- _, err = w.Write(data)
- return err
- }
- encoder := json.NewEncoder(w)
- return encoder.Encode(obj)
-}
-
-// Identifier implements runtime.Encoder interface.
-func (s *Serializer) Identifier() runtime.Identifier {
- return s.identifier
-}
-
-// RecognizesData implements the RecognizingDecoder interface.
-func (s *Serializer) RecognizesData(peek io.Reader) (ok, unknown bool, err error) {
- if s.options.Yaml {
- // we could potentially look for '---'
- return false, true, nil
- }
- _, _, ok = utilyaml.GuessJSONStream(peek, 2048)
- return ok, false, nil
-}
-
-// Framer is the default JSON framing behavior, with newlines delimiting individual objects.
-var Framer = jsonFramer{}
-
-type jsonFramer struct{}
-
-// NewFrameWriter implements stream framing for this serializer
-func (jsonFramer) NewFrameWriter(w io.Writer) io.Writer {
- // we can write JSON objects directly to the writer, because they are self-framing
- return w
-}
-
-// NewFrameReader implements stream framing for this serializer
-func (jsonFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
- // we need to extract the JSON chunks of data to pass to Decode()
- return framer.NewJSONFramedReader(r)
-}
-
-// YAMLFramer is the default JSON framing behavior, with newlines delimiting individual objects.
-var YAMLFramer = yamlFramer{}
-
-type yamlFramer struct{}
-
-// NewFrameWriter implements stream framing for this serializer
-func (yamlFramer) NewFrameWriter(w io.Writer) io.Writer {
- return yamlFrameWriter{w}
-}
-
-// NewFrameReader implements stream framing for this serializer
-func (yamlFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
- // extract the YAML document chunks directly
- return utilyaml.NewDocumentDecoder(r)
-}
-
-type yamlFrameWriter struct {
- w io.Writer
-}
-
-// Write separates each document with the YAML document separator (`---` followed by line
-// break). Writers must write well formed YAML documents (include a final line break).
-func (w yamlFrameWriter) Write(data []byte) (n int, err error) {
- if _, err := w.w.Write([]byte("---\n")); err != nil {
- return 0, err
- }
- return w.w.Write(data)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/meta.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/meta.go
deleted file mode 100644
index df3f5f989..000000000
--- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/meta.go
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package json
-
-import (
- "encoding/json"
- "fmt"
-
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// MetaFactory is used to store and retrieve the version and kind
-// information for JSON objects in a serializer.
-type MetaFactory interface {
- // Interpret should return the version and kind of the wire-format of
- // the object.
- Interpret(data []byte) (*schema.GroupVersionKind, error)
-}
-
-// DefaultMetaFactory is a default factory for versioning objects in JSON. The object
-// in memory and in the default JSON serialization will use the "kind" and "apiVersion"
-// fields.
-var DefaultMetaFactory = SimpleMetaFactory{}
-
-// SimpleMetaFactory provides default methods for retrieving the type and version of objects
-// that are identified with an "apiVersion" and "kind" fields in their JSON
-// serialization. It may be parameterized with the names of the fields in memory, or an
-// optional list of base structs to search for those fields in memory.
-type SimpleMetaFactory struct {
-}
-
-// Interpret will return the APIVersion and Kind of the JSON wire-format
-// encoding of an object, or an error.
-func (SimpleMetaFactory) Interpret(data []byte) (*schema.GroupVersionKind, error) {
- findKind := struct {
- // +optional
- APIVersion string `json:"apiVersion,omitempty"`
- // +optional
- Kind string `json:"kind,omitempty"`
- }{}
- if err := json.Unmarshal(data, &findKind); err != nil {
- return nil, fmt.Errorf("couldn't get version/kind; json parse error: %v", err)
- }
- gv, err := schema.ParseGroupVersion(findKind.APIVersion)
- if err != nil {
- return nil, err
- }
- return &schema.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: findKind.Kind}, nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/negotiated_codec.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/negotiated_codec.go
deleted file mode 100644
index a42b4a41a..000000000
--- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/negotiated_codec.go
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
-Copyright 2016 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package serializer
-
-import (
- "k8s.io/apimachinery/pkg/runtime"
-)
-
-// TODO: We should split negotiated serializers that we can change versions on from those we can change
-// serialization formats on
-type negotiatedSerializerWrapper struct {
- info runtime.SerializerInfo
-}
-
-func NegotiatedSerializerWrapper(info runtime.SerializerInfo) runtime.NegotiatedSerializer {
- return &negotiatedSerializerWrapper{info}
-}
-
-func (n *negotiatedSerializerWrapper) SupportedMediaTypes() []runtime.SerializerInfo {
- return []runtime.SerializerInfo{n.info}
-}
-
-func (n *negotiatedSerializerWrapper) EncoderForVersion(e runtime.Encoder, _ runtime.GroupVersioner) runtime.Encoder {
- return e
-}
-
-func (n *negotiatedSerializerWrapper) DecoderToVersion(d runtime.Decoder, _gv runtime.GroupVersioner) runtime.Decoder {
- return d
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/doc.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/doc.go
deleted file mode 100644
index 72d0ac79b..000000000
--- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/doc.go
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package protobuf provides a Kubernetes serializer for the protobuf format.
-package protobuf // import "k8s.io/apimachinery/pkg/runtime/serializer/protobuf"
diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go
deleted file mode 100644
index 404fb1b7e..000000000
--- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go
+++ /dev/null
@@ -1,476 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package protobuf
-
-import (
- "bytes"
- "fmt"
- "io"
- "net/http"
- "reflect"
-
- "github.com/gogo/protobuf/proto"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/runtime/serializer/recognizer"
- "k8s.io/apimachinery/pkg/util/framer"
-)
-
-var (
- // protoEncodingPrefix serves as a magic number for an encoded protobuf message on this serializer. All
- // proto messages serialized by this schema will be preceded by the bytes 0x6b 0x38 0x73, with the fourth
- // byte being reserved for the encoding style. The only encoding style defined is 0x00, which means that
- // the rest of the byte stream is a message of type k8s.io.kubernetes.pkg.runtime.Unknown (proto2).
- //
- // See k8s.io/apimachinery/pkg/runtime/generated.proto for details of the runtime.Unknown message.
- //
- // This encoding scheme is experimental, and is subject to change at any time.
- protoEncodingPrefix = []byte{0x6b, 0x38, 0x73, 0x00}
-)
-
-type errNotMarshalable struct {
- t reflect.Type
-}
-
-func (e errNotMarshalable) Error() string {
- return fmt.Sprintf("object %v does not implement the protobuf marshalling interface and cannot be encoded to a protobuf message", e.t)
-}
-
-func (e errNotMarshalable) Status() metav1.Status {
- return metav1.Status{
- Status: metav1.StatusFailure,
- Code: http.StatusNotAcceptable,
- Reason: metav1.StatusReason("NotAcceptable"),
- Message: e.Error(),
- }
-}
-
-// IsNotMarshalable checks the type of error, returns a boolean true if error is not nil and not marshalable false otherwise
-func IsNotMarshalable(err error) bool {
- _, ok := err.(errNotMarshalable)
- return err != nil && ok
-}
-
-// NewSerializer creates a Protobuf serializer that handles encoding versioned objects into the proper wire form. If a typer
-// is passed, the encoded object will have group, version, and kind fields set. If typer is nil, the objects will be written
-// as-is (any type info passed with the object will be used).
-func NewSerializer(creater runtime.ObjectCreater, typer runtime.ObjectTyper) *Serializer {
- return &Serializer{
- prefix: protoEncodingPrefix,
- creater: creater,
- typer: typer,
- }
-}
-
-// Serializer handles encoding versioned objects into the proper wire form
-type Serializer struct {
- prefix []byte
- creater runtime.ObjectCreater
- typer runtime.ObjectTyper
-}
-
-var _ runtime.Serializer = &Serializer{}
-var _ recognizer.RecognizingDecoder = &Serializer{}
-
-const serializerIdentifier runtime.Identifier = "protobuf"
-
-// Decode attempts to convert the provided data into a protobuf message, extract the stored schema kind, apply the provided default
-// gvk, and then load that data into an object matching the desired schema kind or the provided into. If into is *runtime.Unknown,
-// the raw data will be extracted and no decoding will be performed. If into is not registered with the typer, then the object will
-// be straight decoded using normal protobuf unmarshalling (the MarshalTo interface). If into is provided and the original data is
-// not fully qualified with kind/version/group, the type of the into will be used to alter the returned gvk. On success or most
-// errors, the method will return the calculated schema kind.
-func (s *Serializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
- prefixLen := len(s.prefix)
- switch {
- case len(originalData) == 0:
- // TODO: treat like decoding {} from JSON with defaulting
- return nil, nil, fmt.Errorf("empty data")
- case len(originalData) < prefixLen || !bytes.Equal(s.prefix, originalData[:prefixLen]):
- return nil, nil, fmt.Errorf("provided data does not appear to be a protobuf message, expected prefix %v", s.prefix)
- case len(originalData) == prefixLen:
- // TODO: treat like decoding {} from JSON with defaulting
- return nil, nil, fmt.Errorf("empty body")
- }
-
- data := originalData[prefixLen:]
- unk := runtime.Unknown{}
- if err := unk.Unmarshal(data); err != nil {
- return nil, nil, err
- }
-
- actual := unk.GroupVersionKind()
- copyKindDefaults(&actual, gvk)
-
- if intoUnknown, ok := into.(*runtime.Unknown); ok && intoUnknown != nil {
- *intoUnknown = unk
- if ok, _, _ := s.RecognizesData(bytes.NewBuffer(unk.Raw)); ok {
- intoUnknown.ContentType = runtime.ContentTypeProtobuf
- }
- return intoUnknown, &actual, nil
- }
-
- if into != nil {
- types, _, err := s.typer.ObjectKinds(into)
- switch {
- case runtime.IsNotRegisteredError(err):
- pb, ok := into.(proto.Message)
- if !ok {
- return nil, &actual, errNotMarshalable{reflect.TypeOf(into)}
- }
- if err := proto.Unmarshal(unk.Raw, pb); err != nil {
- return nil, &actual, err
- }
- return into, &actual, nil
- case err != nil:
- return nil, &actual, err
- default:
- copyKindDefaults(&actual, &types[0])
- // if the result of defaulting did not set a version or group, ensure that at least group is set
- // (copyKindDefaults will not assign Group if version is already set). This guarantees that the group
- // of into is set if there is no better information from the caller or object.
- if len(actual.Version) == 0 && len(actual.Group) == 0 {
- actual.Group = types[0].Group
- }
- }
- }
-
- if len(actual.Kind) == 0 {
- return nil, &actual, runtime.NewMissingKindErr(fmt.Sprintf("%#v", unk.TypeMeta))
- }
- if len(actual.Version) == 0 {
- return nil, &actual, runtime.NewMissingVersionErr(fmt.Sprintf("%#v", unk.TypeMeta))
- }
-
- return unmarshalToObject(s.typer, s.creater, &actual, into, unk.Raw)
-}
-
-// Encode serializes the provided object to the given writer.
-func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error {
- if co, ok := obj.(runtime.CacheableObject); ok {
- return co.CacheEncode(s.Identifier(), s.doEncode, w)
- }
- return s.doEncode(obj, w)
-}
-
-func (s *Serializer) doEncode(obj runtime.Object, w io.Writer) error {
- prefixSize := uint64(len(s.prefix))
-
- var unk runtime.Unknown
- switch t := obj.(type) {
- case *runtime.Unknown:
- estimatedSize := prefixSize + uint64(t.Size())
- data := make([]byte, estimatedSize)
- i, err := t.MarshalTo(data[prefixSize:])
- if err != nil {
- return err
- }
- copy(data, s.prefix)
- _, err = w.Write(data[:prefixSize+uint64(i)])
- return err
- default:
- kind := obj.GetObjectKind().GroupVersionKind()
- unk = runtime.Unknown{
- TypeMeta: runtime.TypeMeta{
- Kind: kind.Kind,
- APIVersion: kind.GroupVersion().String(),
- },
- }
- }
-
- switch t := obj.(type) {
- case bufferedMarshaller:
- // this path performs a single allocation during write but requires the caller to implement
- // the more efficient Size and MarshalToSizedBuffer methods
- encodedSize := uint64(t.Size())
- estimatedSize := prefixSize + estimateUnknownSize(&unk, encodedSize)
- data := make([]byte, estimatedSize)
-
- i, err := unk.NestedMarshalTo(data[prefixSize:], t, encodedSize)
- if err != nil {
- return err
- }
-
- copy(data, s.prefix)
-
- _, err = w.Write(data[:prefixSize+uint64(i)])
- return err
-
- case proto.Marshaler:
- // this path performs extra allocations
- data, err := t.Marshal()
- if err != nil {
- return err
- }
- unk.Raw = data
-
- estimatedSize := prefixSize + uint64(unk.Size())
- data = make([]byte, estimatedSize)
-
- i, err := unk.MarshalTo(data[prefixSize:])
- if err != nil {
- return err
- }
-
- copy(data, s.prefix)
-
- _, err = w.Write(data[:prefixSize+uint64(i)])
- return err
-
- default:
- // TODO: marshal with a different content type and serializer (JSON for third party objects)
- return errNotMarshalable{reflect.TypeOf(obj)}
- }
-}
-
-// Identifier implements runtime.Encoder interface.
-func (s *Serializer) Identifier() runtime.Identifier {
- return serializerIdentifier
-}
-
-// RecognizesData implements the RecognizingDecoder interface.
-func (s *Serializer) RecognizesData(peek io.Reader) (bool, bool, error) {
- prefix := make([]byte, 4)
- n, err := peek.Read(prefix)
- if err != nil {
- if err == io.EOF {
- return false, false, nil
- }
- return false, false, err
- }
- if n != 4 {
- return false, false, nil
- }
- return bytes.Equal(s.prefix, prefix), false, nil
-}
-
-// copyKindDefaults defaults dst to the value in src if dst does not have a value set.
-func copyKindDefaults(dst, src *schema.GroupVersionKind) {
- if src == nil {
- return
- }
- // apply kind and version defaulting from provided default
- if len(dst.Kind) == 0 {
- dst.Kind = src.Kind
- }
- if len(dst.Version) == 0 && len(src.Version) > 0 {
- dst.Group = src.Group
- dst.Version = src.Version
- }
-}
-
-// bufferedMarshaller describes a more efficient marshalling interface that can avoid allocating multiple
-// byte buffers by pre-calculating the size of the final buffer needed.
-type bufferedMarshaller interface {
- proto.Sizer
- runtime.ProtobufMarshaller
-}
-
-// Like bufferedMarshaller, but is able to marshal backwards, which is more efficient since it doesn't call Size() as frequently.
-type bufferedReverseMarshaller interface {
- proto.Sizer
- runtime.ProtobufReverseMarshaller
-}
-
-// estimateUnknownSize returns the expected bytes consumed by a given runtime.Unknown
-// object with a nil RawJSON struct and the expected size of the provided buffer. The
-// returned size will not be correct if RawJSOn is set on unk.
-func estimateUnknownSize(unk *runtime.Unknown, byteSize uint64) uint64 {
- size := uint64(unk.Size())
- // protobuf uses 1 byte for the tag, a varint for the length of the array (at most 8 bytes - uint64 - here),
- // and the size of the array.
- size += 1 + 8 + byteSize
- return size
-}
-
-// NewRawSerializer creates a Protobuf serializer that handles encoding versioned objects into the proper wire form. If typer
-// is not nil, the object has the group, version, and kind fields set. This serializer does not provide type information for the
-// encoded object, and thus is not self describing (callers must know what type is being described in order to decode).
-//
-// This encoding scheme is experimental, and is subject to change at any time.
-func NewRawSerializer(creater runtime.ObjectCreater, typer runtime.ObjectTyper) *RawSerializer {
- return &RawSerializer{
- creater: creater,
- typer: typer,
- }
-}
-
-// RawSerializer encodes and decodes objects without adding a runtime.Unknown wrapper (objects are encoded without identifying
-// type).
-type RawSerializer struct {
- creater runtime.ObjectCreater
- typer runtime.ObjectTyper
-}
-
-var _ runtime.Serializer = &RawSerializer{}
-
-const rawSerializerIdentifier runtime.Identifier = "raw-protobuf"
-
-// Decode attempts to convert the provided data into a protobuf message, extract the stored schema kind, apply the provided default
-// gvk, and then load that data into an object matching the desired schema kind or the provided into. If into is *runtime.Unknown,
-// the raw data will be extracted and no decoding will be performed. If into is not registered with the typer, then the object will
-// be straight decoded using normal protobuf unmarshalling (the MarshalTo interface). If into is provided and the original data is
-// not fully qualified with kind/version/group, the type of the into will be used to alter the returned gvk. On success or most
-// errors, the method will return the calculated schema kind.
-func (s *RawSerializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
- if into == nil {
- return nil, nil, fmt.Errorf("this serializer requires an object to decode into: %#v", s)
- }
-
- if len(originalData) == 0 {
- // TODO: treat like decoding {} from JSON with defaulting
- return nil, nil, fmt.Errorf("empty data")
- }
- data := originalData
-
- actual := &schema.GroupVersionKind{}
- copyKindDefaults(actual, gvk)
-
- if intoUnknown, ok := into.(*runtime.Unknown); ok && intoUnknown != nil {
- intoUnknown.Raw = data
- intoUnknown.ContentEncoding = ""
- intoUnknown.ContentType = runtime.ContentTypeProtobuf
- intoUnknown.SetGroupVersionKind(*actual)
- return intoUnknown, actual, nil
- }
-
- types, _, err := s.typer.ObjectKinds(into)
- switch {
- case runtime.IsNotRegisteredError(err):
- pb, ok := into.(proto.Message)
- if !ok {
- return nil, actual, errNotMarshalable{reflect.TypeOf(into)}
- }
- if err := proto.Unmarshal(data, pb); err != nil {
- return nil, actual, err
- }
- return into, actual, nil
- case err != nil:
- return nil, actual, err
- default:
- copyKindDefaults(actual, &types[0])
- // if the result of defaulting did not set a version or group, ensure that at least group is set
- // (copyKindDefaults will not assign Group if version is already set). This guarantees that the group
- // of into is set if there is no better information from the caller or object.
- if len(actual.Version) == 0 && len(actual.Group) == 0 {
- actual.Group = types[0].Group
- }
- }
-
- if len(actual.Kind) == 0 {
- return nil, actual, runtime.NewMissingKindErr("<protobuf encoded body - must provide default type>")
- }
- if len(actual.Version) == 0 {
- return nil, actual, runtime.NewMissingVersionErr("<protobuf encoded body - must provide default type>")
- }
-
- return unmarshalToObject(s.typer, s.creater, actual, into, data)
-}
-
-// unmarshalToObject is the common code between decode in the raw and normal serializer.
-func unmarshalToObject(typer runtime.ObjectTyper, creater runtime.ObjectCreater, actual *schema.GroupVersionKind, into runtime.Object, data []byte) (runtime.Object, *schema.GroupVersionKind, error) {
- // use the target if necessary
- obj, err := runtime.UseOrCreateObject(typer, creater, *actual, into)
- if err != nil {
- return nil, actual, err
- }
-
- pb, ok := obj.(proto.Message)
- if !ok {
- return nil, actual, errNotMarshalable{reflect.TypeOf(obj)}
- }
- if err := proto.Unmarshal(data, pb); err != nil {
- return nil, actual, err
- }
- if actual != nil {
- obj.GetObjectKind().SetGroupVersionKind(*actual)
- }
- return obj, actual, nil
-}
-
-// Encode serializes the provided object to the given writer. Overrides is ignored.
-func (s *RawSerializer) Encode(obj runtime.Object, w io.Writer) error {
- if co, ok := obj.(runtime.CacheableObject); ok {
- return co.CacheEncode(s.Identifier(), s.doEncode, w)
- }
- return s.doEncode(obj, w)
-}
-
-func (s *RawSerializer) doEncode(obj runtime.Object, w io.Writer) error {
- switch t := obj.(type) {
- case bufferedReverseMarshaller:
- // this path performs a single allocation during write but requires the caller to implement
- // the more efficient Size and MarshalToSizedBuffer methods
- encodedSize := uint64(t.Size())
- data := make([]byte, encodedSize)
-
- n, err := t.MarshalToSizedBuffer(data)
- if err != nil {
- return err
- }
- _, err = w.Write(data[:n])
- return err
-
- case bufferedMarshaller:
- // this path performs a single allocation during write but requires the caller to implement
- // the more efficient Size and MarshalTo methods
- encodedSize := uint64(t.Size())
- data := make([]byte, encodedSize)
-
- n, err := t.MarshalTo(data)
- if err != nil {
- return err
- }
- _, err = w.Write(data[:n])
- return err
-
- case proto.Marshaler:
- // this path performs extra allocations
- data, err := t.Marshal()
- if err != nil {
- return err
- }
- _, err = w.Write(data)
- return err
-
- default:
- return errNotMarshalable{reflect.TypeOf(obj)}
- }
-}
-
-// Identifier implements runtime.Encoder interface.
-func (s *RawSerializer) Identifier() runtime.Identifier {
- return rawSerializerIdentifier
-}
-
-// LengthDelimitedFramer is exported variable of type lengthDelimitedFramer
-var LengthDelimitedFramer = lengthDelimitedFramer{}
-
-// Provides length delimited frame reader and writer methods
-type lengthDelimitedFramer struct{}
-
-// NewFrameWriter implements stream framing for this serializer
-func (lengthDelimitedFramer) NewFrameWriter(w io.Writer) io.Writer {
- return framer.NewLengthDelimitedFrameWriter(w)
-}
-
-// NewFrameReader implements stream framing for this serializer
-func (lengthDelimitedFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
- return framer.NewLengthDelimitedFrameReader(r)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/recognizer.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/recognizer.go
deleted file mode 100644
index 38497ab53..000000000
--- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/recognizer.go
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package recognizer
-
-import (
- "bufio"
- "bytes"
- "fmt"
- "io"
-
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-type RecognizingDecoder interface {
- runtime.Decoder
- // RecognizesData should return true if the input provided in the provided reader
- // belongs to this decoder, or an error if the data could not be read or is ambiguous.
- // Unknown is true if the data could not be determined to match the decoder type.
- // Decoders should assume that they can read as much of peek as they need (as the caller
- // provides) and may return unknown if the data provided is not sufficient to make a
- // a determination. When peek returns EOF that may mean the end of the input or the
- // end of buffered input - recognizers should return the best guess at that time.
- RecognizesData(peek io.Reader) (ok, unknown bool, err error)
-}
-
-// NewDecoder creates a decoder that will attempt multiple decoders in an order defined
-// by:
-//
-// 1. The decoder implements RecognizingDecoder and identifies the data
-// 2. All other decoders, and any decoder that returned true for unknown.
-//
-// The order passed to the constructor is preserved within those priorities.
-func NewDecoder(decoders ...runtime.Decoder) runtime.Decoder {
- return &decoder{
- decoders: decoders,
- }
-}
-
-type decoder struct {
- decoders []runtime.Decoder
-}
-
-var _ RecognizingDecoder = &decoder{}
-
-func (d *decoder) RecognizesData(peek io.Reader) (bool, bool, error) {
- var (
- lastErr error
- anyUnknown bool
- )
- data, _ := bufio.NewReaderSize(peek, 1024).Peek(1024)
- for _, r := range d.decoders {
- switch t := r.(type) {
- case RecognizingDecoder:
- ok, unknown, err := t.RecognizesData(bytes.NewBuffer(data))
- if err != nil {
- lastErr = err
- continue
- }
- anyUnknown = anyUnknown || unknown
- if !ok {
- continue
- }
- return true, false, nil
- }
- }
- return false, anyUnknown, lastErr
-}
-
-func (d *decoder) Decode(data []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
- var (
- lastErr error
- skipped []runtime.Decoder
- )
-
- // try recognizers, record any decoders we need to give a chance later
- for _, r := range d.decoders {
- switch t := r.(type) {
- case RecognizingDecoder:
- buf := bytes.NewBuffer(data)
- ok, unknown, err := t.RecognizesData(buf)
- if err != nil {
- lastErr = err
- continue
- }
- if unknown {
- skipped = append(skipped, t)
- continue
- }
- if !ok {
- continue
- }
- return r.Decode(data, gvk, into)
- default:
- skipped = append(skipped, t)
- }
- }
-
- // try recognizers that returned unknown or didn't recognize their data
- for _, r := range skipped {
- out, actual, err := r.Decode(data, gvk, into)
- if err != nil {
- lastErr = err
- continue
- }
- return out, actual, nil
- }
-
- if lastErr == nil {
- lastErr = fmt.Errorf("no serialization format matched the provided data")
- }
- return nil, nil, lastErr
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go
deleted file mode 100644
index a60a7c041..000000000
--- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package streaming implements encoder and decoder for streams
-// of runtime.Objects over io.Writer/Readers.
-package streaming
-
-import (
- "bytes"
- "fmt"
- "io"
-
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// Encoder is a runtime.Encoder on a stream.
-type Encoder interface {
- // Encode will write the provided object to the stream or return an error. It obeys the same
- // contract as runtime.VersionedEncoder.
- Encode(obj runtime.Object) error
-}
-
-// Decoder is a runtime.Decoder from a stream.
-type Decoder interface {
- // Decode will return io.EOF when no more objects are available.
- Decode(defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)
- // Close closes the underlying stream.
- Close() error
-}
-
-// Serializer is a factory for creating encoders and decoders that work over streams.
-type Serializer interface {
- NewEncoder(w io.Writer) Encoder
- NewDecoder(r io.ReadCloser) Decoder
-}
-
-type decoder struct {
- reader io.ReadCloser
- decoder runtime.Decoder
- buf []byte
- maxBytes int
- resetRead bool
-}
-
-// NewDecoder creates a streaming decoder that reads object chunks from r and decodes them with d.
-// The reader is expected to return ErrShortRead if the provided buffer is not large enough to read
-// an entire object.
-func NewDecoder(r io.ReadCloser, d runtime.Decoder) Decoder {
- return &decoder{
- reader: r,
- decoder: d,
- buf: make([]byte, 1024),
- maxBytes: 16 * 1024 * 1024,
- }
-}
-
-var ErrObjectTooLarge = fmt.Errorf("object to decode was longer than maximum allowed size")
-
-// Decode reads the next object from the stream and decodes it.
-func (d *decoder) Decode(defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
- base := 0
- for {
- n, err := d.reader.Read(d.buf[base:])
- if err == io.ErrShortBuffer {
- if n == 0 {
- return nil, nil, fmt.Errorf("got short buffer with n=0, base=%d, cap=%d", base, cap(d.buf))
- }
- if d.resetRead {
- continue
- }
- // double the buffer size up to maxBytes
- if len(d.buf) < d.maxBytes {
- base += n
- d.buf = append(d.buf, make([]byte, len(d.buf))...)
- continue
- }
- // must read the rest of the frame (until we stop getting ErrShortBuffer)
- d.resetRead = true
- base = 0
- return nil, nil, ErrObjectTooLarge
- }
- if err != nil {
- return nil, nil, err
- }
- if d.resetRead {
- // now that we have drained the large read, continue
- d.resetRead = false
- continue
- }
- base += n
- break
- }
- return d.decoder.Decode(d.buf[:base], defaults, into)
-}
-
-func (d *decoder) Close() error {
- return d.reader.Close()
-}
-
-type encoder struct {
- writer io.Writer
- encoder runtime.Encoder
- buf *bytes.Buffer
-}
-
-// NewEncoder returns a new streaming encoder.
-func NewEncoder(w io.Writer, e runtime.Encoder) Encoder {
- return &encoder{
- writer: w,
- encoder: e,
- buf: &bytes.Buffer{},
- }
-}
-
-// Encode writes the provided object to the nested writer.
-func (e *encoder) Encode(obj runtime.Object) error {
- if err := e.encoder.Encode(obj, e.buf); err != nil {
- return err
- }
- _, err := e.writer.Write(e.buf.Bytes())
- e.buf.Reset()
- return err
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go
deleted file mode 100644
index 718c5dfb7..000000000
--- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package versioning
-
-import (
- "encoding/json"
- "io"
- "reflect"
- "sync"
-
- "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/klog/v2"
-)
-
-// NewDefaultingCodecForScheme is a convenience method for callers that are using a scheme.
-func NewDefaultingCodecForScheme(
- // TODO: I should be a scheme interface?
- scheme *runtime.Scheme,
- encoder runtime.Encoder,
- decoder runtime.Decoder,
- encodeVersion runtime.GroupVersioner,
- decodeVersion runtime.GroupVersioner,
-) runtime.Codec {
- return NewCodec(encoder, decoder, runtime.UnsafeObjectConvertor(scheme), scheme, scheme, scheme, encodeVersion, decodeVersion, scheme.Name())
-}
-
-// NewCodec takes objects in their internal versions and converts them to external versions before
-// serializing them. It assumes the serializer provided to it only deals with external versions.
-// This class is also a serializer, but is generally used with a specific version.
-func NewCodec(
- encoder runtime.Encoder,
- decoder runtime.Decoder,
- convertor runtime.ObjectConvertor,
- creater runtime.ObjectCreater,
- typer runtime.ObjectTyper,
- defaulter runtime.ObjectDefaulter,
- encodeVersion runtime.GroupVersioner,
- decodeVersion runtime.GroupVersioner,
- originalSchemeName string,
-) runtime.Codec {
- internal := &codec{
- encoder: encoder,
- decoder: decoder,
- convertor: convertor,
- creater: creater,
- typer: typer,
- defaulter: defaulter,
-
- encodeVersion: encodeVersion,
- decodeVersion: decodeVersion,
-
- identifier: identifier(encodeVersion, encoder),
-
- originalSchemeName: originalSchemeName,
- }
- return internal
-}
-
-type codec struct {
- encoder runtime.Encoder
- decoder runtime.Decoder
- convertor runtime.ObjectConvertor
- creater runtime.ObjectCreater
- typer runtime.ObjectTyper
- defaulter runtime.ObjectDefaulter
-
- encodeVersion runtime.GroupVersioner
- decodeVersion runtime.GroupVersioner
-
- identifier runtime.Identifier
-
- // originalSchemeName is optional, but when filled in it holds the name of the scheme from which this codec originates
- originalSchemeName string
-}
-
-var identifiersMap sync.Map
-
-type codecIdentifier struct {
- EncodeGV string `json:"encodeGV,omitempty"`
- Encoder string `json:"encoder,omitempty"`
- Name string `json:"name,omitempty"`
-}
-
-// identifier computes Identifier of Encoder based on codec parameters.
-func identifier(encodeGV runtime.GroupVersioner, encoder runtime.Encoder) runtime.Identifier {
- result := codecIdentifier{
- Name: "versioning",
- }
-
- if encodeGV != nil {
- result.EncodeGV = encodeGV.Identifier()
- }
- if encoder != nil {
- result.Encoder = string(encoder.Identifier())
- }
- if id, ok := identifiersMap.Load(result); ok {
- return id.(runtime.Identifier)
- }
- identifier, err := json.Marshal(result)
- if err != nil {
- klog.Fatalf("Failed marshaling identifier for codec: %v", err)
- }
- identifiersMap.Store(result, runtime.Identifier(identifier))
- return runtime.Identifier(identifier)
-}
-
-// Decode attempts a decode of the object, then tries to convert it to the internal version. If into is provided and the decoding is
-// successful, the returned runtime.Object will be the value passed as into. Note that this may bypass conversion if you pass an
-// into that matches the serialized version.
-func (c *codec) Decode(data []byte, defaultGVK *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
- // If the into object is unstructured and expresses an opinion about its group/version,
- // create a new instance of the type so we always exercise the conversion path (skips short-circuiting on `into == obj`)
- decodeInto := into
- if into != nil {
- if _, ok := into.(runtime.Unstructured); ok && !into.GetObjectKind().GroupVersionKind().GroupVersion().Empty() {
- decodeInto = reflect.New(reflect.TypeOf(into).Elem()).Interface().(runtime.Object)
- }
- }
-
- obj, gvk, err := c.decoder.Decode(data, defaultGVK, decodeInto)
- if err != nil {
- return nil, gvk, err
- }
-
- if d, ok := obj.(runtime.NestedObjectDecoder); ok {
- if err := d.DecodeNestedObjects(runtime.WithoutVersionDecoder{c.decoder}); err != nil {
- return nil, gvk, err
- }
- }
-
- // if we specify a target, use generic conversion.
- if into != nil {
- // perform defaulting if requested
- if c.defaulter != nil {
- c.defaulter.Default(obj)
- }
-
- // Short-circuit conversion if the into object is same object
- if into == obj {
- return into, gvk, nil
- }
-
- if err := c.convertor.Convert(obj, into, c.decodeVersion); err != nil {
- return nil, gvk, err
- }
-
- return into, gvk, nil
- }
-
- // perform defaulting if requested
- if c.defaulter != nil {
- c.defaulter.Default(obj)
- }
-
- out, err := c.convertor.ConvertToVersion(obj, c.decodeVersion)
- if err != nil {
- return nil, gvk, err
- }
- return out, gvk, nil
-}
-
-// Encode ensures the provided object is output in the appropriate group and version, invoking
-// conversion if necessary. Unversioned objects (according to the ObjectTyper) are output as is.
-func (c *codec) Encode(obj runtime.Object, w io.Writer) error {
- if co, ok := obj.(runtime.CacheableObject); ok {
- return co.CacheEncode(c.Identifier(), c.doEncode, w)
- }
- return c.doEncode(obj, w)
-}
-
-func (c *codec) doEncode(obj runtime.Object, w io.Writer) error {
- switch obj := obj.(type) {
- case *runtime.Unknown:
- return c.encoder.Encode(obj, w)
- case runtime.Unstructured:
- // An unstructured list can contain objects of multiple group version kinds. don't short-circuit just
- // because the top-level type matches our desired destination type. actually send the object to the converter
- // to give it a chance to convert the list items if needed.
- if _, ok := obj.(*unstructured.UnstructuredList); !ok {
- // avoid conversion roundtrip if GVK is the right one already or is empty (yes, this is a hack, but the old behaviour we rely on in kubectl)
- objGVK := obj.GetObjectKind().GroupVersionKind()
- if len(objGVK.Version) == 0 {
- return c.encoder.Encode(obj, w)
- }
- targetGVK, ok := c.encodeVersion.KindForGroupVersionKinds([]schema.GroupVersionKind{objGVK})
- if !ok {
- return runtime.NewNotRegisteredGVKErrForTarget(c.originalSchemeName, objGVK, c.encodeVersion)
- }
- if targetGVK == objGVK {
- return c.encoder.Encode(obj, w)
- }
- }
- }
-
- gvks, isUnversioned, err := c.typer.ObjectKinds(obj)
- if err != nil {
- return err
- }
-
- objectKind := obj.GetObjectKind()
- old := objectKind.GroupVersionKind()
- // restore the old GVK after encoding
- defer objectKind.SetGroupVersionKind(old)
-
- if c.encodeVersion == nil || isUnversioned {
- if e, ok := obj.(runtime.NestedObjectEncoder); ok {
- if err := e.EncodeNestedObjects(runtime.WithVersionEncoder{Encoder: c.encoder, ObjectTyper: c.typer}); err != nil {
- return err
- }
- }
- objectKind.SetGroupVersionKind(gvks[0])
- return c.encoder.Encode(obj, w)
- }
-
- // Perform a conversion if necessary
- out, err := c.convertor.ConvertToVersion(obj, c.encodeVersion)
- if err != nil {
- return err
- }
-
- if e, ok := out.(runtime.NestedObjectEncoder); ok {
- if err := e.EncodeNestedObjects(runtime.WithVersionEncoder{Version: c.encodeVersion, Encoder: c.encoder, ObjectTyper: c.typer}); err != nil {
- return err
- }
- }
-
- // Conversion is responsible for setting the proper group, version, and kind onto the outgoing object
- return c.encoder.Encode(out, w)
-}
-
-// Identifier implements runtime.Encoder interface.
-func (c *codec) Identifier() runtime.Identifier {
- return c.identifier
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/clock/clock.go b/vendor/k8s.io/apimachinery/pkg/util/clock/clock.go
deleted file mode 100644
index 3e1e2517b..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/clock/clock.go
+++ /dev/null
@@ -1,407 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package clock
-
-import (
- "sync"
- "time"
-)
-
-// PassiveClock allows for injecting fake or real clocks into code
-// that needs to read the current time but does not support scheduling
-// activity in the future.
-type PassiveClock interface {
- Now() time.Time
- Since(time.Time) time.Duration
-}
-
-// Clock allows for injecting fake or real clocks into code that
-// needs to do arbitrary things based on time.
-type Clock interface {
- PassiveClock
- After(time.Duration) <-chan time.Time
- NewTimer(time.Duration) Timer
- Sleep(time.Duration)
- NewTicker(time.Duration) Ticker
-}
-
-// RealClock really calls time.Now()
-type RealClock struct{}
-
-// Now returns the current time.
-func (RealClock) Now() time.Time {
- return time.Now()
-}
-
-// Since returns time since the specified timestamp.
-func (RealClock) Since(ts time.Time) time.Duration {
- return time.Since(ts)
-}
-
-// After is the same as time.After(d).
-func (RealClock) After(d time.Duration) <-chan time.Time {
- return time.After(d)
-}
-
-// NewTimer returns a new Timer.
-func (RealClock) NewTimer(d time.Duration) Timer {
- return &realTimer{
- timer: time.NewTimer(d),
- }
-}
-
-// NewTicker returns a new Ticker.
-func (RealClock) NewTicker(d time.Duration) Ticker {
- return &realTicker{
- ticker: time.NewTicker(d),
- }
-}
-
-// Sleep pauses the RealClock for duration d.
-func (RealClock) Sleep(d time.Duration) {
- time.Sleep(d)
-}
-
-// FakePassiveClock implements PassiveClock, but returns an arbitrary time.
-type FakePassiveClock struct {
- lock sync.RWMutex
- time time.Time
-}
-
-// FakeClock implements Clock, but returns an arbitrary time.
-type FakeClock struct {
- FakePassiveClock
-
- // waiters are waiting for the fake time to pass their specified time
- waiters []fakeClockWaiter
-}
-
-type fakeClockWaiter struct {
- targetTime time.Time
- stepInterval time.Duration
- skipIfBlocked bool
- destChan chan time.Time
-}
-
-// NewFakePassiveClock returns a new FakePassiveClock.
-func NewFakePassiveClock(t time.Time) *FakePassiveClock {
- return &FakePassiveClock{
- time: t,
- }
-}
-
-// NewFakeClock returns a new FakeClock
-func NewFakeClock(t time.Time) *FakeClock {
- return &FakeClock{
- FakePassiveClock: *NewFakePassiveClock(t),
- }
-}
-
-// Now returns f's time.
-func (f *FakePassiveClock) Now() time.Time {
- f.lock.RLock()
- defer f.lock.RUnlock()
- return f.time
-}
-
-// Since returns time since the time in f.
-func (f *FakePassiveClock) Since(ts time.Time) time.Duration {
- f.lock.RLock()
- defer f.lock.RUnlock()
- return f.time.Sub(ts)
-}
-
-// SetTime sets the time on the FakePassiveClock.
-func (f *FakePassiveClock) SetTime(t time.Time) {
- f.lock.Lock()
- defer f.lock.Unlock()
- f.time = t
-}
-
-// After is the Fake version of time.After(d).
-func (f *FakeClock) After(d time.Duration) <-chan time.Time {
- f.lock.Lock()
- defer f.lock.Unlock()
- stopTime := f.time.Add(d)
- ch := make(chan time.Time, 1) // Don't block!
- f.waiters = append(f.waiters, fakeClockWaiter{
- targetTime: stopTime,
- destChan: ch,
- })
- return ch
-}
-
-// NewTimer is the Fake version of time.NewTimer(d).
-func (f *FakeClock) NewTimer(d time.Duration) Timer {
- f.lock.Lock()
- defer f.lock.Unlock()
- stopTime := f.time.Add(d)
- ch := make(chan time.Time, 1) // Don't block!
- timer := &fakeTimer{
- fakeClock: f,
- waiter: fakeClockWaiter{
- targetTime: stopTime,
- destChan: ch,
- },
- }
- f.waiters = append(f.waiters, timer.waiter)
- return timer
-}
-
-// NewTicker returns a new Ticker.
-func (f *FakeClock) NewTicker(d time.Duration) Ticker {
- f.lock.Lock()
- defer f.lock.Unlock()
- tickTime := f.time.Add(d)
- ch := make(chan time.Time, 1) // hold one tick
- f.waiters = append(f.waiters, fakeClockWaiter{
- targetTime: tickTime,
- stepInterval: d,
- skipIfBlocked: true,
- destChan: ch,
- })
-
- return &fakeTicker{
- c: ch,
- }
-}
-
-// Step moves clock by Duration, notifies anyone that's called After, Tick, or NewTimer
-func (f *FakeClock) Step(d time.Duration) {
- f.lock.Lock()
- defer f.lock.Unlock()
- f.setTimeLocked(f.time.Add(d))
-}
-
-// SetTime sets the time on a FakeClock.
-func (f *FakeClock) SetTime(t time.Time) {
- f.lock.Lock()
- defer f.lock.Unlock()
- f.setTimeLocked(t)
-}
-
-// Actually changes the time and checks any waiters. f must be write-locked.
-func (f *FakeClock) setTimeLocked(t time.Time) {
- f.time = t
- newWaiters := make([]fakeClockWaiter, 0, len(f.waiters))
- for i := range f.waiters {
- w := &f.waiters[i]
- if !w.targetTime.After(t) {
-
- if w.skipIfBlocked {
- select {
- case w.destChan <- t:
- default:
- }
- } else {
- w.destChan <- t
- }
-
- if w.stepInterval > 0 {
- for !w.targetTime.After(t) {
- w.targetTime = w.targetTime.Add(w.stepInterval)
- }
- newWaiters = append(newWaiters, *w)
- }
-
- } else {
- newWaiters = append(newWaiters, f.waiters[i])
- }
- }
- f.waiters = newWaiters
-}
-
-// HasWaiters returns true if After has been called on f but not yet satisfied (so you can
-// write race-free tests).
-func (f *FakeClock) HasWaiters() bool {
- f.lock.RLock()
- defer f.lock.RUnlock()
- return len(f.waiters) > 0
-}
-
-// Sleep pauses the FakeClock for duration d.
-func (f *FakeClock) Sleep(d time.Duration) {
- f.Step(d)
-}
-
-// IntervalClock implements Clock, but each invocation of Now steps the clock forward the specified duration
-type IntervalClock struct {
- Time time.Time
- Duration time.Duration
-}
-
-// Now returns i's time.
-func (i *IntervalClock) Now() time.Time {
- i.Time = i.Time.Add(i.Duration)
- return i.Time
-}
-
-// Since returns time since the time in i.
-func (i *IntervalClock) Since(ts time.Time) time.Duration {
- return i.Time.Sub(ts)
-}
-
-// After is currently unimplemented, will panic.
-// TODO: make interval clock use FakeClock so this can be implemented.
-func (*IntervalClock) After(d time.Duration) <-chan time.Time {
- panic("IntervalClock doesn't implement After")
-}
-
-// NewTimer is currently unimplemented, will panic.
-// TODO: make interval clock use FakeClock so this can be implemented.
-func (*IntervalClock) NewTimer(d time.Duration) Timer {
- panic("IntervalClock doesn't implement NewTimer")
-}
-
-// NewTicker is currently unimplemented, will panic.
-// TODO: make interval clock use FakeClock so this can be implemented.
-func (*IntervalClock) NewTicker(d time.Duration) Ticker {
- panic("IntervalClock doesn't implement NewTicker")
-}
-
-// Sleep is currently unimplemented; will panic.
-func (*IntervalClock) Sleep(d time.Duration) {
- panic("IntervalClock doesn't implement Sleep")
-}
-
-// Timer allows for injecting fake or real timers into code that
-// needs to do arbitrary things based on time.
-type Timer interface {
- C() <-chan time.Time
- Stop() bool
- Reset(d time.Duration) bool
-}
-
-// realTimer is backed by an actual time.Timer.
-type realTimer struct {
- timer *time.Timer
-}
-
-// C returns the underlying timer's channel.
-func (r *realTimer) C() <-chan time.Time {
- return r.timer.C
-}
-
-// Stop calls Stop() on the underlying timer.
-func (r *realTimer) Stop() bool {
- return r.timer.Stop()
-}
-
-// Reset calls Reset() on the underlying timer.
-func (r *realTimer) Reset(d time.Duration) bool {
- return r.timer.Reset(d)
-}
-
-// fakeTimer implements Timer based on a FakeClock.
-type fakeTimer struct {
- fakeClock *FakeClock
- waiter fakeClockWaiter
-}
-
-// C returns the channel that notifies when this timer has fired.
-func (f *fakeTimer) C() <-chan time.Time {
- return f.waiter.destChan
-}
-
-// Stop conditionally stops the timer. If the timer has neither fired
-// nor been stopped then this call stops the timer and returns true,
-// otherwise this call returns false. This is like time.Timer::Stop.
-func (f *fakeTimer) Stop() bool {
- f.fakeClock.lock.Lock()
- defer f.fakeClock.lock.Unlock()
- // The timer has already fired or been stopped, unless it is found
- // among the clock's waiters.
- stopped := false
- oldWaiters := f.fakeClock.waiters
- newWaiters := make([]fakeClockWaiter, 0, len(oldWaiters))
- seekChan := f.waiter.destChan
- for i := range oldWaiters {
- // Identify the timer's fakeClockWaiter by the identity of the
- // destination channel, nothing else is necessarily unique and
- // constant since the timer's creation.
- if oldWaiters[i].destChan == seekChan {
- stopped = true
- } else {
- newWaiters = append(newWaiters, oldWaiters[i])
- }
- }
-
- f.fakeClock.waiters = newWaiters
-
- return stopped
-}
-
-// Reset conditionally updates the firing time of the timer. If the
-// timer has neither fired nor been stopped then this call resets the
-// timer to the fake clock's "now" + d and returns true, otherwise
-// it creates a new waiter, adds it to the clock, and returns true.
-//
-// It is not possible to return false, because a fake timer can be reset
-// from any state (waiting to fire, already fired, and stopped).
-//
-// See the GoDoc for time.Timer::Reset for more context on why
-// the return value of Reset() is not useful.
-func (f *fakeTimer) Reset(d time.Duration) bool {
- f.fakeClock.lock.Lock()
- defer f.fakeClock.lock.Unlock()
- waiters := f.fakeClock.waiters
- seekChan := f.waiter.destChan
- for i := range waiters {
- if waiters[i].destChan == seekChan {
- waiters[i].targetTime = f.fakeClock.time.Add(d)
- return true
- }
- }
- // No existing waiter, timer has already fired or been reset.
- // We should still enable Reset() to succeed by creating a
- // new waiter and adding it to the clock's waiters.
- newWaiter := fakeClockWaiter{
- targetTime: f.fakeClock.time.Add(d),
- destChan: seekChan,
- }
- f.fakeClock.waiters = append(f.fakeClock.waiters, newWaiter)
- return true
-}
-
-// Ticker defines the Ticker interface
-type Ticker interface {
- C() <-chan time.Time
- Stop()
-}
-
-type realTicker struct {
- ticker *time.Ticker
-}
-
-func (t *realTicker) C() <-chan time.Time {
- return t.ticker.C
-}
-
-func (t *realTicker) Stop() {
- t.ticker.Stop()
-}
-
-type fakeTicker struct {
- c <-chan time.Time
-}
-
-func (t *fakeTicker) C() <-chan time.Time {
- return t.c
-}
-
-func (t *fakeTicker) Stop() {
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go b/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go
deleted file mode 100644
index 45aa74bf5..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package framer implements simple frame decoding techniques for an io.ReadCloser
-package framer
-
-import (
- "encoding/binary"
- "encoding/json"
- "io"
-)
-
-type lengthDelimitedFrameWriter struct {
- w io.Writer
- h [4]byte
-}
-
-func NewLengthDelimitedFrameWriter(w io.Writer) io.Writer {
- return &lengthDelimitedFrameWriter{w: w}
-}
-
-// Write writes a single frame to the nested writer, prepending it with the length in
-// in bytes of data (as a 4 byte, bigendian uint32).
-func (w *lengthDelimitedFrameWriter) Write(data []byte) (int, error) {
- binary.BigEndian.PutUint32(w.h[:], uint32(len(data)))
- n, err := w.w.Write(w.h[:])
- if err != nil {
- return 0, err
- }
- if n != len(w.h) {
- return 0, io.ErrShortWrite
- }
- return w.w.Write(data)
-}
-
-type lengthDelimitedFrameReader struct {
- r io.ReadCloser
- remaining int
-}
-
-// NewLengthDelimitedFrameReader returns an io.Reader that will decode length-prefixed
-// frames off of a stream.
-//
-// The protocol is:
-//
-// stream: message ...
-// message: prefix body
-// prefix: 4 byte uint32 in BigEndian order, denotes length of body
-// body: bytes (0..prefix)
-//
-// If the buffer passed to Read is not long enough to contain an entire frame, io.ErrShortRead
-// will be returned along with the number of bytes read.
-func NewLengthDelimitedFrameReader(r io.ReadCloser) io.ReadCloser {
- return &lengthDelimitedFrameReader{r: r}
-}
-
-// Read attempts to read an entire frame into data. If that is not possible, io.ErrShortBuffer
-// is returned and subsequent calls will attempt to read the last frame. A frame is complete when
-// err is nil.
-func (r *lengthDelimitedFrameReader) Read(data []byte) (int, error) {
- if r.remaining <= 0 {
- header := [4]byte{}
- n, err := io.ReadAtLeast(r.r, header[:4], 4)
- if err != nil {
- return 0, err
- }
- if n != 4 {
- return 0, io.ErrUnexpectedEOF
- }
- frameLength := int(binary.BigEndian.Uint32(header[:]))
- r.remaining = frameLength
- }
-
- expect := r.remaining
- max := expect
- if max > len(data) {
- max = len(data)
- }
- n, err := io.ReadAtLeast(r.r, data[:max], int(max))
- r.remaining -= n
- if err == io.ErrShortBuffer || r.remaining > 0 {
- return n, io.ErrShortBuffer
- }
- if err != nil {
- return n, err
- }
- if n != expect {
- return n, io.ErrUnexpectedEOF
- }
-
- return n, nil
-}
-
-func (r *lengthDelimitedFrameReader) Close() error {
- return r.r.Close()
-}
-
-type jsonFrameReader struct {
- r io.ReadCloser
- decoder *json.Decoder
- remaining []byte
-}
-
-// NewJSONFramedReader returns an io.Reader that will decode individual JSON objects off
-// of a wire.
-//
-// The boundaries between each frame are valid JSON objects. A JSON parsing error will terminate
-// the read.
-func NewJSONFramedReader(r io.ReadCloser) io.ReadCloser {
- return &jsonFrameReader{
- r: r,
- decoder: json.NewDecoder(r),
- }
-}
-
-// ReadFrame decodes the next JSON object in the stream, or returns an error. The returned
-// byte slice will be modified the next time ReadFrame is invoked and should not be altered.
-func (r *jsonFrameReader) Read(data []byte) (int, error) {
- // Return whatever remaining data exists from an in progress frame
- if n := len(r.remaining); n > 0 {
- if n <= len(data) {
- //lint:ignore SA4006,SA4010 underlying array of data is modified here.
- data = append(data[0:0], r.remaining...)
- r.remaining = nil
- return n, nil
- }
-
- n = len(data)
- //lint:ignore SA4006,SA4010 underlying array of data is modified here.
- data = append(data[0:0], r.remaining[:n]...)
- r.remaining = r.remaining[n:]
- return n, io.ErrShortBuffer
- }
-
- // RawMessage#Unmarshal appends to data - we reset the slice down to 0 and will either see
- // data written to data, or be larger than data and a different array.
- n := len(data)
- m := json.RawMessage(data[:0])
- if err := r.decoder.Decode(&m); err != nil {
- return 0, err
- }
-
- // If capacity of data is less than length of the message, decoder will allocate a new slice
- // and set m to it, which means we need to copy the partial result back into data and preserve
- // the remaining result for subsequent reads.
- if len(m) > n {
- //lint:ignore SA4006,SA4010 underlying array of data is modified here.
- data = append(data[0:0], m[:n]...)
- r.remaining = m[n:]
- return n, io.ErrShortBuffer
- }
- return len(m), nil
-}
-
-func (r *jsonFrameReader) Close() error {
- return r.r.Close()
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/httpstream/doc.go b/vendor/k8s.io/apimachinery/pkg/util/httpstream/doc.go
deleted file mode 100644
index 5893df5bd..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/httpstream/doc.go
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package httpstream adds multiplexed streaming support to HTTP requests and
-// responses via connection upgrades.
-package httpstream // import "k8s.io/apimachinery/pkg/util/httpstream"
diff --git a/vendor/k8s.io/apimachinery/pkg/util/httpstream/httpstream.go b/vendor/k8s.io/apimachinery/pkg/util/httpstream/httpstream.go
deleted file mode 100644
index 00ce5f785..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/httpstream/httpstream.go
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package httpstream
-
-import (
- "fmt"
- "io"
- "net/http"
- "strings"
- "time"
-)
-
-const (
- HeaderConnection = "Connection"
- HeaderUpgrade = "Upgrade"
- HeaderProtocolVersion = "X-Stream-Protocol-Version"
- HeaderAcceptedProtocolVersions = "X-Accepted-Stream-Protocol-Versions"
-)
-
-// NewStreamHandler defines a function that is called when a new Stream is
-// received. If no error is returned, the Stream is accepted; otherwise,
-// the stream is rejected. After the reply frame has been sent, replySent is closed.
-type NewStreamHandler func(stream Stream, replySent <-chan struct{}) error
-
-// NoOpNewStreamHandler is a stream handler that accepts a new stream and
-// performs no other logic.
-func NoOpNewStreamHandler(stream Stream, replySent <-chan struct{}) error { return nil }
-
-// Dialer knows how to open a streaming connection to a server.
-type Dialer interface {
-
- // Dial opens a streaming connection to a server using one of the protocols
- // specified (in order of most preferred to least preferred).
- Dial(protocols ...string) (Connection, string, error)
-}
-
-// UpgradeRoundTripper is a type of http.RoundTripper that is able to upgrade
-// HTTP requests to support multiplexed bidirectional streams. After RoundTrip()
-// is invoked, if the upgrade is successful, clients may retrieve the upgraded
-// connection by calling UpgradeRoundTripper.Connection().
-type UpgradeRoundTripper interface {
- http.RoundTripper
- // NewConnection validates the response and creates a new Connection.
- NewConnection(resp *http.Response) (Connection, error)
-}
-
-// ResponseUpgrader knows how to upgrade HTTP requests and responses to
-// add streaming support to them.
-type ResponseUpgrader interface {
- // UpgradeResponse upgrades an HTTP response to one that supports multiplexed
- // streams. newStreamHandler will be called asynchronously whenever the
- // other end of the upgraded connection creates a new stream.
- UpgradeResponse(w http.ResponseWriter, req *http.Request, newStreamHandler NewStreamHandler) Connection
-}
-
-// Connection represents an upgraded HTTP connection.
-type Connection interface {
- // CreateStream creates a new Stream with the supplied headers.
- CreateStream(headers http.Header) (Stream, error)
- // Close resets all streams and closes the connection.
- Close() error
- // CloseChan returns a channel that is closed when the underlying connection is closed.
- CloseChan() <-chan bool
- // SetIdleTimeout sets the amount of time the connection may remain idle before
- // it is automatically closed.
- SetIdleTimeout(timeout time.Duration)
-}
-
-// Stream represents a bidirectional communications channel that is part of an
-// upgraded connection.
-type Stream interface {
- io.ReadWriteCloser
- // Reset closes both directions of the stream, indicating that neither client
- // or server can use it any more.
- Reset() error
- // Headers returns the headers used to create the stream.
- Headers() http.Header
- // Identifier returns the stream's ID.
- Identifier() uint32
-}
-
-// IsUpgradeRequest returns true if the given request is a connection upgrade request
-func IsUpgradeRequest(req *http.Request) bool {
- for _, h := range req.Header[http.CanonicalHeaderKey(HeaderConnection)] {
- if strings.Contains(strings.ToLower(h), strings.ToLower(HeaderUpgrade)) {
- return true
- }
- }
- return false
-}
-
-func negotiateProtocol(clientProtocols, serverProtocols []string) string {
- for i := range clientProtocols {
- for j := range serverProtocols {
- if clientProtocols[i] == serverProtocols[j] {
- return clientProtocols[i]
- }
- }
- }
- return ""
-}
-
-func commaSeparatedHeaderValues(header []string) []string {
- var parsedClientProtocols []string
- for i := range header {
- for _, clientProtocol := range strings.Split(header[i], ",") {
- if proto := strings.Trim(clientProtocol, " "); len(proto) > 0 {
- parsedClientProtocols = append(parsedClientProtocols, proto)
- }
- }
- }
- return parsedClientProtocols
-}
-
-// Handshake performs a subprotocol negotiation. If the client did request a
-// subprotocol, Handshake will select the first common value found in
-// serverProtocols. If a match is found, Handshake adds a response header
-// indicating the chosen subprotocol. If no match is found, HTTP forbidden is
-// returned, along with a response header containing the list of protocols the
-// server can accept.
-func Handshake(req *http.Request, w http.ResponseWriter, serverProtocols []string) (string, error) {
- clientProtocols := commaSeparatedHeaderValues(req.Header[http.CanonicalHeaderKey(HeaderProtocolVersion)])
- if len(clientProtocols) == 0 {
- return "", fmt.Errorf("unable to upgrade: %s is required", HeaderProtocolVersion)
- }
-
- if len(serverProtocols) == 0 {
- panic(fmt.Errorf("unable to upgrade: serverProtocols is required"))
- }
-
- negotiatedProtocol := negotiateProtocol(clientProtocols, serverProtocols)
- if len(negotiatedProtocol) == 0 {
- for i := range serverProtocols {
- w.Header().Add(HeaderAcceptedProtocolVersions, serverProtocols[i])
- }
- err := fmt.Errorf("unable to upgrade: unable to negotiate protocol: client supports %v, server accepts %v", clientProtocols, serverProtocols)
- http.Error(w, err.Error(), http.StatusForbidden)
- return "", err
- }
-
- w.Header().Add(HeaderProtocolVersion, negotiatedProtocol)
- return negotiatedProtocol, nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go b/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go
deleted file mode 100644
index 336b4908b..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package spdy
-
-import (
- "net"
- "net/http"
- "sync"
- "time"
-
- "github.com/docker/spdystream"
- "k8s.io/apimachinery/pkg/util/httpstream"
- "k8s.io/klog/v2"
-)
-
-// connection maintains state about a spdystream.Connection and its associated
-// streams.
-type connection struct {
- conn *spdystream.Connection
- streams []httpstream.Stream
- streamLock sync.Mutex
- newStreamHandler httpstream.NewStreamHandler
- ping func() (time.Duration, error)
-}
-
-// NewClientConnection creates a new SPDY client connection.
-func NewClientConnection(conn net.Conn) (httpstream.Connection, error) {
- return NewClientConnectionWithPings(conn, 0)
-}
-
-// NewClientConnectionWithPings creates a new SPDY client connection.
-//
-// If pingPeriod is non-zero, a background goroutine will send periodic Ping
-// frames to the server. Use this to keep idle connections through certain load
-// balancers alive longer.
-func NewClientConnectionWithPings(conn net.Conn, pingPeriod time.Duration) (httpstream.Connection, error) {
- spdyConn, err := spdystream.NewConnection(conn, false)
- if err != nil {
- defer conn.Close()
- return nil, err
- }
-
- return newConnection(spdyConn, httpstream.NoOpNewStreamHandler, pingPeriod, spdyConn.Ping), nil
-}
-
-// NewServerConnection creates a new SPDY server connection. newStreamHandler
-// will be invoked when the server receives a newly created stream from the
-// client.
-func NewServerConnection(conn net.Conn, newStreamHandler httpstream.NewStreamHandler) (httpstream.Connection, error) {
- return NewServerConnectionWithPings(conn, newStreamHandler, 0)
-}
-
-// NewServerConnectionWithPings creates a new SPDY server connection.
-// newStreamHandler will be invoked when the server receives a newly created
-// stream from the client.
-//
-// If pingPeriod is non-zero, a background goroutine will send periodic Ping
-// frames to the server. Use this to keep idle connections through certain load
-// balancers alive longer.
-func NewServerConnectionWithPings(conn net.Conn, newStreamHandler httpstream.NewStreamHandler, pingPeriod time.Duration) (httpstream.Connection, error) {
- spdyConn, err := spdystream.NewConnection(conn, true)
- if err != nil {
- defer conn.Close()
- return nil, err
- }
-
- return newConnection(spdyConn, newStreamHandler, pingPeriod, spdyConn.Ping), nil
-}
-
-// newConnection returns a new connection wrapping conn. newStreamHandler
-// will be invoked when the server receives a newly created stream from the
-// client.
-func newConnection(conn *spdystream.Connection, newStreamHandler httpstream.NewStreamHandler, pingPeriod time.Duration, pingFn func() (time.Duration, error)) httpstream.Connection {
- c := &connection{conn: conn, newStreamHandler: newStreamHandler, ping: pingFn}
- go conn.Serve(c.newSpdyStream)
- if pingPeriod > 0 && pingFn != nil {
- go c.sendPings(pingPeriod)
- }
- return c
-}
-
-// createStreamResponseTimeout indicates how long to wait for the other side to
-// acknowledge the new stream before timing out.
-const createStreamResponseTimeout = 30 * time.Second
-
-// Close first sends a reset for all of the connection's streams, and then
-// closes the underlying spdystream.Connection.
-func (c *connection) Close() error {
- c.streamLock.Lock()
- for _, s := range c.streams {
- // calling Reset instead of Close ensures that all streams are fully torn down
- s.Reset()
- }
- c.streams = make([]httpstream.Stream, 0)
- c.streamLock.Unlock()
-
- // now that all streams are fully torn down, it's safe to call close on the underlying connection,
- // which should be able to terminate immediately at this point, instead of waiting for any
- // remaining graceful stream termination.
- return c.conn.Close()
-}
-
-// CreateStream creates a new stream with the specified headers and registers
-// it with the connection.
-func (c *connection) CreateStream(headers http.Header) (httpstream.Stream, error) {
- stream, err := c.conn.CreateStream(headers, nil, false)
- if err != nil {
- return nil, err
- }
- if err = stream.WaitTimeout(createStreamResponseTimeout); err != nil {
- return nil, err
- }
-
- c.registerStream(stream)
- return stream, nil
-}
-
-// registerStream adds the stream s to the connection's list of streams that
-// it owns.
-func (c *connection) registerStream(s httpstream.Stream) {
- c.streamLock.Lock()
- c.streams = append(c.streams, s)
- c.streamLock.Unlock()
-}
-
-// CloseChan returns a channel that, when closed, indicates that the underlying
-// spdystream.Connection has been closed.
-func (c *connection) CloseChan() <-chan bool {
- return c.conn.CloseChan()
-}
-
-// newSpdyStream is the internal new stream handler used by spdystream.Connection.Serve.
-// It calls connection's newStreamHandler, giving it the opportunity to accept or reject
-// the stream. If newStreamHandler returns an error, the stream is rejected. If not, the
-// stream is accepted and registered with the connection.
-func (c *connection) newSpdyStream(stream *spdystream.Stream) {
- replySent := make(chan struct{})
- err := c.newStreamHandler(stream, replySent)
- rejectStream := (err != nil)
- if rejectStream {
- klog.Warningf("Stream rejected: %v", err)
- stream.Reset()
- return
- }
-
- c.registerStream(stream)
- stream.SendReply(http.Header{}, rejectStream)
- close(replySent)
-}
-
-// SetIdleTimeout sets the amount of time the connection may remain idle before
-// it is automatically closed.
-func (c *connection) SetIdleTimeout(timeout time.Duration) {
- c.conn.SetIdleTimeout(timeout)
-}
-
-func (c *connection) sendPings(period time.Duration) {
- t := time.NewTicker(period)
- defer t.Stop()
- for {
- select {
- case <-c.conn.CloseChan():
- return
- case <-t.C:
- }
- if _, err := c.ping(); err != nil {
- klog.V(3).Infof("SPDY Ping failed: %v", err)
- // Continue, in case this is a transient failure.
- // c.conn.CloseChan above will tell us when the connection is
- // actually closed.
- }
- }
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go b/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go
deleted file mode 100644
index 4cb1cfadc..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go
+++ /dev/null
@@ -1,369 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package spdy
-
-import (
- "bufio"
- "bytes"
- "context"
- "crypto/tls"
- "encoding/base64"
- "fmt"
- "io"
- "io/ioutil"
- "net"
- "net/http"
- "net/http/httputil"
- "net/url"
- "strings"
- "time"
-
- apierrors "k8s.io/apimachinery/pkg/api/errors"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/serializer"
- "k8s.io/apimachinery/pkg/util/httpstream"
- utilnet "k8s.io/apimachinery/pkg/util/net"
- "k8s.io/apimachinery/third_party/forked/golang/netutil"
-)
-
-// SpdyRoundTripper knows how to upgrade an HTTP request to one that supports
-// multiplexed streams. After RoundTrip() is invoked, Conn will be set
-// and usable. SpdyRoundTripper implements the UpgradeRoundTripper interface.
-type SpdyRoundTripper struct {
- //tlsConfig holds the TLS configuration settings to use when connecting
- //to the remote server.
- tlsConfig *tls.Config
-
- /* TODO according to http://golang.org/pkg/net/http/#RoundTripper, a RoundTripper
- must be safe for use by multiple concurrent goroutines. If this is absolutely
- necessary, we could keep a map from http.Request to net.Conn. In practice,
- a client will create an http.Client, set the transport to a new insteace of
- SpdyRoundTripper, and use it a single time, so this hopefully won't be an issue.
- */
- // conn is the underlying network connection to the remote server.
- conn net.Conn
-
- // Dialer is the dialer used to connect. Used if non-nil.
- Dialer *net.Dialer
-
- // proxier knows which proxy to use given a request, defaults to http.ProxyFromEnvironment
- // Used primarily for mocking the proxy discovery in tests.
- proxier func(req *http.Request) (*url.URL, error)
-
- // followRedirects indicates if the round tripper should examine responses for redirects and
- // follow them.
- followRedirects bool
- // requireSameHostRedirects restricts redirect following to only follow redirects to the same host
- // as the original request.
- requireSameHostRedirects bool
- // pingPeriod is a period for sending Ping frames over established
- // connections.
- pingPeriod time.Duration
-}
-
-var _ utilnet.TLSClientConfigHolder = &SpdyRoundTripper{}
-var _ httpstream.UpgradeRoundTripper = &SpdyRoundTripper{}
-var _ utilnet.Dialer = &SpdyRoundTripper{}
-
-// NewRoundTripper creates a new SpdyRoundTripper that will use the specified
-// tlsConfig.
-func NewRoundTripper(tlsConfig *tls.Config, followRedirects, requireSameHostRedirects bool) *SpdyRoundTripper {
- return NewRoundTripperWithConfig(RoundTripperConfig{
- TLS: tlsConfig,
- FollowRedirects: followRedirects,
- RequireSameHostRedirects: requireSameHostRedirects,
- })
-}
-
-// NewRoundTripperWithProxy creates a new SpdyRoundTripper that will use the
-// specified tlsConfig and proxy func.
-func NewRoundTripperWithProxy(tlsConfig *tls.Config, followRedirects, requireSameHostRedirects bool, proxier func(*http.Request) (*url.URL, error)) *SpdyRoundTripper {
- return NewRoundTripperWithConfig(RoundTripperConfig{
- TLS: tlsConfig,
- FollowRedirects: followRedirects,
- RequireSameHostRedirects: requireSameHostRedirects,
- Proxier: proxier,
- })
-}
-
-// NewRoundTripperWithProxy creates a new SpdyRoundTripper with the specified
-// configuration.
-func NewRoundTripperWithConfig(cfg RoundTripperConfig) *SpdyRoundTripper {
- if cfg.Proxier == nil {
- cfg.Proxier = utilnet.NewProxierWithNoProxyCIDR(http.ProxyFromEnvironment)
- }
- return &SpdyRoundTripper{
- tlsConfig: cfg.TLS,
- followRedirects: cfg.FollowRedirects,
- requireSameHostRedirects: cfg.RequireSameHostRedirects,
- proxier: cfg.Proxier,
- pingPeriod: cfg.PingPeriod,
- }
-}
-
-// RoundTripperConfig is a set of options for an SpdyRoundTripper.
-type RoundTripperConfig struct {
- // TLS configuration used by the round tripper.
- TLS *tls.Config
- // Proxier is a proxy function invoked on each request. Optional.
- Proxier func(*http.Request) (*url.URL, error)
- // PingPeriod is a period for sending SPDY Pings on the connection.
- // Optional.
- PingPeriod time.Duration
-
- FollowRedirects bool
- RequireSameHostRedirects bool
-}
-
-// TLSClientConfig implements pkg/util/net.TLSClientConfigHolder for proper TLS checking during
-// proxying with a spdy roundtripper.
-func (s *SpdyRoundTripper) TLSClientConfig() *tls.Config {
- return s.tlsConfig
-}
-
-// Dial implements k8s.io/apimachinery/pkg/util/net.Dialer.
-func (s *SpdyRoundTripper) Dial(req *http.Request) (net.Conn, error) {
- conn, err := s.dial(req)
- if err != nil {
- return nil, err
- }
-
- if err := req.Write(conn); err != nil {
- conn.Close()
- return nil, err
- }
-
- return conn, nil
-}
-
-// dial dials the host specified by req, using TLS if appropriate, optionally
-// using a proxy server if one is configured via environment variables.
-func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) {
- proxyURL, err := s.proxier(req)
- if err != nil {
- return nil, err
- }
-
- if proxyURL == nil {
- return s.dialWithoutProxy(req.Context(), req.URL)
- }
-
- // ensure we use a canonical host with proxyReq
- targetHost := netutil.CanonicalAddr(req.URL)
-
- // proxying logic adapted from http://blog.h6t.eu/post/74098062923/golang-websocket-with-http-proxy-support
- proxyReq := http.Request{
- Method: "CONNECT",
- URL: &url.URL{},
- Host: targetHost,
- }
-
- if pa := s.proxyAuth(proxyURL); pa != "" {
- proxyReq.Header = http.Header{}
- proxyReq.Header.Set("Proxy-Authorization", pa)
- }
-
- proxyDialConn, err := s.dialWithoutProxy(req.Context(), proxyURL)
- if err != nil {
- return nil, err
- }
-
- proxyClientConn := httputil.NewProxyClientConn(proxyDialConn, nil)
- _, err = proxyClientConn.Do(&proxyReq)
- if err != nil && err != httputil.ErrPersistEOF {
- return nil, err
- }
-
- rwc, _ := proxyClientConn.Hijack()
-
- if req.URL.Scheme != "https" {
- return rwc, nil
- }
-
- host, _, err := net.SplitHostPort(targetHost)
- if err != nil {
- return nil, err
- }
-
- tlsConfig := s.tlsConfig
- switch {
- case tlsConfig == nil:
- tlsConfig = &tls.Config{ServerName: host}
- case len(tlsConfig.ServerName) == 0:
- tlsConfig = tlsConfig.Clone()
- tlsConfig.ServerName = host
- }
-
- tlsConn := tls.Client(rwc, tlsConfig)
-
- // need to manually call Handshake() so we can call VerifyHostname() below
- if err := tlsConn.Handshake(); err != nil {
- return nil, err
- }
-
- // Return if we were configured to skip validation
- if tlsConfig.InsecureSkipVerify {
- return tlsConn, nil
- }
-
- if err := tlsConn.VerifyHostname(tlsConfig.ServerName); err != nil {
- return nil, err
- }
-
- return tlsConn, nil
-}
-
-// dialWithoutProxy dials the host specified by url, using TLS if appropriate.
-func (s *SpdyRoundTripper) dialWithoutProxy(ctx context.Context, url *url.URL) (net.Conn, error) {
- dialAddr := netutil.CanonicalAddr(url)
-
- if url.Scheme == "http" {
- if s.Dialer == nil {
- var d net.Dialer
- return d.DialContext(ctx, "tcp", dialAddr)
- } else {
- return s.Dialer.DialContext(ctx, "tcp", dialAddr)
- }
- }
-
- // TODO validate the TLSClientConfig is set up?
- var conn *tls.Conn
- var err error
- if s.Dialer == nil {
- conn, err = tls.Dial("tcp", dialAddr, s.tlsConfig)
- } else {
- conn, err = tls.DialWithDialer(s.Dialer, "tcp", dialAddr, s.tlsConfig)
- }
- if err != nil {
- return nil, err
- }
-
- // Return if we were configured to skip validation
- if s.tlsConfig != nil && s.tlsConfig.InsecureSkipVerify {
- return conn, nil
- }
-
- host, _, err := net.SplitHostPort(dialAddr)
- if err != nil {
- return nil, err
- }
- if s.tlsConfig != nil && len(s.tlsConfig.ServerName) > 0 {
- host = s.tlsConfig.ServerName
- }
- err = conn.VerifyHostname(host)
- if err != nil {
- return nil, err
- }
-
- return conn, nil
-}
-
-// proxyAuth returns, for a given proxy URL, the value to be used for the Proxy-Authorization header
-func (s *SpdyRoundTripper) proxyAuth(proxyURL *url.URL) string {
- if proxyURL == nil || proxyURL.User == nil {
- return ""
- }
- credentials := proxyURL.User.String()
- encodedAuth := base64.StdEncoding.EncodeToString([]byte(credentials))
- return fmt.Sprintf("Basic %s", encodedAuth)
-}
-
-// RoundTrip executes the Request and upgrades it. After a successful upgrade,
-// clients may call SpdyRoundTripper.Connection() to retrieve the upgraded
-// connection.
-func (s *SpdyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
- header := utilnet.CloneHeader(req.Header)
- header.Add(httpstream.HeaderConnection, httpstream.HeaderUpgrade)
- header.Add(httpstream.HeaderUpgrade, HeaderSpdy31)
-
- var (
- conn net.Conn
- rawResponse []byte
- err error
- )
-
- if s.followRedirects {
- conn, rawResponse, err = utilnet.ConnectWithRedirects(req.Method, req.URL, header, req.Body, s, s.requireSameHostRedirects)
- } else {
- clone := utilnet.CloneRequest(req)
- clone.Header = header
- conn, err = s.Dial(clone)
- }
- if err != nil {
- return nil, err
- }
-
- responseReader := bufio.NewReader(
- io.MultiReader(
- bytes.NewBuffer(rawResponse),
- conn,
- ),
- )
-
- resp, err := http.ReadResponse(responseReader, nil)
- if err != nil {
- if conn != nil {
- conn.Close()
- }
- return nil, err
- }
-
- s.conn = conn
-
- return resp, nil
-}
-
-// NewConnection validates the upgrade response, creating and returning a new
-// httpstream.Connection if there were no errors.
-func (s *SpdyRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error) {
- connectionHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderConnection))
- upgradeHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderUpgrade))
- if (resp.StatusCode != http.StatusSwitchingProtocols) || !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) {
- defer resp.Body.Close()
- responseError := ""
- responseErrorBytes, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- responseError = "unable to read error from server response"
- } else {
- // TODO: I don't belong here, I should be abstracted from this class
- if obj, _, err := statusCodecs.UniversalDecoder().Decode(responseErrorBytes, nil, &metav1.Status{}); err == nil {
- if status, ok := obj.(*metav1.Status); ok {
- return nil, &apierrors.StatusError{ErrStatus: *status}
- }
- }
- responseError = string(responseErrorBytes)
- responseError = strings.TrimSpace(responseError)
- }
-
- return nil, fmt.Errorf("unable to upgrade connection: %s", responseError)
- }
-
- return NewClientConnectionWithPings(s.conn, s.pingPeriod)
-}
-
-// statusScheme is private scheme for the decoding here until someone fixes the TODO in NewConnection
-var statusScheme = runtime.NewScheme()
-
-// ParameterCodec knows about query parameters used with the meta v1 API spec.
-var statusCodecs = serializer.NewCodecFactory(statusScheme)
-
-func init() {
- statusScheme.AddUnversionedTypes(metav1.SchemeGroupVersion,
- &metav1.Status{},
- )
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade.go b/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade.go
deleted file mode 100644
index f17eb09e9..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade.go
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package spdy
-
-import (
- "bufio"
- "fmt"
- "io"
- "net"
- "net/http"
- "strings"
- "sync/atomic"
- "time"
-
- "k8s.io/apimachinery/pkg/util/httpstream"
- "k8s.io/apimachinery/pkg/util/runtime"
-)
-
-const HeaderSpdy31 = "SPDY/3.1"
-
-// responseUpgrader knows how to upgrade HTTP responses. It
-// implements the httpstream.ResponseUpgrader interface.
-type responseUpgrader struct {
- pingPeriod time.Duration
-}
-
-// connWrapper is used to wrap a hijacked connection and its bufio.Reader. All
-// calls will be handled directly by the underlying net.Conn with the exception
-// of Read and Close calls, which will consider data in the bufio.Reader. This
-// ensures that data already inside the used bufio.Reader instance is also
-// read.
-type connWrapper struct {
- net.Conn
- closed int32
- bufReader *bufio.Reader
-}
-
-func (w *connWrapper) Read(b []byte) (n int, err error) {
- if atomic.LoadInt32(&w.closed) == 1 {
- return 0, io.EOF
- }
- return w.bufReader.Read(b)
-}
-
-func (w *connWrapper) Close() error {
- err := w.Conn.Close()
- atomic.StoreInt32(&w.closed, 1)
- return err
-}
-
-// NewResponseUpgrader returns a new httpstream.ResponseUpgrader that is
-// capable of upgrading HTTP responses using SPDY/3.1 via the
-// spdystream package.
-func NewResponseUpgrader() httpstream.ResponseUpgrader {
- return NewResponseUpgraderWithPings(0)
-}
-
-// NewResponseUpgraderWithPings returns a new httpstream.ResponseUpgrader that
-// is capable of upgrading HTTP responses using SPDY/3.1 via the spdystream
-// package.
-//
-// If pingPeriod is non-zero, for each incoming connection a background
-// goroutine will send periodic Ping frames to the server. Use this to keep
-// idle connections through certain load balancers alive longer.
-func NewResponseUpgraderWithPings(pingPeriod time.Duration) httpstream.ResponseUpgrader {
- return responseUpgrader{pingPeriod: pingPeriod}
-}
-
-// UpgradeResponse upgrades an HTTP response to one that supports multiplexed
-// streams. newStreamHandler will be called synchronously whenever the
-// other end of the upgraded connection creates a new stream.
-func (u responseUpgrader) UpgradeResponse(w http.ResponseWriter, req *http.Request, newStreamHandler httpstream.NewStreamHandler) httpstream.Connection {
- connectionHeader := strings.ToLower(req.Header.Get(httpstream.HeaderConnection))
- upgradeHeader := strings.ToLower(req.Header.Get(httpstream.HeaderUpgrade))
- if !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) {
- errorMsg := fmt.Sprintf("unable to upgrade: missing upgrade headers in request: %#v", req.Header)
- http.Error(w, errorMsg, http.StatusBadRequest)
- return nil
- }
-
- hijacker, ok := w.(http.Hijacker)
- if !ok {
- errorMsg := fmt.Sprintf("unable to upgrade: unable to hijack response")
- http.Error(w, errorMsg, http.StatusInternalServerError)
- return nil
- }
-
- w.Header().Add(httpstream.HeaderConnection, httpstream.HeaderUpgrade)
- w.Header().Add(httpstream.HeaderUpgrade, HeaderSpdy31)
- w.WriteHeader(http.StatusSwitchingProtocols)
-
- conn, bufrw, err := hijacker.Hijack()
- if err != nil {
- runtime.HandleError(fmt.Errorf("unable to upgrade: error hijacking response: %v", err))
- return nil
- }
-
- connWithBuf := &connWrapper{Conn: conn, bufReader: bufrw.Reader}
- spdyConn, err := NewServerConnectionWithPings(connWithBuf, newStreamHandler, u.pingPeriod)
- if err != nil {
- runtime.HandleError(fmt.Errorf("unable to upgrade: error creating SPDY server connection: %v", err))
- return nil
- }
-
- return spdyConn
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/remotecommand/constants.go b/vendor/k8s.io/apimachinery/pkg/util/remotecommand/constants.go
deleted file mode 100644
index acfeb827c..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/remotecommand/constants.go
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
-Copyright 2016 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package remotecommand
-
-import (
- "time"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-)
-
-const (
- DefaultStreamCreationTimeout = 30 * time.Second
-
- // The SPDY subprotocol "channel.k8s.io" is used for remote command
- // attachment/execution. This represents the initial unversioned subprotocol,
- // which has the known bugs http://issues.k8s.io/13394 and
- // http://issues.k8s.io/13395.
- StreamProtocolV1Name = "channel.k8s.io"
-
- // The SPDY subprotocol "v2.channel.k8s.io" is used for remote command
- // attachment/execution. It is the second version of the subprotocol and
- // resolves the issues present in the first version.
- StreamProtocolV2Name = "v2.channel.k8s.io"
-
- // The SPDY subprotocol "v3.channel.k8s.io" is used for remote command
- // attachment/execution. It is the third version of the subprotocol and
- // adds support for resizing container terminals.
- StreamProtocolV3Name = "v3.channel.k8s.io"
-
- // The SPDY subprotocol "v4.channel.k8s.io" is used for remote command
- // attachment/execution. It is the 4th version of the subprotocol and
- // adds support for exit codes.
- StreamProtocolV4Name = "v4.channel.k8s.io"
-
- NonZeroExitCodeReason = metav1.StatusReason("NonZeroExitCode")
- ExitCodeCauseType = metav1.CauseType("ExitCode")
-)
-
-var SupportedStreamingProtocols = []string{StreamProtocolV4Name, StreamProtocolV3Name, StreamProtocolV2Name, StreamProtocolV1Name}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go b/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go
deleted file mode 100644
index 7fe706467..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go
+++ /dev/null
@@ -1,379 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package yaml
-
-import (
- "bufio"
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "io/ioutil"
- "strings"
- "unicode"
-
- jsonutil "k8s.io/apimachinery/pkg/util/json"
-
- "k8s.io/klog/v2"
- "sigs.k8s.io/yaml"
-)
-
-// Unmarshal unmarshals the given data
-// If v is a *map[string]interface{}, *[]interface{}, or *interface{} numbers
-// are converted to int64 or float64
-func Unmarshal(data []byte, v interface{}) error {
- preserveIntFloat := func(d *json.Decoder) *json.Decoder {
- d.UseNumber()
- return d
- }
- switch v := v.(type) {
- case *map[string]interface{}:
- if err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil {
- return err
- }
- return jsonutil.ConvertMapNumbers(*v, 0)
- case *[]interface{}:
- if err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil {
- return err
- }
- return jsonutil.ConvertSliceNumbers(*v, 0)
- case *interface{}:
- if err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil {
- return err
- }
- return jsonutil.ConvertInterfaceNumbers(v, 0)
- default:
- return yaml.Unmarshal(data, v)
- }
-}
-
-// ToJSON converts a single YAML document into a JSON document
-// or returns an error. If the document appears to be JSON the
-// YAML decoding path is not used (so that error messages are
-// JSON specific).
-func ToJSON(data []byte) ([]byte, error) {
- if hasJSONPrefix(data) {
- return data, nil
- }
- return yaml.YAMLToJSON(data)
-}
-
-// YAMLToJSONDecoder decodes YAML documents from an io.Reader by
-// separating individual documents. It first converts the YAML
-// body to JSON, then unmarshals the JSON.
-type YAMLToJSONDecoder struct {
- reader Reader
-}
-
-// NewYAMLToJSONDecoder decodes YAML documents from the provided
-// stream in chunks by converting each document (as defined by
-// the YAML spec) into its own chunk, converting it to JSON via
-// yaml.YAMLToJSON, and then passing it to json.Decoder.
-func NewYAMLToJSONDecoder(r io.Reader) *YAMLToJSONDecoder {
- reader := bufio.NewReader(r)
- return &YAMLToJSONDecoder{
- reader: NewYAMLReader(reader),
- }
-}
-
-// Decode reads a YAML document as JSON from the stream or returns
-// an error. The decoding rules match json.Unmarshal, not
-// yaml.Unmarshal.
-func (d *YAMLToJSONDecoder) Decode(into interface{}) error {
- bytes, err := d.reader.Read()
- if err != nil && err != io.EOF {
- return err
- }
-
- if len(bytes) != 0 {
- err := yaml.Unmarshal(bytes, into)
- if err != nil {
- return YAMLSyntaxError{err}
- }
- }
- return err
-}
-
-// YAMLDecoder reads chunks of objects and returns ErrShortBuffer if
-// the data is not sufficient.
-type YAMLDecoder struct {
- r io.ReadCloser
- scanner *bufio.Scanner
- remaining []byte
-}
-
-// NewDocumentDecoder decodes YAML documents from the provided
-// stream in chunks by converting each document (as defined by
-// the YAML spec) into its own chunk. io.ErrShortBuffer will be
-// returned if the entire buffer could not be read to assist
-// the caller in framing the chunk.
-func NewDocumentDecoder(r io.ReadCloser) io.ReadCloser {
- scanner := bufio.NewScanner(r)
- // the size of initial allocation for buffer 4k
- buf := make([]byte, 4*1024)
- // the maximum size used to buffer a token 5M
- scanner.Buffer(buf, 5*1024*1024)
- scanner.Split(splitYAMLDocument)
- return &YAMLDecoder{
- r: r,
- scanner: scanner,
- }
-}
-
-// Read reads the previous slice into the buffer, or attempts to read
-// the next chunk.
-// TODO: switch to readline approach.
-func (d *YAMLDecoder) Read(data []byte) (n int, err error) {
- left := len(d.remaining)
- if left == 0 {
- // return the next chunk from the stream
- if !d.scanner.Scan() {
- err := d.scanner.Err()
- if err == nil {
- err = io.EOF
- }
- return 0, err
- }
- out := d.scanner.Bytes()
- d.remaining = out
- left = len(out)
- }
-
- // fits within data
- if left <= len(data) {
- copy(data, d.remaining)
- d.remaining = nil
- return left, nil
- }
-
- // caller will need to reread
- copy(data, d.remaining[:len(data)])
- d.remaining = d.remaining[len(data):]
- return len(data), io.ErrShortBuffer
-}
-
-func (d *YAMLDecoder) Close() error {
- return d.r.Close()
-}
-
-const yamlSeparator = "\n---"
-const separator = "---"
-
-// splitYAMLDocument is a bufio.SplitFunc for splitting YAML streams into individual documents.
-func splitYAMLDocument(data []byte, atEOF bool) (advance int, token []byte, err error) {
- if atEOF && len(data) == 0 {
- return 0, nil, nil
- }
- sep := len([]byte(yamlSeparator))
- if i := bytes.Index(data, []byte(yamlSeparator)); i >= 0 {
- // We have a potential document terminator
- i += sep
- after := data[i:]
- if len(after) == 0 {
- // we can't read any more characters
- if atEOF {
- return len(data), data[:len(data)-sep], nil
- }
- return 0, nil, nil
- }
- if j := bytes.IndexByte(after, '\n'); j >= 0 {
- return i + j + 1, data[0 : i-sep], nil
- }
- return 0, nil, nil
- }
- // If we're at EOF, we have a final, non-terminated line. Return it.
- if atEOF {
- return len(data), data, nil
- }
- // Request more data.
- return 0, nil, nil
-}
-
-// decoder is a convenience interface for Decode.
-type decoder interface {
- Decode(into interface{}) error
-}
-
-// YAMLOrJSONDecoder attempts to decode a stream of JSON documents or
-// YAML documents by sniffing for a leading { character.
-type YAMLOrJSONDecoder struct {
- r io.Reader
- bufferSize int
-
- decoder decoder
- rawData []byte
-}
-
-type JSONSyntaxError struct {
- Line int
- Err error
-}
-
-func (e JSONSyntaxError) Error() string {
- return fmt.Sprintf("json: line %d: %s", e.Line, e.Err.Error())
-}
-
-type YAMLSyntaxError struct {
- err error
-}
-
-func (e YAMLSyntaxError) Error() string {
- return e.err.Error()
-}
-
-// NewYAMLOrJSONDecoder returns a decoder that will process YAML documents
-// or JSON documents from the given reader as a stream. bufferSize determines
-// how far into the stream the decoder will look to figure out whether this
-// is a JSON stream (has whitespace followed by an open brace).
-func NewYAMLOrJSONDecoder(r io.Reader, bufferSize int) *YAMLOrJSONDecoder {
- return &YAMLOrJSONDecoder{
- r: r,
- bufferSize: bufferSize,
- }
-}
-
-// Decode unmarshals the next object from the underlying stream into the
-// provide object, or returns an error.
-func (d *YAMLOrJSONDecoder) Decode(into interface{}) error {
- if d.decoder == nil {
- buffer, origData, isJSON := GuessJSONStream(d.r, d.bufferSize)
- if isJSON {
- d.decoder = json.NewDecoder(buffer)
- d.rawData = origData
- } else {
- d.decoder = NewYAMLToJSONDecoder(buffer)
- }
- }
- err := d.decoder.Decode(into)
- if jsonDecoder, ok := d.decoder.(*json.Decoder); ok {
- if syntax, ok := err.(*json.SyntaxError); ok {
- data, readErr := ioutil.ReadAll(jsonDecoder.Buffered())
- if readErr != nil {
- klog.V(4).Infof("reading stream failed: %v", readErr)
- }
- js := string(data)
-
- // if contents from io.Reader are not complete,
- // use the original raw data to prevent panic
- if int64(len(js)) <= syntax.Offset {
- js = string(d.rawData)
- }
-
- start := strings.LastIndex(js[:syntax.Offset], "\n") + 1
- line := strings.Count(js[:start], "\n")
- return JSONSyntaxError{
- Line: line,
- Err: fmt.Errorf(syntax.Error()),
- }
- }
- }
- return err
-}
-
-type Reader interface {
- Read() ([]byte, error)
-}
-
-type YAMLReader struct {
- reader Reader
-}
-
-func NewYAMLReader(r *bufio.Reader) *YAMLReader {
- return &YAMLReader{
- reader: &LineReader{reader: r},
- }
-}
-
-// Read returns a full YAML document.
-func (r *YAMLReader) Read() ([]byte, error) {
- var buffer bytes.Buffer
- for {
- line, err := r.reader.Read()
- if err != nil && err != io.EOF {
- return nil, err
- }
-
- sep := len([]byte(separator))
- if i := bytes.Index(line, []byte(separator)); i == 0 {
- // We have a potential document terminator
- i += sep
- after := line[i:]
- if len(strings.TrimRightFunc(string(after), unicode.IsSpace)) == 0 {
- if buffer.Len() != 0 {
- return buffer.Bytes(), nil
- }
- if err == io.EOF {
- return nil, err
- }
- }
- }
- if err == io.EOF {
- if buffer.Len() != 0 {
- // If we're at EOF, we have a final, non-terminated line. Return it.
- return buffer.Bytes(), nil
- }
- return nil, err
- }
- buffer.Write(line)
- }
-}
-
-type LineReader struct {
- reader *bufio.Reader
-}
-
-// Read returns a single line (with '\n' ended) from the underlying reader.
-// An error is returned iff there is an error with the underlying reader.
-func (r *LineReader) Read() ([]byte, error) {
- var (
- isPrefix bool = true
- err error = nil
- line []byte
- buffer bytes.Buffer
- )
-
- for isPrefix && err == nil {
- line, isPrefix, err = r.reader.ReadLine()
- buffer.Write(line)
- }
- buffer.WriteByte('\n')
- return buffer.Bytes(), err
-}
-
-// GuessJSONStream scans the provided reader up to size, looking
-// for an open brace indicating this is JSON. It will return the
-// bufio.Reader it creates for the consumer.
-func GuessJSONStream(r io.Reader, size int) (io.Reader, []byte, bool) {
- buffer := bufio.NewReaderSize(r, size)
- b, _ := buffer.Peek(size)
- return buffer, b, hasJSONPrefix(b)
-}
-
-var jsonPrefix = []byte("{")
-
-// hasJSONPrefix returns true if the provided buffer appears to start with
-// a JSON open brace.
-func hasJSONPrefix(buf []byte) bool {
- return hasPrefix(buf, jsonPrefix)
-}
-
-// Return true if the first non-whitespace bytes in buf is
-// prefix.
-func hasPrefix(buf []byte, prefix []byte) bool {
- trim := bytes.TrimLeftFunc(buf, unicode.IsSpace)
- return bytes.HasPrefix(trim, prefix)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/version/doc.go b/vendor/k8s.io/apimachinery/pkg/version/doc.go
deleted file mode 100644
index 29574fd6d..000000000
--- a/vendor/k8s.io/apimachinery/pkg/version/doc.go
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// +k8s:openapi-gen=true
-
-// Package version supplies the type for version information collected at build time.
-package version // import "k8s.io/apimachinery/pkg/version"
diff --git a/vendor/k8s.io/apimachinery/pkg/version/helpers.go b/vendor/k8s.io/apimachinery/pkg/version/helpers.go
deleted file mode 100644
index 5e041d6f3..000000000
--- a/vendor/k8s.io/apimachinery/pkg/version/helpers.go
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package version
-
-import (
- "regexp"
- "strconv"
- "strings"
-)
-
-type versionType int
-
-const (
- // Bigger the version type number, higher priority it is
- versionTypeAlpha versionType = iota
- versionTypeBeta
- versionTypeGA
-)
-
-var kubeVersionRegex = regexp.MustCompile("^v([\\d]+)(?:(alpha|beta)([\\d]+))?$")
-
-func parseKubeVersion(v string) (majorVersion int, vType versionType, minorVersion int, ok bool) {
- var err error
- submatches := kubeVersionRegex.FindStringSubmatch(v)
- if len(submatches) != 4 {
- return 0, 0, 0, false
- }
- switch submatches[2] {
- case "alpha":
- vType = versionTypeAlpha
- case "beta":
- vType = versionTypeBeta
- case "":
- vType = versionTypeGA
- default:
- return 0, 0, 0, false
- }
- if majorVersion, err = strconv.Atoi(submatches[1]); err != nil {
- return 0, 0, 0, false
- }
- if vType != versionTypeGA {
- if minorVersion, err = strconv.Atoi(submatches[3]); err != nil {
- return 0, 0, 0, false
- }
- }
- return majorVersion, vType, minorVersion, true
-}
-
-// CompareKubeAwareVersionStrings compares two kube-like version strings.
-// Kube-like version strings are starting with a v, followed by a major version, optional "alpha" or "beta" strings
-// followed by a minor version (e.g. v1, v2beta1). Versions will be sorted based on GA/alpha/beta first and then major
-// and minor versions. e.g. v2, v1, v1beta2, v1beta1, v1alpha1.
-func CompareKubeAwareVersionStrings(v1, v2 string) int {
- if v1 == v2 {
- return 0
- }
- v1major, v1type, v1minor, ok1 := parseKubeVersion(v1)
- v2major, v2type, v2minor, ok2 := parseKubeVersion(v2)
- switch {
- case !ok1 && !ok2:
- return strings.Compare(v2, v1)
- case !ok1 && ok2:
- return -1
- case ok1 && !ok2:
- return 1
- }
- if v1type != v2type {
- return int(v1type) - int(v2type)
- }
- if v1major != v2major {
- return v1major - v2major
- }
- return v1minor - v2minor
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/version/types.go b/vendor/k8s.io/apimachinery/pkg/version/types.go
deleted file mode 100644
index 72727b503..000000000
--- a/vendor/k8s.io/apimachinery/pkg/version/types.go
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package version
-
-// Info contains versioning information.
-// TODO: Add []string of api versions supported? It's still unclear
-// how we'll want to distribute that information.
-type Info struct {
- Major string `json:"major"`
- Minor string `json:"minor"`
- GitVersion string `json:"gitVersion"`
- GitCommit string `json:"gitCommit"`
- GitTreeState string `json:"gitTreeState"`
- BuildDate string `json:"buildDate"`
- GoVersion string `json:"goVersion"`
- Compiler string `json:"compiler"`
- Platform string `json:"platform"`
-}
-
-// String returns info as a human-friendly version string.
-func (info Info) String() string {
- return info.GitVersion
-}
diff --git a/vendor/k8s.io/apimachinery/third_party/forked/golang/netutil/addr.go b/vendor/k8s.io/apimachinery/third_party/forked/golang/netutil/addr.go
deleted file mode 100644
index c70f431c2..000000000
--- a/vendor/k8s.io/apimachinery/third_party/forked/golang/netutil/addr.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package netutil
-
-import (
- "net/url"
- "strings"
-)
-
-// FROM: http://golang.org/src/net/http/client.go
-// Given a string of the form "host", "host:port", or "[ipv6::address]:port",
-// return true if the string includes a port.
-func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") }
-
-// FROM: http://golang.org/src/net/http/transport.go
-var portMap = map[string]string{
- "http": "80",
- "https": "443",
-}
-
-// FROM: http://golang.org/src/net/http/transport.go
-// canonicalAddr returns url.Host but always with a ":port" suffix
-func CanonicalAddr(url *url.URL) string {
- addr := url.Host
- if !hasPort(addr) {
- return addr + ":" + portMap[url.Scheme]
- }
- return addr
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/OWNERS b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/OWNERS
deleted file mode 100644
index e0ec62deb..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/OWNERS
+++ /dev/null
@@ -1,9 +0,0 @@
-# See the OWNERS docs at https://go.k8s.io/owners
-
-# approval on api packages bubbles to api-approvers
-reviewers:
-- sig-auth-authenticators-approvers
-- sig-auth-authenticators-reviewers
-labels:
-- sig/auth
-
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/doc.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/doc.go
deleted file mode 100644
index b99459757..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/doc.go
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// +k8s:deepcopy-gen=package
-// +groupName=client.authentication.k8s.io
-
-package clientauthentication // import "k8s.io/client-go/pkg/apis/clientauthentication"
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/register.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/register.go
deleted file mode 100644
index e4fbc3ea9..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/register.go
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package clientauthentication
-
-import (
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// GroupName is the group name use in this package
-const GroupName = "client.authentication.k8s.io"
-
-// SchemeGroupVersion is group version used to register these objects
-var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: runtime.APIVersionInternal}
-
-// Kind takes an unqualified kind and returns a Group qualified GroupKind
-func Kind(kind string) schema.GroupKind {
- return SchemeGroupVersion.WithKind(kind).GroupKind()
-}
-
-// Resource takes an unqualified resource and returns a Group qualified GroupResource
-func Resource(resource string) schema.GroupResource {
- return SchemeGroupVersion.WithResource(resource).GroupResource()
-}
-
-var (
- SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
- AddToScheme = SchemeBuilder.AddToScheme
-)
-
-func addKnownTypes(scheme *runtime.Scheme) error {
- scheme.AddKnownTypes(SchemeGroupVersion,
- &ExecCredential{},
- )
- return nil
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/types.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/types.go
deleted file mode 100644
index 6fb53cecf..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/types.go
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package clientauthentication
-
-import (
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-)
-
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-
-// ExecCredentials is used by exec-based plugins to communicate credentials to
-// HTTP transports.
-type ExecCredential struct {
- metav1.TypeMeta
-
- // Spec holds information passed to the plugin by the transport. This contains
- // request and runtime specific information, such as if the session is interactive.
- Spec ExecCredentialSpec
-
- // Status is filled in by the plugin and holds the credentials that the transport
- // should use to contact the API.
- // +optional
- Status *ExecCredentialStatus
-}
-
-// ExecCredenitalSpec holds request and runtime specific information provided by
-// the transport.
-type ExecCredentialSpec struct {
- // Response is populated when the transport encounters HTTP status codes, such as 401,
- // suggesting previous credentials were invalid.
- // +optional
- Response *Response
-
- // Interactive is true when the transport detects the command is being called from an
- // interactive prompt.
- // +optional
- Interactive bool
-}
-
-// ExecCredentialStatus holds credentials for the transport to use.
-type ExecCredentialStatus struct {
- // ExpirationTimestamp indicates a time when the provided credentials expire.
- // +optional
- ExpirationTimestamp *metav1.Time
- // Token is a bearer token used by the client for request authentication.
- // +optional
- Token string
- // PEM-encoded client TLS certificate.
- // +optional
- ClientCertificateData string
- // PEM-encoded client TLS private key.
- // +optional
- ClientKeyData string
-}
-
-// Response defines metadata about a failed request, including HTTP status code and
-// response headers.
-type Response struct {
- // Headers holds HTTP headers returned by the server.
- Header map[string][]string
- // Code is the HTTP status code returned by the server.
- Code int32
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/doc.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/doc.go
deleted file mode 100644
index 19ab77614..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/doc.go
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// +k8s:deepcopy-gen=package
-// +k8s:conversion-gen=k8s.io/client-go/pkg/apis/clientauthentication
-// +k8s:openapi-gen=true
-// +k8s:defaulter-gen=TypeMeta
-
-// +groupName=client.authentication.k8s.io
-
-package v1alpha1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1"
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/register.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/register.go
deleted file mode 100644
index 2acd13dea..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/register.go
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package v1alpha1
-
-import (
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// GroupName is the group name use in this package
-const GroupName = "client.authentication.k8s.io"
-
-// SchemeGroupVersion is group version used to register these objects
-var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"}
-
-// Resource takes an unqualified resource and returns a Group qualified GroupResource
-func Resource(resource string) schema.GroupResource {
- return SchemeGroupVersion.WithResource(resource).GroupResource()
-}
-
-var (
- SchemeBuilder runtime.SchemeBuilder
- localSchemeBuilder = &SchemeBuilder
- AddToScheme = localSchemeBuilder.AddToScheme
-)
-
-func init() {
- // We only register manually written functions here. The registration of the
- // generated functions takes place in the generated files. The separation
- // makes the code compile even when the generated files are missing.
- localSchemeBuilder.Register(addKnownTypes)
-}
-
-func addKnownTypes(scheme *runtime.Scheme) error {
- scheme.AddKnownTypes(SchemeGroupVersion,
- &ExecCredential{},
- )
- metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
- return nil
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/types.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/types.go
deleted file mode 100644
index c714e2457..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/types.go
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package v1alpha1
-
-import (
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-)
-
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-
-// ExecCredential is used by exec-based plugins to communicate credentials to
-// HTTP transports.
-type ExecCredential struct {
- metav1.TypeMeta `json:",inline"`
-
- // Spec holds information passed to the plugin by the transport. This contains
- // request and runtime specific information, such as if the session is interactive.
- Spec ExecCredentialSpec `json:"spec,omitempty"`
-
- // Status is filled in by the plugin and holds the credentials that the transport
- // should use to contact the API.
- // +optional
- Status *ExecCredentialStatus `json:"status,omitempty"`
-}
-
-// ExecCredenitalSpec holds request and runtime specific information provided by
-// the transport.
-type ExecCredentialSpec struct {
- // Response is populated when the transport encounters HTTP status codes, such as 401,
- // suggesting previous credentials were invalid.
- // +optional
- Response *Response `json:"response,omitempty"`
-
- // Interactive is true when the transport detects the command is being called from an
- // interactive prompt.
- // +optional
- Interactive bool `json:"interactive,omitempty"`
-}
-
-// ExecCredentialStatus holds credentials for the transport to use.
-//
-// Token and ClientKeyData are sensitive fields. This data should only be
-// transmitted in-memory between client and exec plugin process. Exec plugin
-// itself should at least be protected via file permissions.
-type ExecCredentialStatus struct {
- // ExpirationTimestamp indicates a time when the provided credentials expire.
- // +optional
- ExpirationTimestamp *metav1.Time `json:"expirationTimestamp,omitempty"`
- // Token is a bearer token used by the client for request authentication.
- Token string `json:"token,omitempty"`
- // PEM-encoded client TLS certificates (including intermediates, if any).
- ClientCertificateData string `json:"clientCertificateData,omitempty"`
- // PEM-encoded private key for the above certificate.
- ClientKeyData string `json:"clientKeyData,omitempty"`
-}
-
-// Response defines metadata about a failed request, including HTTP status code and
-// response headers.
-type Response struct {
- // Header holds HTTP headers returned by the server.
- Header map[string][]string `json:"header,omitempty"`
- // Code is the HTTP status code returned by the server.
- Code int32 `json:"code,omitempty"`
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.conversion.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.conversion.go
deleted file mode 100644
index 461c20b29..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.conversion.go
+++ /dev/null
@@ -1,176 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Code generated by conversion-gen. DO NOT EDIT.
-
-package v1alpha1
-
-import (
- unsafe "unsafe"
-
- v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- conversion "k8s.io/apimachinery/pkg/conversion"
- runtime "k8s.io/apimachinery/pkg/runtime"
- clientauthentication "k8s.io/client-go/pkg/apis/clientauthentication"
-)
-
-func init() {
- localSchemeBuilder.Register(RegisterConversions)
-}
-
-// RegisterConversions adds conversion functions to the given scheme.
-// Public to allow building arbitrary schemes.
-func RegisterConversions(s *runtime.Scheme) error {
- if err := s.AddGeneratedConversionFunc((*ExecCredential)(nil), (*clientauthentication.ExecCredential)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_v1alpha1_ExecCredential_To_clientauthentication_ExecCredential(a.(*ExecCredential), b.(*clientauthentication.ExecCredential), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*clientauthentication.ExecCredential)(nil), (*ExecCredential)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_clientauthentication_ExecCredential_To_v1alpha1_ExecCredential(a.(*clientauthentication.ExecCredential), b.(*ExecCredential), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*ExecCredentialSpec)(nil), (*clientauthentication.ExecCredentialSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_v1alpha1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(a.(*ExecCredentialSpec), b.(*clientauthentication.ExecCredentialSpec), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*clientauthentication.ExecCredentialSpec)(nil), (*ExecCredentialSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_clientauthentication_ExecCredentialSpec_To_v1alpha1_ExecCredentialSpec(a.(*clientauthentication.ExecCredentialSpec), b.(*ExecCredentialSpec), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*ExecCredentialStatus)(nil), (*clientauthentication.ExecCredentialStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_v1alpha1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus(a.(*ExecCredentialStatus), b.(*clientauthentication.ExecCredentialStatus), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*clientauthentication.ExecCredentialStatus)(nil), (*ExecCredentialStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_clientauthentication_ExecCredentialStatus_To_v1alpha1_ExecCredentialStatus(a.(*clientauthentication.ExecCredentialStatus), b.(*ExecCredentialStatus), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*Response)(nil), (*clientauthentication.Response)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_v1alpha1_Response_To_clientauthentication_Response(a.(*Response), b.(*clientauthentication.Response), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*clientauthentication.Response)(nil), (*Response)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_clientauthentication_Response_To_v1alpha1_Response(a.(*clientauthentication.Response), b.(*Response), scope)
- }); err != nil {
- return err
- }
- return nil
-}
-
-func autoConvert_v1alpha1_ExecCredential_To_clientauthentication_ExecCredential(in *ExecCredential, out *clientauthentication.ExecCredential, s conversion.Scope) error {
- if err := Convert_v1alpha1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(&in.Spec, &out.Spec, s); err != nil {
- return err
- }
- out.Status = (*clientauthentication.ExecCredentialStatus)(unsafe.Pointer(in.Status))
- return nil
-}
-
-// Convert_v1alpha1_ExecCredential_To_clientauthentication_ExecCredential is an autogenerated conversion function.
-func Convert_v1alpha1_ExecCredential_To_clientauthentication_ExecCredential(in *ExecCredential, out *clientauthentication.ExecCredential, s conversion.Scope) error {
- return autoConvert_v1alpha1_ExecCredential_To_clientauthentication_ExecCredential(in, out, s)
-}
-
-func autoConvert_clientauthentication_ExecCredential_To_v1alpha1_ExecCredential(in *clientauthentication.ExecCredential, out *ExecCredential, s conversion.Scope) error {
- if err := Convert_clientauthentication_ExecCredentialSpec_To_v1alpha1_ExecCredentialSpec(&in.Spec, &out.Spec, s); err != nil {
- return err
- }
- out.Status = (*ExecCredentialStatus)(unsafe.Pointer(in.Status))
- return nil
-}
-
-// Convert_clientauthentication_ExecCredential_To_v1alpha1_ExecCredential is an autogenerated conversion function.
-func Convert_clientauthentication_ExecCredential_To_v1alpha1_ExecCredential(in *clientauthentication.ExecCredential, out *ExecCredential, s conversion.Scope) error {
- return autoConvert_clientauthentication_ExecCredential_To_v1alpha1_ExecCredential(in, out, s)
-}
-
-func autoConvert_v1alpha1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(in *ExecCredentialSpec, out *clientauthentication.ExecCredentialSpec, s conversion.Scope) error {
- out.Response = (*clientauthentication.Response)(unsafe.Pointer(in.Response))
- out.Interactive = in.Interactive
- return nil
-}
-
-// Convert_v1alpha1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec is an autogenerated conversion function.
-func Convert_v1alpha1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(in *ExecCredentialSpec, out *clientauthentication.ExecCredentialSpec, s conversion.Scope) error {
- return autoConvert_v1alpha1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(in, out, s)
-}
-
-func autoConvert_clientauthentication_ExecCredentialSpec_To_v1alpha1_ExecCredentialSpec(in *clientauthentication.ExecCredentialSpec, out *ExecCredentialSpec, s conversion.Scope) error {
- out.Response = (*Response)(unsafe.Pointer(in.Response))
- out.Interactive = in.Interactive
- return nil
-}
-
-// Convert_clientauthentication_ExecCredentialSpec_To_v1alpha1_ExecCredentialSpec is an autogenerated conversion function.
-func Convert_clientauthentication_ExecCredentialSpec_To_v1alpha1_ExecCredentialSpec(in *clientauthentication.ExecCredentialSpec, out *ExecCredentialSpec, s conversion.Scope) error {
- return autoConvert_clientauthentication_ExecCredentialSpec_To_v1alpha1_ExecCredentialSpec(in, out, s)
-}
-
-func autoConvert_v1alpha1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus(in *ExecCredentialStatus, out *clientauthentication.ExecCredentialStatus, s conversion.Scope) error {
- out.ExpirationTimestamp = (*v1.Time)(unsafe.Pointer(in.ExpirationTimestamp))
- out.Token = in.Token
- out.ClientCertificateData = in.ClientCertificateData
- out.ClientKeyData = in.ClientKeyData
- return nil
-}
-
-// Convert_v1alpha1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus is an autogenerated conversion function.
-func Convert_v1alpha1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus(in *ExecCredentialStatus, out *clientauthentication.ExecCredentialStatus, s conversion.Scope) error {
- return autoConvert_v1alpha1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus(in, out, s)
-}
-
-func autoConvert_clientauthentication_ExecCredentialStatus_To_v1alpha1_ExecCredentialStatus(in *clientauthentication.ExecCredentialStatus, out *ExecCredentialStatus, s conversion.Scope) error {
- out.ExpirationTimestamp = (*v1.Time)(unsafe.Pointer(in.ExpirationTimestamp))
- out.Token = in.Token
- out.ClientCertificateData = in.ClientCertificateData
- out.ClientKeyData = in.ClientKeyData
- return nil
-}
-
-// Convert_clientauthentication_ExecCredentialStatus_To_v1alpha1_ExecCredentialStatus is an autogenerated conversion function.
-func Convert_clientauthentication_ExecCredentialStatus_To_v1alpha1_ExecCredentialStatus(in *clientauthentication.ExecCredentialStatus, out *ExecCredentialStatus, s conversion.Scope) error {
- return autoConvert_clientauthentication_ExecCredentialStatus_To_v1alpha1_ExecCredentialStatus(in, out, s)
-}
-
-func autoConvert_v1alpha1_Response_To_clientauthentication_Response(in *Response, out *clientauthentication.Response, s conversion.Scope) error {
- out.Header = *(*map[string][]string)(unsafe.Pointer(&in.Header))
- out.Code = in.Code
- return nil
-}
-
-// Convert_v1alpha1_Response_To_clientauthentication_Response is an autogenerated conversion function.
-func Convert_v1alpha1_Response_To_clientauthentication_Response(in *Response, out *clientauthentication.Response, s conversion.Scope) error {
- return autoConvert_v1alpha1_Response_To_clientauthentication_Response(in, out, s)
-}
-
-func autoConvert_clientauthentication_Response_To_v1alpha1_Response(in *clientauthentication.Response, out *Response, s conversion.Scope) error {
- out.Header = *(*map[string][]string)(unsafe.Pointer(&in.Header))
- out.Code = in.Code
- return nil
-}
-
-// Convert_clientauthentication_Response_To_v1alpha1_Response is an autogenerated conversion function.
-func Convert_clientauthentication_Response_To_v1alpha1_Response(in *clientauthentication.Response, out *Response, s conversion.Scope) error {
- return autoConvert_clientauthentication_Response_To_v1alpha1_Response(in, out, s)
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.deepcopy.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.deepcopy.go
deleted file mode 100644
index a73d31b3f..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.deepcopy.go
+++ /dev/null
@@ -1,128 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Code generated by deepcopy-gen. DO NOT EDIT.
-
-package v1alpha1
-
-import (
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ExecCredential) DeepCopyInto(out *ExecCredential) {
- *out = *in
- out.TypeMeta = in.TypeMeta
- in.Spec.DeepCopyInto(&out.Spec)
- if in.Status != nil {
- in, out := &in.Status, &out.Status
- *out = new(ExecCredentialStatus)
- (*in).DeepCopyInto(*out)
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecCredential.
-func (in *ExecCredential) DeepCopy() *ExecCredential {
- if in == nil {
- return nil
- }
- out := new(ExecCredential)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *ExecCredential) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- }
- return nil
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ExecCredentialSpec) DeepCopyInto(out *ExecCredentialSpec) {
- *out = *in
- if in.Response != nil {
- in, out := &in.Response, &out.Response
- *out = new(Response)
- (*in).DeepCopyInto(*out)
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecCredentialSpec.
-func (in *ExecCredentialSpec) DeepCopy() *ExecCredentialSpec {
- if in == nil {
- return nil
- }
- out := new(ExecCredentialSpec)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ExecCredentialStatus) DeepCopyInto(out *ExecCredentialStatus) {
- *out = *in
- if in.ExpirationTimestamp != nil {
- in, out := &in.ExpirationTimestamp, &out.ExpirationTimestamp
- *out = (*in).DeepCopy()
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecCredentialStatus.
-func (in *ExecCredentialStatus) DeepCopy() *ExecCredentialStatus {
- if in == nil {
- return nil
- }
- out := new(ExecCredentialStatus)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *Response) DeepCopyInto(out *Response) {
- *out = *in
- if in.Header != nil {
- in, out := &in.Header, &out.Header
- *out = make(map[string][]string, len(*in))
- for key, val := range *in {
- var outVal []string
- if val == nil {
- (*out)[key] = nil
- } else {
- in, out := &val, &outVal
- *out = make([]string, len(*in))
- copy(*out, *in)
- }
- (*out)[key] = outVal
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Response.
-func (in *Response) DeepCopy() *Response {
- if in == nil {
- return nil
- }
- out := new(Response)
- in.DeepCopyInto(out)
- return out
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.defaults.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.defaults.go
deleted file mode 100644
index dd621a3ac..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1/zz_generated.defaults.go
+++ /dev/null
@@ -1,32 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Code generated by defaulter-gen. DO NOT EDIT.
-
-package v1alpha1
-
-import (
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-// RegisterDefaults adds defaulters functions to the given scheme.
-// Public to allow building arbitrary schemes.
-// All generated defaulters are covering - they call all nested defaulters.
-func RegisterDefaults(scheme *runtime.Scheme) error {
- return nil
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/conversion.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/conversion.go
deleted file mode 100644
index f543806ac..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/conversion.go
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package v1beta1
-
-import (
- conversion "k8s.io/apimachinery/pkg/conversion"
- clientauthentication "k8s.io/client-go/pkg/apis/clientauthentication"
-)
-
-func Convert_clientauthentication_ExecCredentialSpec_To_v1beta1_ExecCredentialSpec(in *clientauthentication.ExecCredentialSpec, out *ExecCredentialSpec, s conversion.Scope) error {
- return nil
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/doc.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/doc.go
deleted file mode 100644
index 22d1c588b..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/doc.go
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// +k8s:deepcopy-gen=package
-// +k8s:conversion-gen=k8s.io/client-go/pkg/apis/clientauthentication
-// +k8s:openapi-gen=true
-// +k8s:defaulter-gen=TypeMeta
-
-// +groupName=client.authentication.k8s.io
-
-package v1beta1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1"
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/register.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/register.go
deleted file mode 100644
index 0bb92f16a..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/register.go
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package v1beta1
-
-import (
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// GroupName is the group name use in this package
-const GroupName = "client.authentication.k8s.io"
-
-// SchemeGroupVersion is group version used to register these objects
-var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1beta1"}
-
-// Resource takes an unqualified resource and returns a Group qualified GroupResource
-func Resource(resource string) schema.GroupResource {
- return SchemeGroupVersion.WithResource(resource).GroupResource()
-}
-
-var (
- SchemeBuilder runtime.SchemeBuilder
- localSchemeBuilder = &SchemeBuilder
- AddToScheme = localSchemeBuilder.AddToScheme
-)
-
-func init() {
- // We only register manually written functions here. The registration of the
- // generated functions takes place in the generated files. The separation
- // makes the code compile even when the generated files are missing.
- localSchemeBuilder.Register(addKnownTypes)
-}
-
-func addKnownTypes(scheme *runtime.Scheme) error {
- scheme.AddKnownTypes(SchemeGroupVersion,
- &ExecCredential{},
- )
- metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
- return nil
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/types.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/types.go
deleted file mode 100644
index d6e267452..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/types.go
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package v1beta1
-
-import (
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-)
-
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-
-// ExecCredentials is used by exec-based plugins to communicate credentials to
-// HTTP transports.
-type ExecCredential struct {
- metav1.TypeMeta `json:",inline"`
-
- // Spec holds information passed to the plugin by the transport. This contains
- // request and runtime specific information, such as if the session is interactive.
- Spec ExecCredentialSpec `json:"spec,omitempty"`
-
- // Status is filled in by the plugin and holds the credentials that the transport
- // should use to contact the API.
- // +optional
- Status *ExecCredentialStatus `json:"status,omitempty"`
-}
-
-// ExecCredenitalSpec holds request and runtime specific information provided by
-// the transport.
-type ExecCredentialSpec struct{}
-
-// ExecCredentialStatus holds credentials for the transport to use.
-//
-// Token and ClientKeyData are sensitive fields. This data should only be
-// transmitted in-memory between client and exec plugin process. Exec plugin
-// itself should at least be protected via file permissions.
-type ExecCredentialStatus struct {
- // ExpirationTimestamp indicates a time when the provided credentials expire.
- // +optional
- ExpirationTimestamp *metav1.Time `json:"expirationTimestamp,omitempty"`
- // Token is a bearer token used by the client for request authentication.
- Token string `json:"token,omitempty"`
- // PEM-encoded client TLS certificates (including intermediates, if any).
- ClientCertificateData string `json:"clientCertificateData,omitempty"`
- // PEM-encoded private key for the above certificate.
- ClientKeyData string `json:"clientKeyData,omitempty"`
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.conversion.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.conversion.go
deleted file mode 100644
index 94ef4b733..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.conversion.go
+++ /dev/null
@@ -1,142 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Code generated by conversion-gen. DO NOT EDIT.
-
-package v1beta1
-
-import (
- unsafe "unsafe"
-
- v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- conversion "k8s.io/apimachinery/pkg/conversion"
- runtime "k8s.io/apimachinery/pkg/runtime"
- clientauthentication "k8s.io/client-go/pkg/apis/clientauthentication"
-)
-
-func init() {
- localSchemeBuilder.Register(RegisterConversions)
-}
-
-// RegisterConversions adds conversion functions to the given scheme.
-// Public to allow building arbitrary schemes.
-func RegisterConversions(s *runtime.Scheme) error {
- if err := s.AddGeneratedConversionFunc((*ExecCredential)(nil), (*clientauthentication.ExecCredential)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_v1beta1_ExecCredential_To_clientauthentication_ExecCredential(a.(*ExecCredential), b.(*clientauthentication.ExecCredential), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*clientauthentication.ExecCredential)(nil), (*ExecCredential)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_clientauthentication_ExecCredential_To_v1beta1_ExecCredential(a.(*clientauthentication.ExecCredential), b.(*ExecCredential), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*ExecCredentialSpec)(nil), (*clientauthentication.ExecCredentialSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_v1beta1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(a.(*ExecCredentialSpec), b.(*clientauthentication.ExecCredentialSpec), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*clientauthentication.ExecCredentialSpec)(nil), (*ExecCredentialSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_clientauthentication_ExecCredentialSpec_To_v1beta1_ExecCredentialSpec(a.(*clientauthentication.ExecCredentialSpec), b.(*ExecCredentialSpec), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*ExecCredentialStatus)(nil), (*clientauthentication.ExecCredentialStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_v1beta1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus(a.(*ExecCredentialStatus), b.(*clientauthentication.ExecCredentialStatus), scope)
- }); err != nil {
- return err
- }
- if err := s.AddGeneratedConversionFunc((*clientauthentication.ExecCredentialStatus)(nil), (*ExecCredentialStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_clientauthentication_ExecCredentialStatus_To_v1beta1_ExecCredentialStatus(a.(*clientauthentication.ExecCredentialStatus), b.(*ExecCredentialStatus), scope)
- }); err != nil {
- return err
- }
- if err := s.AddConversionFunc((*clientauthentication.ExecCredentialSpec)(nil), (*ExecCredentialSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
- return Convert_clientauthentication_ExecCredentialSpec_To_v1beta1_ExecCredentialSpec(a.(*clientauthentication.ExecCredentialSpec), b.(*ExecCredentialSpec), scope)
- }); err != nil {
- return err
- }
- return nil
-}
-
-func autoConvert_v1beta1_ExecCredential_To_clientauthentication_ExecCredential(in *ExecCredential, out *clientauthentication.ExecCredential, s conversion.Scope) error {
- if err := Convert_v1beta1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(&in.Spec, &out.Spec, s); err != nil {
- return err
- }
- out.Status = (*clientauthentication.ExecCredentialStatus)(unsafe.Pointer(in.Status))
- return nil
-}
-
-// Convert_v1beta1_ExecCredential_To_clientauthentication_ExecCredential is an autogenerated conversion function.
-func Convert_v1beta1_ExecCredential_To_clientauthentication_ExecCredential(in *ExecCredential, out *clientauthentication.ExecCredential, s conversion.Scope) error {
- return autoConvert_v1beta1_ExecCredential_To_clientauthentication_ExecCredential(in, out, s)
-}
-
-func autoConvert_clientauthentication_ExecCredential_To_v1beta1_ExecCredential(in *clientauthentication.ExecCredential, out *ExecCredential, s conversion.Scope) error {
- if err := Convert_clientauthentication_ExecCredentialSpec_To_v1beta1_ExecCredentialSpec(&in.Spec, &out.Spec, s); err != nil {
- return err
- }
- out.Status = (*ExecCredentialStatus)(unsafe.Pointer(in.Status))
- return nil
-}
-
-// Convert_clientauthentication_ExecCredential_To_v1beta1_ExecCredential is an autogenerated conversion function.
-func Convert_clientauthentication_ExecCredential_To_v1beta1_ExecCredential(in *clientauthentication.ExecCredential, out *ExecCredential, s conversion.Scope) error {
- return autoConvert_clientauthentication_ExecCredential_To_v1beta1_ExecCredential(in, out, s)
-}
-
-func autoConvert_v1beta1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(in *ExecCredentialSpec, out *clientauthentication.ExecCredentialSpec, s conversion.Scope) error {
- return nil
-}
-
-// Convert_v1beta1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec is an autogenerated conversion function.
-func Convert_v1beta1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(in *ExecCredentialSpec, out *clientauthentication.ExecCredentialSpec, s conversion.Scope) error {
- return autoConvert_v1beta1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(in, out, s)
-}
-
-func autoConvert_clientauthentication_ExecCredentialSpec_To_v1beta1_ExecCredentialSpec(in *clientauthentication.ExecCredentialSpec, out *ExecCredentialSpec, s conversion.Scope) error {
- // WARNING: in.Response requires manual conversion: does not exist in peer-type
- // WARNING: in.Interactive requires manual conversion: does not exist in peer-type
- return nil
-}
-
-func autoConvert_v1beta1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus(in *ExecCredentialStatus, out *clientauthentication.ExecCredentialStatus, s conversion.Scope) error {
- out.ExpirationTimestamp = (*v1.Time)(unsafe.Pointer(in.ExpirationTimestamp))
- out.Token = in.Token
- out.ClientCertificateData = in.ClientCertificateData
- out.ClientKeyData = in.ClientKeyData
- return nil
-}
-
-// Convert_v1beta1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus is an autogenerated conversion function.
-func Convert_v1beta1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus(in *ExecCredentialStatus, out *clientauthentication.ExecCredentialStatus, s conversion.Scope) error {
- return autoConvert_v1beta1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus(in, out, s)
-}
-
-func autoConvert_clientauthentication_ExecCredentialStatus_To_v1beta1_ExecCredentialStatus(in *clientauthentication.ExecCredentialStatus, out *ExecCredentialStatus, s conversion.Scope) error {
- out.ExpirationTimestamp = (*v1.Time)(unsafe.Pointer(in.ExpirationTimestamp))
- out.Token = in.Token
- out.ClientCertificateData = in.ClientCertificateData
- out.ClientKeyData = in.ClientKeyData
- return nil
-}
-
-// Convert_clientauthentication_ExecCredentialStatus_To_v1beta1_ExecCredentialStatus is an autogenerated conversion function.
-func Convert_clientauthentication_ExecCredentialStatus_To_v1beta1_ExecCredentialStatus(in *clientauthentication.ExecCredentialStatus, out *ExecCredentialStatus, s conversion.Scope) error {
- return autoConvert_clientauthentication_ExecCredentialStatus_To_v1beta1_ExecCredentialStatus(in, out, s)
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.deepcopy.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.deepcopy.go
deleted file mode 100644
index 736b8cf00..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.deepcopy.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Code generated by deepcopy-gen. DO NOT EDIT.
-
-package v1beta1
-
-import (
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ExecCredential) DeepCopyInto(out *ExecCredential) {
- *out = *in
- out.TypeMeta = in.TypeMeta
- out.Spec = in.Spec
- if in.Status != nil {
- in, out := &in.Status, &out.Status
- *out = new(ExecCredentialStatus)
- (*in).DeepCopyInto(*out)
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecCredential.
-func (in *ExecCredential) DeepCopy() *ExecCredential {
- if in == nil {
- return nil
- }
- out := new(ExecCredential)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *ExecCredential) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- }
- return nil
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ExecCredentialSpec) DeepCopyInto(out *ExecCredentialSpec) {
- *out = *in
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecCredentialSpec.
-func (in *ExecCredentialSpec) DeepCopy() *ExecCredentialSpec {
- if in == nil {
- return nil
- }
- out := new(ExecCredentialSpec)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ExecCredentialStatus) DeepCopyInto(out *ExecCredentialStatus) {
- *out = *in
- if in.ExpirationTimestamp != nil {
- in, out := &in.ExpirationTimestamp, &out.ExpirationTimestamp
- *out = (*in).DeepCopy()
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecCredentialStatus.
-func (in *ExecCredentialStatus) DeepCopy() *ExecCredentialStatus {
- if in == nil {
- return nil
- }
- out := new(ExecCredentialStatus)
- in.DeepCopyInto(out)
- return out
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.defaults.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.defaults.go
deleted file mode 100644
index 73e63fc11..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.defaults.go
+++ /dev/null
@@ -1,32 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Code generated by defaulter-gen. DO NOT EDIT.
-
-package v1beta1
-
-import (
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-// RegisterDefaults adds defaulters functions to the given scheme.
-// Public to allow building arbitrary schemes.
-// All generated defaulters are covering - they call all nested defaulters.
-func RegisterDefaults(scheme *runtime.Scheme) error {
- return nil
-}
diff --git a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/zz_generated.deepcopy.go b/vendor/k8s.io/client-go/pkg/apis/clientauthentication/zz_generated.deepcopy.go
deleted file mode 100644
index c568a6fc8..000000000
--- a/vendor/k8s.io/client-go/pkg/apis/clientauthentication/zz_generated.deepcopy.go
+++ /dev/null
@@ -1,128 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Code generated by deepcopy-gen. DO NOT EDIT.
-
-package clientauthentication
-
-import (
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ExecCredential) DeepCopyInto(out *ExecCredential) {
- *out = *in
- out.TypeMeta = in.TypeMeta
- in.Spec.DeepCopyInto(&out.Spec)
- if in.Status != nil {
- in, out := &in.Status, &out.Status
- *out = new(ExecCredentialStatus)
- (*in).DeepCopyInto(*out)
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecCredential.
-func (in *ExecCredential) DeepCopy() *ExecCredential {
- if in == nil {
- return nil
- }
- out := new(ExecCredential)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *ExecCredential) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- }
- return nil
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ExecCredentialSpec) DeepCopyInto(out *ExecCredentialSpec) {
- *out = *in
- if in.Response != nil {
- in, out := &in.Response, &out.Response
- *out = new(Response)
- (*in).DeepCopyInto(*out)
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecCredentialSpec.
-func (in *ExecCredentialSpec) DeepCopy() *ExecCredentialSpec {
- if in == nil {
- return nil
- }
- out := new(ExecCredentialSpec)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ExecCredentialStatus) DeepCopyInto(out *ExecCredentialStatus) {
- *out = *in
- if in.ExpirationTimestamp != nil {
- in, out := &in.ExpirationTimestamp, &out.ExpirationTimestamp
- *out = (*in).DeepCopy()
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecCredentialStatus.
-func (in *ExecCredentialStatus) DeepCopy() *ExecCredentialStatus {
- if in == nil {
- return nil
- }
- out := new(ExecCredentialStatus)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *Response) DeepCopyInto(out *Response) {
- *out = *in
- if in.Header != nil {
- in, out := &in.Header, &out.Header
- *out = make(map[string][]string, len(*in))
- for key, val := range *in {
- var outVal []string
- if val == nil {
- (*out)[key] = nil
- } else {
- in, out := &val, &outVal
- *out = make([]string, len(*in))
- copy(*out, *in)
- }
- (*out)[key] = outVal
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Response.
-func (in *Response) DeepCopy() *Response {
- if in == nil {
- return nil
- }
- out := new(Response)
- in.DeepCopyInto(out)
- return out
-}
diff --git a/vendor/k8s.io/client-go/pkg/version/.gitattributes b/vendor/k8s.io/client-go/pkg/version/.gitattributes
deleted file mode 100644
index 7e349eff6..000000000
--- a/vendor/k8s.io/client-go/pkg/version/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-base.go export-subst
diff --git a/vendor/k8s.io/client-go/pkg/version/base.go b/vendor/k8s.io/client-go/pkg/version/base.go
deleted file mode 100644
index 9b4c79f89..000000000
--- a/vendor/k8s.io/client-go/pkg/version/base.go
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package version
-
-// Base version information.
-//
-// This is the fallback data used when version information from git is not
-// provided via go ldflags. It provides an approximation of the Kubernetes
-// version for ad-hoc builds (e.g. `go build`) that cannot get the version
-// information from git.
-//
-// If you are looking at these fields in the git tree, they look
-// strange. They are modified on the fly by the build process. The
-// in-tree values are dummy values used for "git archive", which also
-// works for GitHub tar downloads.
-//
-// When releasing a new Kubernetes version, this file is updated by
-// build/mark_new_version.sh to reflect the new version, and then a
-// git annotated tag (using format vX.Y where X == Major version and Y
-// == Minor version) is created to point to the commit that updates
-// pkg/version/base.go
-var (
- // TODO: Deprecate gitMajor and gitMinor, use only gitVersion
- // instead. First step in deprecation, keep the fields but make
- // them irrelevant. (Next we'll take it out, which may muck with
- // scripts consuming the kubectl version output - but most of
- // these should be looking at gitVersion already anyways.)
- gitMajor string = "" // major version, always numeric
- gitMinor string = "" // minor version, numeric possibly followed by "+"
-
- // semantic version, derived by build scripts (see
- // https://git.k8s.io/community/contributors/design-proposals/release/versioning.md
- // for a detailed discussion of this field)
- //
- // TODO: This field is still called "gitVersion" for legacy
- // reasons. For prerelease versions, the build metadata on the
- // semantic version is a git hash, but the version itself is no
- // longer the direct output of "git describe", but a slight
- // translation to be semver compliant.
-
- // NOTE: The $Format strings are replaced during 'git archive' thanks to the
- // companion .gitattributes file containing 'export-subst' in this same
- // directory. See also https://git-scm.com/docs/gitattributes
- gitVersion string = "v0.0.0-master+$Format:%h$"
- gitCommit string = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD)
- gitTreeState string = "" // state of git tree, either "clean" or "dirty"
-
- buildDate string = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ')
-)
diff --git a/vendor/k8s.io/client-go/pkg/version/def.bzl b/vendor/k8s.io/client-go/pkg/version/def.bzl
deleted file mode 100644
index 9c018a4ef..000000000
--- a/vendor/k8s.io/client-go/pkg/version/def.bzl
+++ /dev/null
@@ -1,38 +0,0 @@
-# Copyright 2017 The Kubernetes Authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Implements hack/lib/version.sh's kube::version::ldflags() for Bazel.
-def version_x_defs():
- # This should match the list of packages in kube::version::ldflag
- stamp_pkgs = [
- "k8s.io/kubernetes/pkg/version",
- # In hack/lib/version.sh, this has a vendor/ prefix. That isn't needed here?
- "k8s.io/client-go/pkg/version",
- ]
- # This should match the list of vars in kube::version::ldflags
- # It should also match the list of vars set in hack/print-workspace-status.sh.
- stamp_vars = [
- "buildDate",
- "gitCommit",
- "gitMajor",
- "gitMinor",
- "gitTreeState",
- "gitVersion",
- ]
- # Generate the cross-product.
- x_defs = {}
- for pkg in stamp_pkgs:
- for var in stamp_vars:
- x_defs["%s.%s" % (pkg, var)] = "{%s}" % var
- return x_defs
diff --git a/vendor/k8s.io/client-go/pkg/version/doc.go b/vendor/k8s.io/client-go/pkg/version/doc.go
deleted file mode 100644
index 05e997e13..000000000
--- a/vendor/k8s.io/client-go/pkg/version/doc.go
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// +k8s:openapi-gen=true
-
-// Package version supplies version information collected at build time to
-// kubernetes components.
-package version // import "k8s.io/client-go/pkg/version"
diff --git a/vendor/k8s.io/client-go/pkg/version/version.go b/vendor/k8s.io/client-go/pkg/version/version.go
deleted file mode 100644
index 8c8350d13..000000000
--- a/vendor/k8s.io/client-go/pkg/version/version.go
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package version
-
-import (
- "fmt"
- "runtime"
-
- apimachineryversion "k8s.io/apimachinery/pkg/version"
-)
-
-// Get returns the overall codebase version. It's for detecting
-// what code a binary was built from.
-func Get() apimachineryversion.Info {
- // These variables typically come from -ldflags settings and in
- // their absence fallback to the settings in pkg/version/base.go
- return apimachineryversion.Info{
- Major: gitMajor,
- Minor: gitMinor,
- GitVersion: gitVersion,
- GitCommit: gitCommit,
- GitTreeState: gitTreeState,
- BuildDate: buildDate,
- GoVersion: runtime.Version(),
- Compiler: runtime.Compiler,
- Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH),
- }
-}
diff --git a/vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go b/vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go
deleted file mode 100644
index b88902c10..000000000
--- a/vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go
+++ /dev/null
@@ -1,360 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package exec
-
-import (
- "bytes"
- "context"
- "crypto/tls"
- "errors"
- "fmt"
- "io"
- "net"
- "net/http"
- "os"
- "os/exec"
- "reflect"
- "sync"
- "time"
-
- "github.com/davecgh/go-spew/spew"
- "golang.org/x/crypto/ssh/terminal"
- v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/runtime/serializer"
- utilruntime "k8s.io/apimachinery/pkg/util/runtime"
- "k8s.io/client-go/pkg/apis/clientauthentication"
- "k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1"
- "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1"
- "k8s.io/client-go/tools/clientcmd/api"
- "k8s.io/client-go/transport"
- "k8s.io/client-go/util/connrotation"
- "k8s.io/klog"
-)
-
-const execInfoEnv = "KUBERNETES_EXEC_INFO"
-
-var scheme = runtime.NewScheme()
-var codecs = serializer.NewCodecFactory(scheme)
-
-func init() {
- v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"})
- utilruntime.Must(v1alpha1.AddToScheme(scheme))
- utilruntime.Must(v1beta1.AddToScheme(scheme))
- utilruntime.Must(clientauthentication.AddToScheme(scheme))
-}
-
-var (
- // Since transports can be constantly re-initialized by programs like kubectl,
- // keep a cache of initialized authenticators keyed by a hash of their config.
- globalCache = newCache()
- // The list of API versions we accept.
- apiVersions = map[string]schema.GroupVersion{
- v1alpha1.SchemeGroupVersion.String(): v1alpha1.SchemeGroupVersion,
- v1beta1.SchemeGroupVersion.String(): v1beta1.SchemeGroupVersion,
- }
-)
-
-func newCache() *cache {
- return &cache{m: make(map[string]*Authenticator)}
-}
-
-var spewConfig = &spew.ConfigState{DisableMethods: true, Indent: " "}
-
-func cacheKey(c *api.ExecConfig) string {
- return spewConfig.Sprint(c)
-}
-
-type cache struct {
- mu sync.Mutex
- m map[string]*Authenticator
-}
-
-func (c *cache) get(s string) (*Authenticator, bool) {
- c.mu.Lock()
- defer c.mu.Unlock()
- a, ok := c.m[s]
- return a, ok
-}
-
-// put inserts an authenticator into the cache. If an authenticator is already
-// associated with the key, the first one is returned instead.
-func (c *cache) put(s string, a *Authenticator) *Authenticator {
- c.mu.Lock()
- defer c.mu.Unlock()
- existing, ok := c.m[s]
- if ok {
- return existing
- }
- c.m[s] = a
- return a
-}
-
-// GetAuthenticator returns an exec-based plugin for providing client credentials.
-func GetAuthenticator(config *api.ExecConfig) (*Authenticator, error) {
- return newAuthenticator(globalCache, config)
-}
-
-func newAuthenticator(c *cache, config *api.ExecConfig) (*Authenticator, error) {
- key := cacheKey(config)
- if a, ok := c.get(key); ok {
- return a, nil
- }
-
- gv, ok := apiVersions[config.APIVersion]
- if !ok {
- return nil, fmt.Errorf("exec plugin: invalid apiVersion %q", config.APIVersion)
- }
-
- a := &Authenticator{
- cmd: config.Command,
- args: config.Args,
- group: gv,
-
- stdin: os.Stdin,
- stderr: os.Stderr,
- interactive: terminal.IsTerminal(int(os.Stdout.Fd())),
- now: time.Now,
- environ: os.Environ,
- }
-
- for _, env := range config.Env {
- a.env = append(a.env, env.Name+"="+env.Value)
- }
-
- return c.put(key, a), nil
-}
-
-// Authenticator is a client credential provider that rotates credentials by executing a plugin.
-// The plugin input and output are defined by the API group client.authentication.k8s.io.
-type Authenticator struct {
- // Set by the config
- cmd string
- args []string
- group schema.GroupVersion
- env []string
-
- // Stubbable for testing
- stdin io.Reader
- stderr io.Writer
- interactive bool
- now func() time.Time
- environ func() []string
-
- // Cached results.
- //
- // The mutex also guards calling the plugin. Since the plugin could be
- // interactive we want to make sure it's only called once.
- mu sync.Mutex
- cachedCreds *credentials
- exp time.Time
-
- onRotate func()
-}
-
-type credentials struct {
- token string
- cert *tls.Certificate
-}
-
-// UpdateTransportConfig updates the transport.Config to use credentials
-// returned by the plugin.
-func (a *Authenticator) UpdateTransportConfig(c *transport.Config) error {
- c.Wrap(func(rt http.RoundTripper) http.RoundTripper {
- return &roundTripper{a, rt}
- })
-
- if c.TLS.GetCert != nil {
- return errors.New("can't add TLS certificate callback: transport.Config.TLS.GetCert already set")
- }
- c.TLS.GetCert = a.cert
-
- var dial func(ctx context.Context, network, addr string) (net.Conn, error)
- if c.Dial != nil {
- dial = c.Dial
- } else {
- dial = (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext
- }
- d := connrotation.NewDialer(dial)
- a.onRotate = d.CloseAll
- c.Dial = d.DialContext
-
- return nil
-}
-
-type roundTripper struct {
- a *Authenticator
- base http.RoundTripper
-}
-
-func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
- // If a user has already set credentials, use that. This makes commands like
- // "kubectl get --token (token) pods" work.
- if req.Header.Get("Authorization") != "" {
- return r.base.RoundTrip(req)
- }
-
- creds, err := r.a.getCreds()
- if err != nil {
- return nil, fmt.Errorf("getting credentials: %v", err)
- }
- if creds.token != "" {
- req.Header.Set("Authorization", "Bearer "+creds.token)
- }
-
- res, err := r.base.RoundTrip(req)
- if err != nil {
- return nil, err
- }
- if res.StatusCode == http.StatusUnauthorized {
- resp := &clientauthentication.Response{
- Header: res.Header,
- Code: int32(res.StatusCode),
- }
- if err := r.a.maybeRefreshCreds(creds, resp); err != nil {
- klog.Errorf("refreshing credentials: %v", err)
- }
- }
- return res, nil
-}
-
-func (a *Authenticator) credsExpired() bool {
- if a.exp.IsZero() {
- return false
- }
- return a.now().After(a.exp)
-}
-
-func (a *Authenticator) cert() (*tls.Certificate, error) {
- creds, err := a.getCreds()
- if err != nil {
- return nil, err
- }
- return creds.cert, nil
-}
-
-func (a *Authenticator) getCreds() (*credentials, error) {
- a.mu.Lock()
- defer a.mu.Unlock()
- if a.cachedCreds != nil && !a.credsExpired() {
- return a.cachedCreds, nil
- }
-
- if err := a.refreshCredsLocked(nil); err != nil {
- return nil, err
- }
- return a.cachedCreds, nil
-}
-
-// maybeRefreshCreds executes the plugin to force a rotation of the
-// credentials, unless they were rotated already.
-func (a *Authenticator) maybeRefreshCreds(creds *credentials, r *clientauthentication.Response) error {
- a.mu.Lock()
- defer a.mu.Unlock()
-
- // Since we're not making a new pointer to a.cachedCreds in getCreds, no
- // need to do deep comparison.
- if creds != a.cachedCreds {
- // Credentials already rotated.
- return nil
- }
-
- return a.refreshCredsLocked(r)
-}
-
-// refreshCredsLocked executes the plugin and reads the credentials from
-// stdout. It must be called while holding the Authenticator's mutex.
-func (a *Authenticator) refreshCredsLocked(r *clientauthentication.Response) error {
- cred := &clientauthentication.ExecCredential{
- Spec: clientauthentication.ExecCredentialSpec{
- Response: r,
- Interactive: a.interactive,
- },
- }
-
- env := append(a.environ(), a.env...)
- if a.group == v1alpha1.SchemeGroupVersion {
- // Input spec disabled for beta due to lack of use. Possibly re-enable this later if
- // someone wants it back.
- //
- // See: https://github.com/kubernetes/kubernetes/issues/61796
- data, err := runtime.Encode(codecs.LegacyCodec(a.group), cred)
- if err != nil {
- return fmt.Errorf("encode ExecCredentials: %v", err)
- }
- env = append(env, fmt.Sprintf("%s=%s", execInfoEnv, data))
- }
-
- stdout := &bytes.Buffer{}
- cmd := exec.Command(a.cmd, a.args...)
- cmd.Env = env
- cmd.Stderr = a.stderr
- cmd.Stdout = stdout
- if a.interactive {
- cmd.Stdin = a.stdin
- }
-
- if err := cmd.Run(); err != nil {
- return fmt.Errorf("exec: %v", err)
- }
-
- _, gvk, err := codecs.UniversalDecoder(a.group).Decode(stdout.Bytes(), nil, cred)
- if err != nil {
- return fmt.Errorf("decoding stdout: %v", err)
- }
- if gvk.Group != a.group.Group || gvk.Version != a.group.Version {
- return fmt.Errorf("exec plugin is configured to use API version %s, plugin returned version %s",
- a.group, schema.GroupVersion{Group: gvk.Group, Version: gvk.Version})
- }
-
- if cred.Status == nil {
- return fmt.Errorf("exec plugin didn't return a status field")
- }
- if cred.Status.Token == "" && cred.Status.ClientCertificateData == "" && cred.Status.ClientKeyData == "" {
- return fmt.Errorf("exec plugin didn't return a token or cert/key pair")
- }
- if (cred.Status.ClientCertificateData == "") != (cred.Status.ClientKeyData == "") {
- return fmt.Errorf("exec plugin returned only certificate or key, not both")
- }
-
- if cred.Status.ExpirationTimestamp != nil {
- a.exp = cred.Status.ExpirationTimestamp.Time
- } else {
- a.exp = time.Time{}
- }
-
- newCreds := &credentials{
- token: cred.Status.Token,
- }
- if cred.Status.ClientKeyData != "" && cred.Status.ClientCertificateData != "" {
- cert, err := tls.X509KeyPair([]byte(cred.Status.ClientCertificateData), []byte(cred.Status.ClientKeyData))
- if err != nil {
- return fmt.Errorf("failed parsing client key/certificate: %v", err)
- }
- newCreds.cert = &cert
- }
-
- oldCreds := a.cachedCreds
- a.cachedCreds = newCreds
- // Only close all connections when TLS cert rotates. Token rotation doesn't
- // need the extra noise.
- if a.onRotate != nil && oldCreds != nil && !reflect.DeepEqual(oldCreds.cert, a.cachedCreds.cert) {
- a.onRotate()
- }
- return nil
-}
diff --git a/vendor/k8s.io/client-go/rest/OWNERS b/vendor/k8s.io/client-go/rest/OWNERS
deleted file mode 100644
index 49dabc61b..000000000
--- a/vendor/k8s.io/client-go/rest/OWNERS
+++ /dev/null
@@ -1,26 +0,0 @@
-# See the OWNERS docs at https://go.k8s.io/owners
-
-reviewers:
-- thockin
-- smarterclayton
-- caesarxuchao
-- wojtek-t
-- deads2k
-- brendandburns
-- liggitt
-- nikhiljindal
-- gmarek
-- erictune
-- sttts
-- luxas
-- dims
-- errordeveloper
-- hongchaodeng
-- krousey
-- resouer
-- cjcullen
-- rmmh
-- lixiaobing10051267
-- asalkeld
-- juanvallejo
-- lojies
diff --git a/vendor/k8s.io/client-go/rest/client.go b/vendor/k8s.io/client-go/rest/client.go
deleted file mode 100644
index 927403cb2..000000000
--- a/vendor/k8s.io/client-go/rest/client.go
+++ /dev/null
@@ -1,258 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package rest
-
-import (
- "fmt"
- "mime"
- "net/http"
- "net/url"
- "os"
- "strconv"
- "strings"
- "time"
-
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/types"
- "k8s.io/client-go/util/flowcontrol"
-)
-
-const (
- // Environment variables: Note that the duration should be long enough that the backoff
- // persists for some reasonable time (i.e. 120 seconds). The typical base might be "1".
- envBackoffBase = "KUBE_CLIENT_BACKOFF_BASE"
- envBackoffDuration = "KUBE_CLIENT_BACKOFF_DURATION"
-)
-
-// Interface captures the set of operations for generically interacting with Kubernetes REST apis.
-type Interface interface {
- GetRateLimiter() flowcontrol.RateLimiter
- Verb(verb string) *Request
- Post() *Request
- Put() *Request
- Patch(pt types.PatchType) *Request
- Get() *Request
- Delete() *Request
- APIVersion() schema.GroupVersion
-}
-
-// RESTClient imposes common Kubernetes API conventions on a set of resource paths.
-// The baseURL is expected to point to an HTTP or HTTPS path that is the parent
-// of one or more resources. The server should return a decodable API resource
-// object, or an api.Status object which contains information about the reason for
-// any failure.
-//
-// Most consumers should use client.New() to get a Kubernetes API client.
-type RESTClient struct {
- // base is the root URL for all invocations of the client
- base *url.URL
- // versionedAPIPath is a path segment connecting the base URL to the resource root
- versionedAPIPath string
-
- // contentConfig is the information used to communicate with the server.
- contentConfig ContentConfig
-
- // serializers contain all serializers for underlying content type.
- serializers Serializers
-
- // creates BackoffManager that is passed to requests.
- createBackoffMgr func() BackoffManager
-
- // TODO extract this into a wrapper interface via the RESTClient interface in kubectl.
- Throttle flowcontrol.RateLimiter
-
- // Set specific behavior of the client. If not set http.DefaultClient will be used.
- Client *http.Client
-}
-
-type Serializers struct {
- Encoder runtime.Encoder
- Decoder runtime.Decoder
- StreamingSerializer runtime.Serializer
- Framer runtime.Framer
- RenegotiatedDecoder func(contentType string, params map[string]string) (runtime.Decoder, error)
-}
-
-// NewRESTClient creates a new RESTClient. This client performs generic REST functions
-// such as Get, Put, Post, and Delete on specified paths. Codec controls encoding and
-// decoding of responses from the server.
-func NewRESTClient(baseURL *url.URL, versionedAPIPath string, config ContentConfig, maxQPS float32, maxBurst int, rateLimiter flowcontrol.RateLimiter, client *http.Client) (*RESTClient, error) {
- base := *baseURL
- if !strings.HasSuffix(base.Path, "/") {
- base.Path += "/"
- }
- base.RawQuery = ""
- base.Fragment = ""
-
- if config.GroupVersion == nil {
- config.GroupVersion = &schema.GroupVersion{}
- }
- if len(config.ContentType) == 0 {
- config.ContentType = "application/json"
- }
- serializers, err := createSerializers(config)
- if err != nil {
- return nil, err
- }
-
- var throttle flowcontrol.RateLimiter
- if maxQPS > 0 && rateLimiter == nil {
- throttle = flowcontrol.NewTokenBucketRateLimiter(maxQPS, maxBurst)
- } else if rateLimiter != nil {
- throttle = rateLimiter
- }
- return &RESTClient{
- base: &base,
- versionedAPIPath: versionedAPIPath,
- contentConfig: config,
- serializers: *serializers,
- createBackoffMgr: readExpBackoffConfig,
- Throttle: throttle,
- Client: client,
- }, nil
-}
-
-// GetRateLimiter returns rate limier for a given client, or nil if it's called on a nil client
-func (c *RESTClient) GetRateLimiter() flowcontrol.RateLimiter {
- if c == nil {
- return nil
- }
- return c.Throttle
-}
-
-// readExpBackoffConfig handles the internal logic of determining what the
-// backoff policy is. By default if no information is available, NoBackoff.
-// TODO Generalize this see #17727 .
-func readExpBackoffConfig() BackoffManager {
- backoffBase := os.Getenv(envBackoffBase)
- backoffDuration := os.Getenv(envBackoffDuration)
-
- backoffBaseInt, errBase := strconv.ParseInt(backoffBase, 10, 64)
- backoffDurationInt, errDuration := strconv.ParseInt(backoffDuration, 10, 64)
- if errBase != nil || errDuration != nil {
- return &NoBackoff{}
- }
- return &URLBackoff{
- Backoff: flowcontrol.NewBackOff(
- time.Duration(backoffBaseInt)*time.Second,
- time.Duration(backoffDurationInt)*time.Second)}
-}
-
-// createSerializers creates all necessary serializers for given contentType.
-// TODO: the negotiated serializer passed to this method should probably return
-// serializers that control decoding and versioning without this package
-// being aware of the types. Depends on whether RESTClient must deal with
-// generic infrastructure.
-func createSerializers(config ContentConfig) (*Serializers, error) {
- mediaTypes := config.NegotiatedSerializer.SupportedMediaTypes()
- contentType := config.ContentType
- mediaType, _, err := mime.ParseMediaType(contentType)
- if err != nil {
- return nil, fmt.Errorf("the content type specified in the client configuration is not recognized: %v", err)
- }
- info, ok := runtime.SerializerInfoForMediaType(mediaTypes, mediaType)
- if !ok {
- if len(contentType) != 0 || len(mediaTypes) == 0 {
- return nil, fmt.Errorf("no serializers registered for %s", contentType)
- }
- info = mediaTypes[0]
- }
-
- internalGV := schema.GroupVersions{
- {
- Group: config.GroupVersion.Group,
- Version: runtime.APIVersionInternal,
- },
- // always include the legacy group as a decoding target to handle non-error `Status` return types
- {
- Group: "",
- Version: runtime.APIVersionInternal,
- },
- }
-
- s := &Serializers{
- Encoder: config.NegotiatedSerializer.EncoderForVersion(info.Serializer, *config.GroupVersion),
- Decoder: config.NegotiatedSerializer.DecoderToVersion(info.Serializer, internalGV),
-
- RenegotiatedDecoder: func(contentType string, params map[string]string) (runtime.Decoder, error) {
- info, ok := runtime.SerializerInfoForMediaType(mediaTypes, contentType)
- if !ok {
- return nil, fmt.Errorf("serializer for %s not registered", contentType)
- }
- return config.NegotiatedSerializer.DecoderToVersion(info.Serializer, internalGV), nil
- },
- }
- if info.StreamSerializer != nil {
- s.StreamingSerializer = info.StreamSerializer.Serializer
- s.Framer = info.StreamSerializer.Framer
- }
-
- return s, nil
-}
-
-// Verb begins a request with a verb (GET, POST, PUT, DELETE).
-//
-// Example usage of RESTClient's request building interface:
-// c, err := NewRESTClient(...)
-// if err != nil { ... }
-// resp, err := c.Verb("GET").
-// Path("pods").
-// SelectorParam("labels", "area=staging").
-// Timeout(10*time.Second).
-// Do()
-// if err != nil { ... }
-// list, ok := resp.(*api.PodList)
-//
-func (c *RESTClient) Verb(verb string) *Request {
- backoff := c.createBackoffMgr()
-
- if c.Client == nil {
- return NewRequest(nil, verb, c.base, c.versionedAPIPath, c.contentConfig, c.serializers, backoff, c.Throttle, 0)
- }
- return NewRequest(c.Client, verb, c.base, c.versionedAPIPath, c.contentConfig, c.serializers, backoff, c.Throttle, c.Client.Timeout)
-}
-
-// Post begins a POST request. Short for c.Verb("POST").
-func (c *RESTClient) Post() *Request {
- return c.Verb("POST")
-}
-
-// Put begins a PUT request. Short for c.Verb("PUT").
-func (c *RESTClient) Put() *Request {
- return c.Verb("PUT")
-}
-
-// Patch begins a PATCH request. Short for c.Verb("Patch").
-func (c *RESTClient) Patch(pt types.PatchType) *Request {
- return c.Verb("PATCH").SetHeader("Content-Type", string(pt))
-}
-
-// Get begins a GET request. Short for c.Verb("GET").
-func (c *RESTClient) Get() *Request {
- return c.Verb("GET")
-}
-
-// Delete begins a DELETE request. Short for c.Verb("DELETE").
-func (c *RESTClient) Delete() *Request {
- return c.Verb("DELETE")
-}
-
-// APIVersion returns the APIVersion this RESTClient is expected to use.
-func (c *RESTClient) APIVersion() schema.GroupVersion {
- return *c.contentConfig.GroupVersion
-}
diff --git a/vendor/k8s.io/client-go/rest/config.go b/vendor/k8s.io/client-go/rest/config.go
deleted file mode 100644
index c75825ec5..000000000
--- a/vendor/k8s.io/client-go/rest/config.go
+++ /dev/null
@@ -1,549 +0,0 @@
-/*
-Copyright 2016 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package rest
-
-import (
- "context"
- "errors"
- "fmt"
- "io/ioutil"
- "net"
- "net/http"
- "os"
- "path/filepath"
- gruntime "runtime"
- "strings"
- "time"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/client-go/pkg/version"
- clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
- "k8s.io/client-go/transport"
- certutil "k8s.io/client-go/util/cert"
- "k8s.io/client-go/util/flowcontrol"
- "k8s.io/klog"
-)
-
-const (
- DefaultQPS float32 = 5.0
- DefaultBurst int = 10
-)
-
-var ErrNotInCluster = errors.New("unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined")
-
-// Config holds the common attributes that can be passed to a Kubernetes client on
-// initialization.
-type Config struct {
- // Host must be a host string, a host:port pair, or a URL to the base of the apiserver.
- // If a URL is given then the (optional) Path of that URL represents a prefix that must
- // be appended to all request URIs used to access the apiserver. This allows a frontend
- // proxy to easily relocate all of the apiserver endpoints.
- Host string
- // APIPath is a sub-path that points to an API root.
- APIPath string
-
- // ContentConfig contains settings that affect how objects are transformed when
- // sent to the server.
- ContentConfig
-
- // Server requires Basic authentication
- Username string
- Password string
-
- // Server requires Bearer authentication. This client will not attempt to use
- // refresh tokens for an OAuth2 flow.
- // TODO: demonstrate an OAuth2 compatible client.
- BearerToken string
-
- // Path to a file containing a BearerToken.
- // If set, the contents are periodically read.
- // The last successfully read value takes precedence over BearerToken.
- BearerTokenFile string
-
- // Impersonate is the configuration that RESTClient will use for impersonation.
- Impersonate ImpersonationConfig
-
- // Server requires plugin-specified authentication.
- AuthProvider *clientcmdapi.AuthProviderConfig
-
- // Callback to persist config for AuthProvider.
- AuthConfigPersister AuthProviderConfigPersister
-
- // Exec-based authentication provider.
- ExecProvider *clientcmdapi.ExecConfig
-
- // TLSClientConfig contains settings to enable transport layer security
- TLSClientConfig
-
- // UserAgent is an optional field that specifies the caller of this request.
- UserAgent string
-
- // Transport may be used for custom HTTP behavior. This attribute may not
- // be specified with the TLS client certificate options. Use WrapTransport
- // to provide additional per-server middleware behavior.
- Transport http.RoundTripper
- // WrapTransport will be invoked for custom HTTP behavior after the underlying
- // transport is initialized (either the transport created from TLSClientConfig,
- // Transport, or http.DefaultTransport). The config may layer other RoundTrippers
- // on top of the returned RoundTripper.
- //
- // A future release will change this field to an array. Use config.Wrap()
- // instead of setting this value directly.
- WrapTransport transport.WrapperFunc
-
- // QPS indicates the maximum QPS to the master from this client.
- // If it's zero, the created RESTClient will use DefaultQPS: 5
- QPS float32
-
- // Maximum burst for throttle.
- // If it's zero, the created RESTClient will use DefaultBurst: 10.
- Burst int
-
- // Rate limiter for limiting connections to the master from this client. If present overwrites QPS/Burst
- RateLimiter flowcontrol.RateLimiter
-
- // The maximum length of time to wait before giving up on a server request. A value of zero means no timeout.
- Timeout time.Duration
-
- // Dial specifies the dial function for creating unencrypted TCP connections.
- Dial func(ctx context.Context, network, address string) (net.Conn, error)
-
- // Version forces a specific version to be used (if registered)
- // Do we need this?
- // Version string
-}
-
-var _ fmt.Stringer = new(Config)
-var _ fmt.GoStringer = new(Config)
-
-type sanitizedConfig *Config
-
-type sanitizedAuthConfigPersister struct{ AuthProviderConfigPersister }
-
-func (sanitizedAuthConfigPersister) GoString() string {
- return "rest.AuthProviderConfigPersister(--- REDACTED ---)"
-}
-func (sanitizedAuthConfigPersister) String() string {
- return "rest.AuthProviderConfigPersister(--- REDACTED ---)"
-}
-
-// GoString implements fmt.GoStringer and sanitizes sensitive fields of Config
-// to prevent accidental leaking via logs.
-func (c *Config) GoString() string {
- return c.String()
-}
-
-// String implements fmt.Stringer and sanitizes sensitive fields of Config to
-// prevent accidental leaking via logs.
-func (c *Config) String() string {
- if c == nil {
- return "<nil>"
- }
- cc := sanitizedConfig(CopyConfig(c))
- // Explicitly mark non-empty credential fields as redacted.
- if cc.Password != "" {
- cc.Password = "--- REDACTED ---"
- }
- if cc.BearerToken != "" {
- cc.BearerToken = "--- REDACTED ---"
- }
- if cc.AuthConfigPersister != nil {
- cc.AuthConfigPersister = sanitizedAuthConfigPersister{cc.AuthConfigPersister}
- }
-
- return fmt.Sprintf("%#v", cc)
-}
-
-// ImpersonationConfig has all the available impersonation options
-type ImpersonationConfig struct {
- // UserName is the username to impersonate on each request.
- UserName string
- // Groups are the groups to impersonate on each request.
- Groups []string
- // Extra is a free-form field which can be used to link some authentication information
- // to authorization information. This field allows you to impersonate it.
- Extra map[string][]string
-}
-
-// +k8s:deepcopy-gen=true
-// TLSClientConfig contains settings to enable transport layer security
-type TLSClientConfig struct {
- // Server should be accessed without verifying the TLS certificate. For testing only.
- Insecure bool
- // ServerName is passed to the server for SNI and is used in the client to check server
- // ceritificates against. If ServerName is empty, the hostname used to contact the
- // server is used.
- ServerName string
-
- // Server requires TLS client certificate authentication
- CertFile string
- // Server requires TLS client certificate authentication
- KeyFile string
- // Trusted root certificates for server
- CAFile string
-
- // CertData holds PEM-encoded bytes (typically read from a client certificate file).
- // CertData takes precedence over CertFile
- CertData []byte
- // KeyData holds PEM-encoded bytes (typically read from a client certificate key file).
- // KeyData takes precedence over KeyFile
- KeyData []byte
- // CAData holds PEM-encoded bytes (typically read from a root certificates bundle).
- // CAData takes precedence over CAFile
- CAData []byte
-}
-
-var _ fmt.Stringer = TLSClientConfig{}
-var _ fmt.GoStringer = TLSClientConfig{}
-
-type sanitizedTLSClientConfig TLSClientConfig
-
-// GoString implements fmt.GoStringer and sanitizes sensitive fields of
-// TLSClientConfig to prevent accidental leaking via logs.
-func (c TLSClientConfig) GoString() string {
- return c.String()
-}
-
-// String implements fmt.Stringer and sanitizes sensitive fields of
-// TLSClientConfig to prevent accidental leaking via logs.
-func (c TLSClientConfig) String() string {
- cc := sanitizedTLSClientConfig{
- Insecure: c.Insecure,
- ServerName: c.ServerName,
- CertFile: c.CertFile,
- KeyFile: c.KeyFile,
- CAFile: c.CAFile,
- CertData: c.CertData,
- KeyData: c.KeyData,
- CAData: c.CAData,
- }
- // Explicitly mark non-empty credential fields as redacted.
- if len(cc.CertData) != 0 {
- cc.CertData = []byte("--- TRUNCATED ---")
- }
- if len(cc.KeyData) != 0 {
- cc.KeyData = []byte("--- REDACTED ---")
- }
- return fmt.Sprintf("%#v", cc)
-}
-
-type ContentConfig struct {
- // AcceptContentTypes specifies the types the client will accept and is optional.
- // If not set, ContentType will be used to define the Accept header
- AcceptContentTypes string
- // ContentType specifies the wire format used to communicate with the server.
- // This value will be set as the Accept header on requests made to the server, and
- // as the default content type on any object sent to the server. If not set,
- // "application/json" is used.
- ContentType string
- // GroupVersion is the API version to talk to. Must be provided when initializing
- // a RESTClient directly. When initializing a Client, will be set with the default
- // code version.
- GroupVersion *schema.GroupVersion
- // NegotiatedSerializer is used for obtaining encoders and decoders for multiple
- // supported media types.
- NegotiatedSerializer runtime.NegotiatedSerializer
-}
-
-// RESTClientFor returns a RESTClient that satisfies the requested attributes on a client Config
-// object. Note that a RESTClient may require fields that are optional when initializing a Client.
-// A RESTClient created by this method is generic - it expects to operate on an API that follows
-// the Kubernetes conventions, but may not be the Kubernetes API.
-func RESTClientFor(config *Config) (*RESTClient, error) {
- if config.GroupVersion == nil {
- return nil, fmt.Errorf("GroupVersion is required when initializing a RESTClient")
- }
- if config.NegotiatedSerializer == nil {
- return nil, fmt.Errorf("NegotiatedSerializer is required when initializing a RESTClient")
- }
- qps := config.QPS
- if config.QPS == 0.0 {
- qps = DefaultQPS
- }
- burst := config.Burst
- if config.Burst == 0 {
- burst = DefaultBurst
- }
-
- baseURL, versionedAPIPath, err := defaultServerUrlFor(config)
- if err != nil {
- return nil, err
- }
-
- transport, err := TransportFor(config)
- if err != nil {
- return nil, err
- }
-
- var httpClient *http.Client
- if transport != http.DefaultTransport {
- httpClient = &http.Client{Transport: transport}
- if config.Timeout > 0 {
- httpClient.Timeout = config.Timeout
- }
- }
-
- return NewRESTClient(baseURL, versionedAPIPath, config.ContentConfig, qps, burst, config.RateLimiter, httpClient)
-}
-
-// UnversionedRESTClientFor is the same as RESTClientFor, except that it allows
-// the config.Version to be empty.
-func UnversionedRESTClientFor(config *Config) (*RESTClient, error) {
- if config.NegotiatedSerializer == nil {
- return nil, fmt.Errorf("NegotiatedSerializer is required when initializing a RESTClient")
- }
-
- baseURL, versionedAPIPath, err := defaultServerUrlFor(config)
- if err != nil {
- return nil, err
- }
-
- transport, err := TransportFor(config)
- if err != nil {
- return nil, err
- }
-
- var httpClient *http.Client
- if transport != http.DefaultTransport {
- httpClient = &http.Client{Transport: transport}
- if config.Timeout > 0 {
- httpClient.Timeout = config.Timeout
- }
- }
-
- versionConfig := config.ContentConfig
- if versionConfig.GroupVersion == nil {
- v := metav1.SchemeGroupVersion
- versionConfig.GroupVersion = &v
- }
-
- return NewRESTClient(baseURL, versionedAPIPath, versionConfig, config.QPS, config.Burst, config.RateLimiter, httpClient)
-}
-
-// SetKubernetesDefaults sets default values on the provided client config for accessing the
-// Kubernetes API or returns an error if any of the defaults are impossible or invalid.
-func SetKubernetesDefaults(config *Config) error {
- if len(config.UserAgent) == 0 {
- config.UserAgent = DefaultKubernetesUserAgent()
- }
- return nil
-}
-
-// adjustCommit returns sufficient significant figures of the commit's git hash.
-func adjustCommit(c string) string {
- if len(c) == 0 {
- return "unknown"
- }
- if len(c) > 7 {
- return c[:7]
- }
- return c
-}
-
-// adjustVersion strips "alpha", "beta", etc. from version in form
-// major.minor.patch-[alpha|beta|etc].
-func adjustVersion(v string) string {
- if len(v) == 0 {
- return "unknown"
- }
- seg := strings.SplitN(v, "-", 2)
- return seg[0]
-}
-
-// adjustCommand returns the last component of the
-// OS-specific command path for use in User-Agent.
-func adjustCommand(p string) string {
- // Unlikely, but better than returning "".
- if len(p) == 0 {
- return "unknown"
- }
- return filepath.Base(p)
-}
-
-// buildUserAgent builds a User-Agent string from given args.
-func buildUserAgent(command, version, os, arch, commit string) string {
- return fmt.Sprintf(
- "%s/%s (%s/%s) kubernetes/%s", command, version, os, arch, commit)
-}
-
-// DefaultKubernetesUserAgent returns a User-Agent string built from static global vars.
-func DefaultKubernetesUserAgent() string {
- return buildUserAgent(
- adjustCommand(os.Args[0]),
- adjustVersion(version.Get().GitVersion),
- gruntime.GOOS,
- gruntime.GOARCH,
- adjustCommit(version.Get().GitCommit))
-}
-
-// InClusterConfig returns a config object which uses the service account
-// kubernetes gives to pods. It's intended for clients that expect to be
-// running inside a pod running on kubernetes. It will return ErrNotInCluster
-// if called from a process not running in a kubernetes environment.
-func InClusterConfig() (*Config, error) {
- const (
- tokenFile = "/var/run/secrets/kubernetes.io/serviceaccount/token"
- rootCAFile = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
- )
- host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT")
- if len(host) == 0 || len(port) == 0 {
- return nil, ErrNotInCluster
- }
-
- token, err := ioutil.ReadFile(tokenFile)
- if err != nil {
- return nil, err
- }
-
- tlsClientConfig := TLSClientConfig{}
-
- if _, err := certutil.NewPool(rootCAFile); err != nil {
- klog.Errorf("Expected to load root CA config from %s, but got err: %v", rootCAFile, err)
- } else {
- tlsClientConfig.CAFile = rootCAFile
- }
-
- return &Config{
- // TODO: switch to using cluster DNS.
- Host: "https://" + net.JoinHostPort(host, port),
- TLSClientConfig: tlsClientConfig,
- BearerToken: string(token),
- BearerTokenFile: tokenFile,
- }, nil
-}
-
-// IsConfigTransportTLS returns true if and only if the provided
-// config will result in a protected connection to the server when it
-// is passed to restclient.RESTClientFor(). Use to determine when to
-// send credentials over the wire.
-//
-// Note: the Insecure flag is ignored when testing for this value, so MITM attacks are
-// still possible.
-func IsConfigTransportTLS(config Config) bool {
- baseURL, _, err := defaultServerUrlFor(&config)
- if err != nil {
- return false
- }
- return baseURL.Scheme == "https"
-}
-
-// LoadTLSFiles copies the data from the CertFile, KeyFile, and CAFile fields into the CertData,
-// KeyData, and CAFile fields, or returns an error. If no error is returned, all three fields are
-// either populated or were empty to start.
-func LoadTLSFiles(c *Config) error {
- var err error
- c.CAData, err = dataFromSliceOrFile(c.CAData, c.CAFile)
- if err != nil {
- return err
- }
-
- c.CertData, err = dataFromSliceOrFile(c.CertData, c.CertFile)
- if err != nil {
- return err
- }
-
- c.KeyData, err = dataFromSliceOrFile(c.KeyData, c.KeyFile)
- if err != nil {
- return err
- }
- return nil
-}
-
-// dataFromSliceOrFile returns data from the slice (if non-empty), or from the file,
-// or an error if an error occurred reading the file
-func dataFromSliceOrFile(data []byte, file string) ([]byte, error) {
- if len(data) > 0 {
- return data, nil
- }
- if len(file) > 0 {
- fileData, err := ioutil.ReadFile(file)
- if err != nil {
- return []byte{}, err
- }
- return fileData, nil
- }
- return nil, nil
-}
-
-func AddUserAgent(config *Config, userAgent string) *Config {
- fullUserAgent := DefaultKubernetesUserAgent() + "/" + userAgent
- config.UserAgent = fullUserAgent
- return config
-}
-
-// AnonymousClientConfig returns a copy of the given config with all user credentials (cert/key, bearer token, and username/password) and custom transports (WrapTransport, Transport) removed
-func AnonymousClientConfig(config *Config) *Config {
- // copy only known safe fields
- return &Config{
- Host: config.Host,
- APIPath: config.APIPath,
- ContentConfig: config.ContentConfig,
- TLSClientConfig: TLSClientConfig{
- Insecure: config.Insecure,
- ServerName: config.ServerName,
- CAFile: config.TLSClientConfig.CAFile,
- CAData: config.TLSClientConfig.CAData,
- },
- RateLimiter: config.RateLimiter,
- UserAgent: config.UserAgent,
- QPS: config.QPS,
- Burst: config.Burst,
- Timeout: config.Timeout,
- Dial: config.Dial,
- }
-}
-
-// CopyConfig returns a copy of the given config
-func CopyConfig(config *Config) *Config {
- return &Config{
- Host: config.Host,
- APIPath: config.APIPath,
- ContentConfig: config.ContentConfig,
- Username: config.Username,
- Password: config.Password,
- BearerToken: config.BearerToken,
- BearerTokenFile: config.BearerTokenFile,
- Impersonate: ImpersonationConfig{
- Groups: config.Impersonate.Groups,
- Extra: config.Impersonate.Extra,
- UserName: config.Impersonate.UserName,
- },
- AuthProvider: config.AuthProvider,
- AuthConfigPersister: config.AuthConfigPersister,
- ExecProvider: config.ExecProvider,
- TLSClientConfig: TLSClientConfig{
- Insecure: config.TLSClientConfig.Insecure,
- ServerName: config.TLSClientConfig.ServerName,
- CertFile: config.TLSClientConfig.CertFile,
- KeyFile: config.TLSClientConfig.KeyFile,
- CAFile: config.TLSClientConfig.CAFile,
- CertData: config.TLSClientConfig.CertData,
- KeyData: config.TLSClientConfig.KeyData,
- CAData: config.TLSClientConfig.CAData,
- },
- UserAgent: config.UserAgent,
- Transport: config.Transport,
- WrapTransport: config.WrapTransport,
- QPS: config.QPS,
- Burst: config.Burst,
- RateLimiter: config.RateLimiter,
- Timeout: config.Timeout,
- Dial: config.Dial,
- }
-}
diff --git a/vendor/k8s.io/client-go/rest/plugin.go b/vendor/k8s.io/client-go/rest/plugin.go
deleted file mode 100644
index 83ef5ae32..000000000
--- a/vendor/k8s.io/client-go/rest/plugin.go
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
-Copyright 2016 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package rest
-
-import (
- "fmt"
- "net/http"
- "sync"
-
- "k8s.io/klog"
-
- clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
-)
-
-type AuthProvider interface {
- // WrapTransport allows the plugin to create a modified RoundTripper that
- // attaches authorization headers (or other info) to requests.
- WrapTransport(http.RoundTripper) http.RoundTripper
- // Login allows the plugin to initialize its configuration. It must not
- // require direct user interaction.
- Login() error
-}
-
-// Factory generates an AuthProvider plugin.
-// clusterAddress is the address of the current cluster.
-// config is the initial configuration for this plugin.
-// persister allows the plugin to save updated configuration.
-type Factory func(clusterAddress string, config map[string]string, persister AuthProviderConfigPersister) (AuthProvider, error)
-
-// AuthProviderConfigPersister allows a plugin to persist configuration info
-// for just itself.
-type AuthProviderConfigPersister interface {
- Persist(map[string]string) error
-}
-
-// All registered auth provider plugins.
-var pluginsLock sync.Mutex
-var plugins = make(map[string]Factory)
-
-func RegisterAuthProviderPlugin(name string, plugin Factory) error {
- pluginsLock.Lock()
- defer pluginsLock.Unlock()
- if _, found := plugins[name]; found {
- return fmt.Errorf("Auth Provider Plugin %q was registered twice", name)
- }
- klog.V(4).Infof("Registered Auth Provider Plugin %q", name)
- plugins[name] = plugin
- return nil
-}
-
-func GetAuthProvider(clusterAddress string, apc *clientcmdapi.AuthProviderConfig, persister AuthProviderConfigPersister) (AuthProvider, error) {
- pluginsLock.Lock()
- defer pluginsLock.Unlock()
- p, ok := plugins[apc.Name]
- if !ok {
- return nil, fmt.Errorf("No Auth Provider found for name %q", apc.Name)
- }
- return p(clusterAddress, apc.Config, persister)
-}
diff --git a/vendor/k8s.io/client-go/rest/request.go b/vendor/k8s.io/client-go/rest/request.go
deleted file mode 100644
index 0570615fc..000000000
--- a/vendor/k8s.io/client-go/rest/request.go
+++ /dev/null
@@ -1,1206 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package rest
-
-import (
- "bytes"
- "context"
- "encoding/hex"
- "fmt"
- "io"
- "io/ioutil"
- "mime"
- "net/http"
- "net/url"
- "path"
- "reflect"
- "strconv"
- "strings"
- "time"
-
- "golang.org/x/net/http2"
- "k8s.io/apimachinery/pkg/api/errors"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/runtime/serializer/streaming"
- "k8s.io/apimachinery/pkg/util/net"
- "k8s.io/apimachinery/pkg/watch"
- restclientwatch "k8s.io/client-go/rest/watch"
- "k8s.io/client-go/tools/metrics"
- "k8s.io/client-go/util/flowcontrol"
- "k8s.io/klog"
-)
-
-var (
- // longThrottleLatency defines threshold for logging requests. All requests being
- // throttle for more than longThrottleLatency will be logged.
- longThrottleLatency = 50 * time.Millisecond
-)
-
-// HTTPClient is an interface for testing a request object.
-type HTTPClient interface {
- Do(req *http.Request) (*http.Response, error)
-}
-
-// ResponseWrapper is an interface for getting a response.
-// The response may be either accessed as a raw data (the whole output is put into memory) or as a stream.
-type ResponseWrapper interface {
- DoRaw() ([]byte, error)
- Stream() (io.ReadCloser, error)
-}
-
-// RequestConstructionError is returned when there's an error assembling a request.
-type RequestConstructionError struct {
- Err error
-}
-
-// Error returns a textual description of 'r'.
-func (r *RequestConstructionError) Error() string {
- return fmt.Sprintf("request construction error: '%v'", r.Err)
-}
-
-// Request allows for building up a request to a server in a chained fashion.
-// Any errors are stored until the end of your call, so you only have to
-// check once.
-type Request struct {
- // required
- client HTTPClient
- verb string
-
- baseURL *url.URL
- content ContentConfig
- serializers Serializers
-
- // generic components accessible via method setters
- pathPrefix string
- subpath string
- params url.Values
- headers http.Header
-
- // structural elements of the request that are part of the Kubernetes API conventions
- namespace string
- namespaceSet bool
- resource string
- resourceName string
- subresource string
- timeout time.Duration
-
- // output
- err error
- body io.Reader
-
- // This is only used for per-request timeouts, deadlines, and cancellations.
- ctx context.Context
-
- backoffMgr BackoffManager
- throttle flowcontrol.RateLimiter
-}
-
-// NewRequest creates a new request helper object for accessing runtime.Objects on a server.
-func NewRequest(client HTTPClient, verb string, baseURL *url.URL, versionedAPIPath string, content ContentConfig, serializers Serializers, backoff BackoffManager, throttle flowcontrol.RateLimiter, timeout time.Duration) *Request {
- if backoff == nil {
- klog.V(2).Infof("Not implementing request backoff strategy.")
- backoff = &NoBackoff{}
- }
-
- pathPrefix := "/"
- if baseURL != nil {
- pathPrefix = path.Join(pathPrefix, baseURL.Path)
- }
- r := &Request{
- client: client,
- verb: verb,
- baseURL: baseURL,
- pathPrefix: path.Join(pathPrefix, versionedAPIPath),
- content: content,
- serializers: serializers,
- backoffMgr: backoff,
- throttle: throttle,
- timeout: timeout,
- }
- switch {
- case len(content.AcceptContentTypes) > 0:
- r.SetHeader("Accept", content.AcceptContentTypes)
- case len(content.ContentType) > 0:
- r.SetHeader("Accept", content.ContentType+", */*")
- }
- return r
-}
-
-// Prefix adds segments to the relative beginning to the request path. These
-// items will be placed before the optional Namespace, Resource, or Name sections.
-// Setting AbsPath will clear any previously set Prefix segments
-func (r *Request) Prefix(segments ...string) *Request {
- if r.err != nil {
- return r
- }
- r.pathPrefix = path.Join(r.pathPrefix, path.Join(segments...))
- return r
-}
-
-// Suffix appends segments to the end of the path. These items will be placed after the prefix and optional
-// Namespace, Resource, or Name sections.
-func (r *Request) Suffix(segments ...string) *Request {
- if r.err != nil {
- return r
- }
- r.subpath = path.Join(r.subpath, path.Join(segments...))
- return r
-}
-
-// Resource sets the resource to access (<resource>/[ns/<namespace>/]<name>)
-func (r *Request) Resource(resource string) *Request {
- if r.err != nil {
- return r
- }
- if len(r.resource) != 0 {
- r.err = fmt.Errorf("resource already set to %q, cannot change to %q", r.resource, resource)
- return r
- }
- if msgs := IsValidPathSegmentName(resource); len(msgs) != 0 {
- r.err = fmt.Errorf("invalid resource %q: %v", resource, msgs)
- return r
- }
- r.resource = resource
- return r
-}
-
-// BackOff sets the request's backoff manager to the one specified,
-// or defaults to the stub implementation if nil is provided
-func (r *Request) BackOff(manager BackoffManager) *Request {
- if manager == nil {
- r.backoffMgr = &NoBackoff{}
- return r
- }
-
- r.backoffMgr = manager
- return r
-}
-
-// Throttle receives a rate-limiter and sets or replaces an existing request limiter
-func (r *Request) Throttle(limiter flowcontrol.RateLimiter) *Request {
- r.throttle = limiter
- return r
-}
-
-// SubResource sets a sub-resource path which can be multiple segments after the resource
-// name but before the suffix.
-func (r *Request) SubResource(subresources ...string) *Request {
- if r.err != nil {
- return r
- }
- subresource := path.Join(subresources...)
- if len(r.subresource) != 0 {
- r.err = fmt.Errorf("subresource already set to %q, cannot change to %q", r.resource, subresource)
- return r
- }
- for _, s := range subresources {
- if msgs := IsValidPathSegmentName(s); len(msgs) != 0 {
- r.err = fmt.Errorf("invalid subresource %q: %v", s, msgs)
- return r
- }
- }
- r.subresource = subresource
- return r
-}
-
-// Name sets the name of a resource to access (<resource>/[ns/<namespace>/]<name>)
-func (r *Request) Name(resourceName string) *Request {
- if r.err != nil {
- return r
- }
- if len(resourceName) == 0 {
- r.err = fmt.Errorf("resource name may not be empty")
- return r
- }
- if len(r.resourceName) != 0 {
- r.err = fmt.Errorf("resource name already set to %q, cannot change to %q", r.resourceName, resourceName)
- return r
- }
- if msgs := IsValidPathSegmentName(resourceName); len(msgs) != 0 {
- r.err = fmt.Errorf("invalid resource name %q: %v", resourceName, msgs)
- return r
- }
- r.resourceName = resourceName
- return r
-}
-
-// Namespace applies the namespace scope to a request (<resource>/[ns/<namespace>/]<name>)
-func (r *Request) Namespace(namespace string) *Request {
- if r.err != nil {
- return r
- }
- if r.namespaceSet {
- r.err = fmt.Errorf("namespace already set to %q, cannot change to %q", r.namespace, namespace)
- return r
- }
- if msgs := IsValidPathSegmentName(namespace); len(msgs) != 0 {
- r.err = fmt.Errorf("invalid namespace %q: %v", namespace, msgs)
- return r
- }
- r.namespaceSet = true
- r.namespace = namespace
- return r
-}
-
-// NamespaceIfScoped is a convenience function to set a namespace if scoped is true
-func (r *Request) NamespaceIfScoped(namespace string, scoped bool) *Request {
- if scoped {
- return r.Namespace(namespace)
- }
- return r
-}
-
-// AbsPath overwrites an existing path with the segments provided. Trailing slashes are preserved
-// when a single segment is passed.
-func (r *Request) AbsPath(segments ...string) *Request {
- if r.err != nil {
- return r
- }
- r.pathPrefix = path.Join(r.baseURL.Path, path.Join(segments...))
- if len(segments) == 1 && (len(r.baseURL.Path) > 1 || len(segments[0]) > 1) && strings.HasSuffix(segments[0], "/") {
- // preserve any trailing slashes for legacy behavior
- r.pathPrefix += "/"
- }
- return r
-}
-
-// RequestURI overwrites existing path and parameters with the value of the provided server relative
-// URI.
-func (r *Request) RequestURI(uri string) *Request {
- if r.err != nil {
- return r
- }
- locator, err := url.Parse(uri)
- if err != nil {
- r.err = err
- return r
- }
- r.pathPrefix = locator.Path
- if len(locator.Query()) > 0 {
- if r.params == nil {
- r.params = make(url.Values)
- }
- for k, v := range locator.Query() {
- r.params[k] = v
- }
- }
- return r
-}
-
-// Param creates a query parameter with the given string value.
-func (r *Request) Param(paramName, s string) *Request {
- if r.err != nil {
- return r
- }
- return r.setParam(paramName, s)
-}
-
-// VersionedParams will take the provided object, serialize it to a map[string][]string using the
-// implicit RESTClient API version and the default parameter codec, and then add those as parameters
-// to the request. Use this to provide versioned query parameters from client libraries.
-// VersionedParams will not write query parameters that have omitempty set and are empty. If a
-// parameter has already been set it is appended to (Params and VersionedParams are additive).
-func (r *Request) VersionedParams(obj runtime.Object, codec runtime.ParameterCodec) *Request {
- return r.SpecificallyVersionedParams(obj, codec, *r.content.GroupVersion)
-}
-
-func (r *Request) SpecificallyVersionedParams(obj runtime.Object, codec runtime.ParameterCodec, version schema.GroupVersion) *Request {
- if r.err != nil {
- return r
- }
- params, err := codec.EncodeParameters(obj, version)
- if err != nil {
- r.err = err
- return r
- }
- for k, v := range params {
- if r.params == nil {
- r.params = make(url.Values)
- }
- r.params[k] = append(r.params[k], v...)
- }
- return r
-}
-
-func (r *Request) setParam(paramName, value string) *Request {
- if r.params == nil {
- r.params = make(url.Values)
- }
- r.params[paramName] = append(r.params[paramName], value)
- return r
-}
-
-func (r *Request) SetHeader(key string, values ...string) *Request {
- if r.headers == nil {
- r.headers = http.Header{}
- }
- r.headers.Del(key)
- for _, value := range values {
- r.headers.Add(key, value)
- }
- return r
-}
-
-// Timeout makes the request use the given duration as an overall timeout for the
-// request. Additionally, if set passes the value as "timeout" parameter in URL.
-func (r *Request) Timeout(d time.Duration) *Request {
- if r.err != nil {
- return r
- }
- r.timeout = d
- return r
-}
-
-// Body makes the request use obj as the body. Optional.
-// If obj is a string, try to read a file of that name.
-// If obj is a []byte, send it directly.
-// If obj is an io.Reader, use it directly.
-// If obj is a runtime.Object, marshal it correctly, and set Content-Type header.
-// If obj is a runtime.Object and nil, do nothing.
-// Otherwise, set an error.
-func (r *Request) Body(obj interface{}) *Request {
- if r.err != nil {
- return r
- }
- switch t := obj.(type) {
- case string:
- data, err := ioutil.ReadFile(t)
- if err != nil {
- r.err = err
- return r
- }
- glogBody("Request Body", data)
- r.body = bytes.NewReader(data)
- case []byte:
- glogBody("Request Body", t)
- r.body = bytes.NewReader(t)
- case io.Reader:
- r.body = t
- case runtime.Object:
- // callers may pass typed interface pointers, therefore we must check nil with reflection
- if reflect.ValueOf(t).IsNil() {
- return r
- }
- data, err := runtime.Encode(r.serializers.Encoder, t)
- if err != nil {
- r.err = err
- return r
- }
- glogBody("Request Body", data)
- r.body = bytes.NewReader(data)
- r.SetHeader("Content-Type", r.content.ContentType)
- default:
- r.err = fmt.Errorf("unknown type used for body: %+v", obj)
- }
- return r
-}
-
-// Context adds a context to the request. Contexts are only used for
-// timeouts, deadlines, and cancellations.
-func (r *Request) Context(ctx context.Context) *Request {
- r.ctx = ctx
- return r
-}
-
-// URL returns the current working URL.
-func (r *Request) URL() *url.URL {
- p := r.pathPrefix
- if r.namespaceSet && len(r.namespace) > 0 {
- p = path.Join(p, "namespaces", r.namespace)
- }
- if len(r.resource) != 0 {
- p = path.Join(p, strings.ToLower(r.resource))
- }
- // Join trims trailing slashes, so preserve r.pathPrefix's trailing slash for backwards compatibility if nothing was changed
- if len(r.resourceName) != 0 || len(r.subpath) != 0 || len(r.subresource) != 0 {
- p = path.Join(p, r.resourceName, r.subresource, r.subpath)
- }
-
- finalURL := &url.URL{}
- if r.baseURL != nil {
- *finalURL = *r.baseURL
- }
- finalURL.Path = p
-
- query := url.Values{}
- for key, values := range r.params {
- for _, value := range values {
- query.Add(key, value)
- }
- }
-
- // timeout is handled specially here.
- if r.timeout != 0 {
- query.Set("timeout", r.timeout.String())
- }
- finalURL.RawQuery = query.Encode()
- return finalURL
-}
-
-// finalURLTemplate is similar to URL(), but will make all specific parameter values equal
-// - instead of name or namespace, "{name}" and "{namespace}" will be used, and all query
-// parameters will be reset. This creates a copy of the url so as not to change the
-// underlying object.
-func (r Request) finalURLTemplate() url.URL {
- newParams := url.Values{}
- v := []string{"{value}"}
- for k := range r.params {
- newParams[k] = v
- }
- r.params = newParams
- url := r.URL()
- segments := strings.Split(r.URL().Path, "/")
- groupIndex := 0
- index := 0
- if r.URL() != nil && r.baseURL != nil && strings.Contains(r.URL().Path, r.baseURL.Path) {
- groupIndex += len(strings.Split(r.baseURL.Path, "/"))
- }
- if groupIndex >= len(segments) {
- return *url
- }
-
- const CoreGroupPrefix = "api"
- const NamedGroupPrefix = "apis"
- isCoreGroup := segments[groupIndex] == CoreGroupPrefix
- isNamedGroup := segments[groupIndex] == NamedGroupPrefix
- if isCoreGroup {
- // checking the case of core group with /api/v1/... format
- index = groupIndex + 2
- } else if isNamedGroup {
- // checking the case of named group with /apis/apps/v1/... format
- index = groupIndex + 3
- } else {
- // this should not happen that the only two possibilities are /api... and /apis..., just want to put an
- // outlet here in case more API groups are added in future if ever possible:
- // https://kubernetes.io/docs/concepts/overview/kubernetes-api/#api-groups
- // if a wrong API groups name is encountered, return the {prefix} for url.Path
- url.Path = "/{prefix}"
- url.RawQuery = ""
- return *url
- }
- //switch segLength := len(segments) - index; segLength {
- switch {
- // case len(segments) - index == 1:
- // resource (with no name) do nothing
- case len(segments)-index == 2:
- // /$RESOURCE/$NAME: replace $NAME with {name}
- segments[index+1] = "{name}"
- case len(segments)-index == 3:
- if segments[index+2] == "finalize" || segments[index+2] == "status" {
- // /$RESOURCE/$NAME/$SUBRESOURCE: replace $NAME with {name}
- segments[index+1] = "{name}"
- } else {
- // /namespace/$NAMESPACE/$RESOURCE: replace $NAMESPACE with {namespace}
- segments[index+1] = "{namespace}"
- }
- case len(segments)-index >= 4:
- segments[index+1] = "{namespace}"
- // /namespace/$NAMESPACE/$RESOURCE/$NAME: replace $NAMESPACE with {namespace}, $NAME with {name}
- if segments[index+3] != "finalize" && segments[index+3] != "status" {
- // /$RESOURCE/$NAME/$SUBRESOURCE: replace $NAME with {name}
- segments[index+3] = "{name}"
- }
- }
- url.Path = path.Join(segments...)
- return *url
-}
-
-func (r *Request) tryThrottle() {
- now := time.Now()
- if r.throttle != nil {
- r.throttle.Accept()
- }
- if latency := time.Since(now); latency > longThrottleLatency {
- klog.V(4).Infof("Throttling request took %v, request: %s:%s", latency, r.verb, r.URL().String())
- }
-}
-
-// Watch attempts to begin watching the requested location.
-// Returns a watch.Interface, or an error.
-func (r *Request) Watch() (watch.Interface, error) {
- return r.WatchWithSpecificDecoders(
- func(body io.ReadCloser) streaming.Decoder {
- framer := r.serializers.Framer.NewFrameReader(body)
- return streaming.NewDecoder(framer, r.serializers.StreamingSerializer)
- },
- r.serializers.Decoder,
- )
-}
-
-// WatchWithSpecificDecoders attempts to begin watching the requested location with a *different* decoder.
-// Turns out that you want one "standard" decoder for the watch event and one "personal" decoder for the content
-// Returns a watch.Interface, or an error.
-func (r *Request) WatchWithSpecificDecoders(wrapperDecoderFn func(io.ReadCloser) streaming.Decoder, embeddedDecoder runtime.Decoder) (watch.Interface, error) {
- // We specifically don't want to rate limit watches, so we
- // don't use r.throttle here.
- if r.err != nil {
- return nil, r.err
- }
- if r.serializers.Framer == nil {
- return nil, fmt.Errorf("watching resources is not possible with this client (content-type: %s)", r.content.ContentType)
- }
-
- url := r.URL().String()
- req, err := http.NewRequest(r.verb, url, r.body)
- if err != nil {
- return nil, err
- }
- if r.ctx != nil {
- req = req.WithContext(r.ctx)
- }
- req.Header = r.headers
- client := r.client
- if client == nil {
- client = http.DefaultClient
- }
- r.backoffMgr.Sleep(r.backoffMgr.CalculateBackoff(r.URL()))
- resp, err := client.Do(req)
- updateURLMetrics(r, resp, err)
- if r.baseURL != nil {
- if err != nil {
- r.backoffMgr.UpdateBackoff(r.baseURL, err, 0)
- } else {
- r.backoffMgr.UpdateBackoff(r.baseURL, err, resp.StatusCode)
- }
- }
- if err != nil {
- // The watch stream mechanism handles many common partial data errors, so closed
- // connections can be retried in many cases.
- if net.IsProbableEOF(err) {
- return watch.NewEmptyWatch(), nil
- }
- return nil, err
- }
- if resp.StatusCode != http.StatusOK {
- defer resp.Body.Close()
- if result := r.transformResponse(resp, req); result.err != nil {
- return nil, result.err
- }
- return nil, fmt.Errorf("for request %s, got status: %v", url, resp.StatusCode)
- }
- wrapperDecoder := wrapperDecoderFn(resp.Body)
- return watch.NewStreamWatcher(
- restclientwatch.NewDecoder(wrapperDecoder, embeddedDecoder),
- // use 500 to indicate that the cause of the error is unknown - other error codes
- // are more specific to HTTP interactions, and set a reason
- errors.NewClientErrorReporter(http.StatusInternalServerError, r.verb, "ClientWatchDecoding"),
- ), nil
-}
-
-// updateURLMetrics is a convenience function for pushing metrics.
-// It also handles corner cases for incomplete/invalid request data.
-func updateURLMetrics(req *Request, resp *http.Response, err error) {
- url := "none"
- if req.baseURL != nil {
- url = req.baseURL.Host
- }
-
- // Errors can be arbitrary strings. Unbound label cardinality is not suitable for a metric
- // system so we just report them as `<error>`.
- if err != nil {
- metrics.RequestResult.Increment("<error>", req.verb, url)
- } else {
- //Metrics for failure codes
- metrics.RequestResult.Increment(strconv.Itoa(resp.StatusCode), req.verb, url)
- }
-}
-
-// Stream formats and executes the request, and offers streaming of the response.
-// Returns io.ReadCloser which could be used for streaming of the response, or an error
-// Any non-2xx http status code causes an error. If we get a non-2xx code, we try to convert the body into an APIStatus object.
-// If we can, we return that as an error. Otherwise, we create an error that lists the http status and the content of the response.
-func (r *Request) Stream() (io.ReadCloser, error) {
- if r.err != nil {
- return nil, r.err
- }
-
- r.tryThrottle()
-
- url := r.URL().String()
- req, err := http.NewRequest(r.verb, url, nil)
- if err != nil {
- return nil, err
- }
- if r.ctx != nil {
- req = req.WithContext(r.ctx)
- }
- req.Header = r.headers
- client := r.client
- if client == nil {
- client = http.DefaultClient
- }
- r.backoffMgr.Sleep(r.backoffMgr.CalculateBackoff(r.URL()))
- resp, err := client.Do(req)
- updateURLMetrics(r, resp, err)
- if r.baseURL != nil {
- if err != nil {
- r.backoffMgr.UpdateBackoff(r.URL(), err, 0)
- } else {
- r.backoffMgr.UpdateBackoff(r.URL(), err, resp.StatusCode)
- }
- }
- if err != nil {
- return nil, err
- }
-
- switch {
- case (resp.StatusCode >= 200) && (resp.StatusCode < 300):
- return resp.Body, nil
-
- default:
- // ensure we close the body before returning the error
- defer resp.Body.Close()
-
- result := r.transformResponse(resp, req)
- err := result.Error()
- if err == nil {
- err = fmt.Errorf("%d while accessing %v: %s", result.statusCode, url, string(result.body))
- }
- return nil, err
- }
-}
-
-// request connects to the server and invokes the provided function when a server response is
-// received. It handles retry behavior and up front validation of requests. It will invoke
-// fn at most once. It will return an error if a problem occurred prior to connecting to the
-// server - the provided function is responsible for handling server errors.
-func (r *Request) request(fn func(*http.Request, *http.Response)) error {
- //Metrics for total request latency
- start := time.Now()
- defer func() {
- metrics.RequestLatency.Observe(r.verb, r.finalURLTemplate(), time.Since(start))
- }()
-
- if r.err != nil {
- klog.V(4).Infof("Error in request: %v", r.err)
- return r.err
- }
-
- // TODO: added to catch programmer errors (invoking operations with an object with an empty namespace)
- if (r.verb == "GET" || r.verb == "PUT" || r.verb == "DELETE") && r.namespaceSet && len(r.resourceName) > 0 && len(r.namespace) == 0 {
- return fmt.Errorf("an empty namespace may not be set when a resource name is provided")
- }
- if (r.verb == "POST") && r.namespaceSet && len(r.namespace) == 0 {
- return fmt.Errorf("an empty namespace may not be set during creation")
- }
-
- client := r.client
- if client == nil {
- client = http.DefaultClient
- }
-
- // Right now we make about ten retry attempts if we get a Retry-After response.
- maxRetries := 10
- retries := 0
- for {
- url := r.URL().String()
- req, err := http.NewRequest(r.verb, url, r.body)
- if err != nil {
- return err
- }
- if r.timeout > 0 {
- if r.ctx == nil {
- r.ctx = context.Background()
- }
- var cancelFn context.CancelFunc
- r.ctx, cancelFn = context.WithTimeout(r.ctx, r.timeout)
- defer cancelFn()
- }
- if r.ctx != nil {
- req = req.WithContext(r.ctx)
- }
- req.Header = r.headers
-
- r.backoffMgr.Sleep(r.backoffMgr.CalculateBackoff(r.URL()))
- if retries > 0 {
- // We are retrying the request that we already send to apiserver
- // at least once before.
- // This request should also be throttled with the client-internal throttler.
- r.tryThrottle()
- }
- resp, err := client.Do(req)
- updateURLMetrics(r, resp, err)
- if err != nil {
- r.backoffMgr.UpdateBackoff(r.URL(), err, 0)
- } else {
- r.backoffMgr.UpdateBackoff(r.URL(), err, resp.StatusCode)
- }
- if err != nil {
- // "Connection reset by peer" is usually a transient error.
- // Thus in case of "GET" operations, we simply retry it.
- // We are not automatically retrying "write" operations, as
- // they are not idempotent.
- if !net.IsConnectionReset(err) || r.verb != "GET" {
- return err
- }
- // For the purpose of retry, we set the artificial "retry-after" response.
- // TODO: Should we clean the original response if it exists?
- resp = &http.Response{
- StatusCode: http.StatusInternalServerError,
- Header: http.Header{"Retry-After": []string{"1"}},
- Body: ioutil.NopCloser(bytes.NewReader([]byte{})),
- }
- }
-
- done := func() bool {
- // Ensure the response body is fully read and closed
- // before we reconnect, so that we reuse the same TCP
- // connection.
- defer func() {
- const maxBodySlurpSize = 2 << 10
- if resp.ContentLength <= maxBodySlurpSize {
- io.Copy(ioutil.Discard, &io.LimitedReader{R: resp.Body, N: maxBodySlurpSize})
- }
- resp.Body.Close()
- }()
-
- retries++
- if seconds, wait := checkWait(resp); wait && retries < maxRetries {
- if seeker, ok := r.body.(io.Seeker); ok && r.body != nil {
- _, err := seeker.Seek(0, 0)
- if err != nil {
- klog.V(4).Infof("Could not retry request, can't Seek() back to beginning of body for %T", r.body)
- fn(req, resp)
- return true
- }
- }
-
- klog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", seconds, retries, url)
- r.backoffMgr.Sleep(time.Duration(seconds) * time.Second)
- return false
- }
- fn(req, resp)
- return true
- }()
- if done {
- return nil
- }
- }
-}
-
-// Do formats and executes the request. Returns a Result object for easy response
-// processing.
-//
-// Error type:
-// * If the request can't be constructed, or an error happened earlier while building its
-// arguments: *RequestConstructionError
-// * If the server responds with a status: *errors.StatusError or *errors.UnexpectedObjectError
-// * http.Client.Do errors are returned directly.
-func (r *Request) Do() Result {
- r.tryThrottle()
-
- var result Result
- err := r.request(func(req *http.Request, resp *http.Response) {
- result = r.transformResponse(resp, req)
- })
- if err != nil {
- return Result{err: err}
- }
- return result
-}
-
-// DoRaw executes the request but does not process the response body.
-func (r *Request) DoRaw() ([]byte, error) {
- r.tryThrottle()
-
- var result Result
- err := r.request(func(req *http.Request, resp *http.Response) {
- result.body, result.err = ioutil.ReadAll(resp.Body)
- glogBody("Response Body", result.body)
- if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent {
- result.err = r.transformUnstructuredResponseError(resp, req, result.body)
- }
- })
- if err != nil {
- return nil, err
- }
- return result.body, result.err
-}
-
-// transformResponse converts an API response into a structured API object
-func (r *Request) transformResponse(resp *http.Response, req *http.Request) Result {
- var body []byte
- if resp.Body != nil {
- data, err := ioutil.ReadAll(resp.Body)
- switch err.(type) {
- case nil:
- body = data
- case http2.StreamError:
- // This is trying to catch the scenario that the server may close the connection when sending the
- // response body. This can be caused by server timeout due to a slow network connection.
- // TODO: Add test for this. Steps may be:
- // 1. client-go (or kubectl) sends a GET request.
- // 2. Apiserver sends back the headers and then part of the body
- // 3. Apiserver closes connection.
- // 4. client-go should catch this and return an error.
- klog.V(2).Infof("Stream error %#v when reading response body, may be caused by closed connection.", err)
- streamErr := fmt.Errorf("Stream error when reading response body, may be caused by closed connection. Please retry. Original error: %v", err)
- return Result{
- err: streamErr,
- }
- default:
- klog.Errorf("Unexpected error when reading response body: %v", err)
- unexpectedErr := fmt.Errorf("Unexpected error when reading response body. Please retry. Original error: %v", err)
- return Result{
- err: unexpectedErr,
- }
- }
- }
-
- glogBody("Response Body", body)
-
- // verify the content type is accurate
- contentType := resp.Header.Get("Content-Type")
- decoder := r.serializers.Decoder
- if len(contentType) > 0 && (decoder == nil || (len(r.content.ContentType) > 0 && contentType != r.content.ContentType)) {
- mediaType, params, err := mime.ParseMediaType(contentType)
- if err != nil {
- return Result{err: errors.NewInternalError(err)}
- }
- decoder, err = r.serializers.RenegotiatedDecoder(mediaType, params)
- if err != nil {
- // if we fail to negotiate a decoder, treat this as an unstructured error
- switch {
- case resp.StatusCode == http.StatusSwitchingProtocols:
- // no-op, we've been upgraded
- case resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent:
- return Result{err: r.transformUnstructuredResponseError(resp, req, body)}
- }
- return Result{
- body: body,
- contentType: contentType,
- statusCode: resp.StatusCode,
- }
- }
- }
-
- switch {
- case resp.StatusCode == http.StatusSwitchingProtocols:
- // no-op, we've been upgraded
- case resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent:
- // calculate an unstructured error from the response which the Result object may use if the caller
- // did not return a structured error.
- retryAfter, _ := retryAfterSeconds(resp)
- err := r.newUnstructuredResponseError(body, isTextResponse(resp), resp.StatusCode, req.Method, retryAfter)
- return Result{
- body: body,
- contentType: contentType,
- statusCode: resp.StatusCode,
- decoder: decoder,
- err: err,
- }
- }
-
- return Result{
- body: body,
- contentType: contentType,
- statusCode: resp.StatusCode,
- decoder: decoder,
- }
-}
-
-// truncateBody decides if the body should be truncated, based on the glog Verbosity.
-func truncateBody(body string) string {
- max := 0
- switch {
- case bool(klog.V(10)):
- return body
- case bool(klog.V(9)):
- max = 10240
- case bool(klog.V(8)):
- max = 1024
- }
-
- if len(body) <= max {
- return body
- }
-
- return body[:max] + fmt.Sprintf(" [truncated %d chars]", len(body)-max)
-}
-
-// glogBody logs a body output that could be either JSON or protobuf. It explicitly guards against
-// allocating a new string for the body output unless necessary. Uses a simple heuristic to determine
-// whether the body is printable.
-func glogBody(prefix string, body []byte) {
- if klog.V(8) {
- if bytes.IndexFunc(body, func(r rune) bool {
- return r < 0x0a
- }) != -1 {
- klog.Infof("%s:\n%s", prefix, truncateBody(hex.Dump(body)))
- } else {
- klog.Infof("%s: %s", prefix, truncateBody(string(body)))
- }
- }
-}
-
-// maxUnstructuredResponseTextBytes is an upper bound on how much output to include in the unstructured error.
-const maxUnstructuredResponseTextBytes = 2048
-
-// transformUnstructuredResponseError handles an error from the server that is not in a structured form.
-// It is expected to transform any response that is not recognizable as a clear server sent error from the
-// K8S API using the information provided with the request. In practice, HTTP proxies and client libraries
-// introduce a level of uncertainty to the responses returned by servers that in common use result in
-// unexpected responses. The rough structure is:
-//
-// 1. Assume the server sends you something sane - JSON + well defined error objects + proper codes
-// - this is the happy path
-// - when you get this output, trust what the server sends
-// 2. Guard against empty fields / bodies in received JSON and attempt to cull sufficient info from them to
-// generate a reasonable facsimile of the original failure.
-// - Be sure to use a distinct error type or flag that allows a client to distinguish between this and error 1 above
-// 3. Handle true disconnect failures / completely malformed data by moving up to a more generic client error
-// 4. Distinguish between various connection failures like SSL certificates, timeouts, proxy errors, unexpected
-// initial contact, the presence of mismatched body contents from posted content types
-// - Give these a separate distinct error type and capture as much as possible of the original message
-//
-// TODO: introduce transformation of generic http.Client.Do() errors that separates 4.
-func (r *Request) transformUnstructuredResponseError(resp *http.Response, req *http.Request, body []byte) error {
- if body == nil && resp.Body != nil {
- if data, err := ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: maxUnstructuredResponseTextBytes}); err == nil {
- body = data
- }
- }
- retryAfter, _ := retryAfterSeconds(resp)
- return r.newUnstructuredResponseError(body, isTextResponse(resp), resp.StatusCode, req.Method, retryAfter)
-}
-
-// newUnstructuredResponseError instantiates the appropriate generic error for the provided input. It also logs the body.
-func (r *Request) newUnstructuredResponseError(body []byte, isTextResponse bool, statusCode int, method string, retryAfter int) error {
- // cap the amount of output we create
- if len(body) > maxUnstructuredResponseTextBytes {
- body = body[:maxUnstructuredResponseTextBytes]
- }
-
- message := "unknown"
- if isTextResponse {
- message = strings.TrimSpace(string(body))
- }
- var groupResource schema.GroupResource
- if len(r.resource) > 0 {
- groupResource.Group = r.content.GroupVersion.Group
- groupResource.Resource = r.resource
- }
- return errors.NewGenericServerResponse(
- statusCode,
- method,
- groupResource,
- r.resourceName,
- message,
- retryAfter,
- true,
- )
-}
-
-// isTextResponse returns true if the response appears to be a textual media type.
-func isTextResponse(resp *http.Response) bool {
- contentType := resp.Header.Get("Content-Type")
- if len(contentType) == 0 {
- return true
- }
- media, _, err := mime.ParseMediaType(contentType)
- if err != nil {
- return false
- }
- return strings.HasPrefix(media, "text/")
-}
-
-// checkWait returns true along with a number of seconds if the server instructed us to wait
-// before retrying.
-func checkWait(resp *http.Response) (int, bool) {
- switch r := resp.StatusCode; {
- // any 500 error code and 429 can trigger a wait
- case r == http.StatusTooManyRequests, r >= 500:
- default:
- return 0, false
- }
- i, ok := retryAfterSeconds(resp)
- return i, ok
-}
-
-// retryAfterSeconds returns the value of the Retry-After header and true, or 0 and false if
-// the header was missing or not a valid number.
-func retryAfterSeconds(resp *http.Response) (int, bool) {
- if h := resp.Header.Get("Retry-After"); len(h) > 0 {
- if i, err := strconv.Atoi(h); err == nil {
- return i, true
- }
- }
- return 0, false
-}
-
-// Result contains the result of calling Request.Do().
-type Result struct {
- body []byte
- contentType string
- err error
- statusCode int
-
- decoder runtime.Decoder
-}
-
-// Raw returns the raw result.
-func (r Result) Raw() ([]byte, error) {
- return r.body, r.err
-}
-
-// Get returns the result as an object, which means it passes through the decoder.
-// If the returned object is of type Status and has .Status != StatusSuccess, the
-// additional information in Status will be used to enrich the error.
-func (r Result) Get() (runtime.Object, error) {
- if r.err != nil {
- // Check whether the result has a Status object in the body and prefer that.
- return nil, r.Error()
- }
- if r.decoder == nil {
- return nil, fmt.Errorf("serializer for %s doesn't exist", r.contentType)
- }
-
- // decode, but if the result is Status return that as an error instead.
- out, _, err := r.decoder.Decode(r.body, nil, nil)
- if err != nil {
- return nil, err
- }
- switch t := out.(type) {
- case *metav1.Status:
- // any status besides StatusSuccess is considered an error.
- if t.Status != metav1.StatusSuccess {
- return nil, errors.FromObject(t)
- }
- }
- return out, nil
-}
-
-// StatusCode returns the HTTP status code of the request. (Only valid if no
-// error was returned.)
-func (r Result) StatusCode(statusCode *int) Result {
- *statusCode = r.statusCode
- return r
-}
-
-// Into stores the result into obj, if possible. If obj is nil it is ignored.
-// If the returned object is of type Status and has .Status != StatusSuccess, the
-// additional information in Status will be used to enrich the error.
-func (r Result) Into(obj runtime.Object) error {
- if r.err != nil {
- // Check whether the result has a Status object in the body and prefer that.
- return r.Error()
- }
- if r.decoder == nil {
- return fmt.Errorf("serializer for %s doesn't exist", r.contentType)
- }
- if len(r.body) == 0 {
- return fmt.Errorf("0-length response with status code: %d and content type: %s",
- r.statusCode, r.contentType)
- }
-
- out, _, err := r.decoder.Decode(r.body, nil, obj)
- if err != nil || out == obj {
- return err
- }
- // if a different object is returned, see if it is Status and avoid double decoding
- // the object.
- switch t := out.(type) {
- case *metav1.Status:
- // any status besides StatusSuccess is considered an error.
- if t.Status != metav1.StatusSuccess {
- return errors.FromObject(t)
- }
- }
- return nil
-}
-
-// WasCreated updates the provided bool pointer to whether the server returned
-// 201 created or a different response.
-func (r Result) WasCreated(wasCreated *bool) Result {
- *wasCreated = r.statusCode == http.StatusCreated
- return r
-}
-
-// Error returns the error executing the request, nil if no error occurred.
-// If the returned object is of type Status and has Status != StatusSuccess, the
-// additional information in Status will be used to enrich the error.
-// See the Request.Do() comment for what errors you might get.
-func (r Result) Error() error {
- // if we have received an unexpected server error, and we have a body and decoder, we can try to extract
- // a Status object.
- if r.err == nil || !errors.IsUnexpectedServerError(r.err) || len(r.body) == 0 || r.decoder == nil {
- return r.err
- }
-
- // attempt to convert the body into a Status object
- // to be backwards compatible with old servers that do not return a version, default to "v1"
- out, _, err := r.decoder.Decode(r.body, &schema.GroupVersionKind{Version: "v1"}, nil)
- if err != nil {
- klog.V(5).Infof("body was not decodable (unable to check for Status): %v", err)
- return r.err
- }
- switch t := out.(type) {
- case *metav1.Status:
- // because we default the kind, we *must* check for StatusFailure
- if t.Status == metav1.StatusFailure {
- return errors.FromObject(t)
- }
- }
- return r.err
-}
-
-// NameMayNotBe specifies strings that cannot be used as names specified as path segments (like the REST API or etcd store)
-var NameMayNotBe = []string{".", ".."}
-
-// NameMayNotContain specifies substrings that cannot be used in names specified as path segments (like the REST API or etcd store)
-var NameMayNotContain = []string{"/", "%"}
-
-// IsValidPathSegmentName validates the name can be safely encoded as a path segment
-func IsValidPathSegmentName(name string) []string {
- for _, illegalName := range NameMayNotBe {
- if name == illegalName {
- return []string{fmt.Sprintf(`may not be '%s'`, illegalName)}
- }
- }
-
- var errors []string
- for _, illegalContent := range NameMayNotContain {
- if strings.Contains(name, illegalContent) {
- errors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))
- }
- }
-
- return errors
-}
-
-// IsValidPathSegmentPrefix validates the name can be used as a prefix for a name which will be encoded as a path segment
-// It does not check for exact matches with disallowed names, since an arbitrary suffix might make the name valid
-func IsValidPathSegmentPrefix(name string) []string {
- var errors []string
- for _, illegalContent := range NameMayNotContain {
- if strings.Contains(name, illegalContent) {
- errors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))
- }
- }
-
- return errors
-}
-
-// ValidatePathSegmentName validates the name can be safely encoded as a path segment
-func ValidatePathSegmentName(name string, prefix bool) []string {
- if prefix {
- return IsValidPathSegmentPrefix(name)
- }
- return IsValidPathSegmentName(name)
-}
diff --git a/vendor/k8s.io/client-go/rest/transport.go b/vendor/k8s.io/client-go/rest/transport.go
deleted file mode 100644
index de33ecbfc..000000000
--- a/vendor/k8s.io/client-go/rest/transport.go
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package rest
-
-import (
- "crypto/tls"
- "errors"
- "net/http"
-
- "k8s.io/client-go/plugin/pkg/client/auth/exec"
- "k8s.io/client-go/transport"
-)
-
-// TLSConfigFor returns a tls.Config that will provide the transport level security defined
-// by the provided Config. Will return nil if no transport level security is requested.
-func TLSConfigFor(config *Config) (*tls.Config, error) {
- cfg, err := config.TransportConfig()
- if err != nil {
- return nil, err
- }
- return transport.TLSConfigFor(cfg)
-}
-
-// TransportFor returns an http.RoundTripper that will provide the authentication
-// or transport level security defined by the provided Config. Will return the
-// default http.DefaultTransport if no special case behavior is needed.
-func TransportFor(config *Config) (http.RoundTripper, error) {
- cfg, err := config.TransportConfig()
- if err != nil {
- return nil, err
- }
- return transport.New(cfg)
-}
-
-// HTTPWrappersForConfig wraps a round tripper with any relevant layered behavior from the
-// config. Exposed to allow more clients that need HTTP-like behavior but then must hijack
-// the underlying connection (like WebSocket or HTTP2 clients). Pure HTTP clients should use
-// the higher level TransportFor or RESTClientFor methods.
-func HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTripper, error) {
- cfg, err := config.TransportConfig()
- if err != nil {
- return nil, err
- }
- return transport.HTTPWrappersForConfig(cfg, rt)
-}
-
-// TransportConfig converts a client config to an appropriate transport config.
-func (c *Config) TransportConfig() (*transport.Config, error) {
- conf := &transport.Config{
- UserAgent: c.UserAgent,
- Transport: c.Transport,
- WrapTransport: c.WrapTransport,
- TLS: transport.TLSConfig{
- Insecure: c.Insecure,
- ServerName: c.ServerName,
- CAFile: c.CAFile,
- CAData: c.CAData,
- CertFile: c.CertFile,
- CertData: c.CertData,
- KeyFile: c.KeyFile,
- KeyData: c.KeyData,
- },
- Username: c.Username,
- Password: c.Password,
- BearerToken: c.BearerToken,
- BearerTokenFile: c.BearerTokenFile,
- Impersonate: transport.ImpersonationConfig{
- UserName: c.Impersonate.UserName,
- Groups: c.Impersonate.Groups,
- Extra: c.Impersonate.Extra,
- },
- Dial: c.Dial,
- }
-
- if c.ExecProvider != nil && c.AuthProvider != nil {
- return nil, errors.New("execProvider and authProvider cannot be used in combination")
- }
-
- if c.ExecProvider != nil {
- provider, err := exec.GetAuthenticator(c.ExecProvider)
- if err != nil {
- return nil, err
- }
- if err := provider.UpdateTransportConfig(conf); err != nil {
- return nil, err
- }
- }
- if c.AuthProvider != nil {
- provider, err := GetAuthProvider(c.Host, c.AuthProvider, c.AuthConfigPersister)
- if err != nil {
- return nil, err
- }
- conf.Wrap(provider.WrapTransport)
- }
- return conf, nil
-}
-
-// Wrap adds a transport middleware function that will give the caller
-// an opportunity to wrap the underlying http.RoundTripper prior to the
-// first API call being made. The provided function is invoked after any
-// existing transport wrappers are invoked.
-func (c *Config) Wrap(fn transport.WrapperFunc) {
- c.WrapTransport = transport.Wrappers(c.WrapTransport, fn)
-}
diff --git a/vendor/k8s.io/client-go/rest/url_utils.go b/vendor/k8s.io/client-go/rest/url_utils.go
deleted file mode 100644
index a56d1838d..000000000
--- a/vendor/k8s.io/client-go/rest/url_utils.go
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
-Copyright 2016 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package rest
-
-import (
- "fmt"
- "net/url"
- "path"
-
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// DefaultServerURL converts a host, host:port, or URL string to the default base server API path
-// to use with a Client at a given API version following the standard conventions for a
-// Kubernetes API.
-func DefaultServerURL(host, apiPath string, groupVersion schema.GroupVersion, defaultTLS bool) (*url.URL, string, error) {
- if host == "" {
- return nil, "", fmt.Errorf("host must be a URL or a host:port pair")
- }
- base := host
- hostURL, err := url.Parse(base)
- if err != nil || hostURL.Scheme == "" || hostURL.Host == "" {
- scheme := "http://"
- if defaultTLS {
- scheme = "https://"
- }
- hostURL, err = url.Parse(scheme + base)
- if err != nil {
- return nil, "", err
- }
- if hostURL.Path != "" && hostURL.Path != "/" {
- return nil, "", fmt.Errorf("host must be a URL or a host:port pair: %q", base)
- }
- }
-
- // hostURL.Path is optional; a non-empty Path is treated as a prefix that is to be applied to
- // all URIs used to access the host. this is useful when there's a proxy in front of the
- // apiserver that has relocated the apiserver endpoints, forwarding all requests from, for
- // example, /a/b/c to the apiserver. in this case the Path should be /a/b/c.
- //
- // if running without a frontend proxy (that changes the location of the apiserver), then
- // hostURL.Path should be blank.
- //
- // versionedAPIPath, a path relative to baseURL.Path, points to a versioned API base
- versionedAPIPath := DefaultVersionedAPIPath(apiPath, groupVersion)
-
- return hostURL, versionedAPIPath, nil
-}
-
-// DefaultVersionedAPIPathFor constructs the default path for the given group version, assuming the given
-// API path, following the standard conventions of the Kubernetes API.
-func DefaultVersionedAPIPath(apiPath string, groupVersion schema.GroupVersion) string {
- versionedAPIPath := path.Join("/", apiPath)
-
- // Add the version to the end of the path
- if len(groupVersion.Group) > 0 {
- versionedAPIPath = path.Join(versionedAPIPath, groupVersion.Group, groupVersion.Version)
-
- } else {
- versionedAPIPath = path.Join(versionedAPIPath, groupVersion.Version)
- }
-
- return versionedAPIPath
-}
-
-// defaultServerUrlFor is shared between IsConfigTransportTLS and RESTClientFor. It
-// requires Host and Version to be set prior to being called.
-func defaultServerUrlFor(config *Config) (*url.URL, string, error) {
- // TODO: move the default to secure when the apiserver supports TLS by default
- // config.Insecure is taken to mean "I want HTTPS but don't bother checking the certs against a CA."
- hasCA := len(config.CAFile) != 0 || len(config.CAData) != 0
- hasCert := len(config.CertFile) != 0 || len(config.CertData) != 0
- defaultTLS := hasCA || hasCert || config.Insecure
- host := config.Host
- if host == "" {
- host = "localhost"
- }
-
- if config.GroupVersion != nil {
- return DefaultServerURL(host, config.APIPath, *config.GroupVersion, defaultTLS)
- }
- return DefaultServerURL(host, config.APIPath, schema.GroupVersion{}, defaultTLS)
-}
diff --git a/vendor/k8s.io/client-go/rest/urlbackoff.go b/vendor/k8s.io/client-go/rest/urlbackoff.go
deleted file mode 100644
index d00e42f86..000000000
--- a/vendor/k8s.io/client-go/rest/urlbackoff.go
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package rest
-
-import (
- "net/url"
- "time"
-
- "k8s.io/apimachinery/pkg/util/sets"
- "k8s.io/client-go/util/flowcontrol"
- "k8s.io/klog"
-)
-
-// Set of resp. Codes that we backoff for.
-// In general these should be errors that indicate a server is overloaded.
-// These shouldn't be configured by any user, we set them based on conventions
-// described in
-var serverIsOverloadedSet = sets.NewInt(429)
-var maxResponseCode = 499
-
-type BackoffManager interface {
- UpdateBackoff(actualUrl *url.URL, err error, responseCode int)
- CalculateBackoff(actualUrl *url.URL) time.Duration
- Sleep(d time.Duration)
-}
-
-// URLBackoff struct implements the semantics on top of Backoff which
-// we need for URL specific exponential backoff.
-type URLBackoff struct {
- // Uses backoff as underlying implementation.
- Backoff *flowcontrol.Backoff
-}
-
-// NoBackoff is a stub implementation, can be used for mocking or else as a default.
-type NoBackoff struct {
-}
-
-func (n *NoBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) {
- // do nothing.
-}
-
-func (n *NoBackoff) CalculateBackoff(actualUrl *url.URL) time.Duration {
- return 0 * time.Second
-}
-
-func (n *NoBackoff) Sleep(d time.Duration) {
- time.Sleep(d)
-}
-
-// Disable makes the backoff trivial, i.e., sets it to zero. This might be used
-// by tests which want to run 1000s of mock requests without slowing down.
-func (b *URLBackoff) Disable() {
- klog.V(4).Infof("Disabling backoff strategy")
- b.Backoff = flowcontrol.NewBackOff(0*time.Second, 0*time.Second)
-}
-
-// baseUrlKey returns the key which urls will be mapped to.
-// For example, 127.0.0.1:8080/api/v2/abcde -> 127.0.0.1:8080.
-func (b *URLBackoff) baseUrlKey(rawurl *url.URL) string {
- // Simple implementation for now, just the host.
- // We may backoff specific paths (i.e. "pods") differentially
- // in the future.
- host, err := url.Parse(rawurl.String())
- if err != nil {
- klog.V(4).Infof("Error extracting url: %v", rawurl)
- panic("bad url!")
- }
- return host.Host
-}
-
-// UpdateBackoff updates backoff metadata
-func (b *URLBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) {
- // range for retry counts that we store is [0,13]
- if responseCode > maxResponseCode || serverIsOverloadedSet.Has(responseCode) {
- b.Backoff.Next(b.baseUrlKey(actualUrl), b.Backoff.Clock.Now())
- return
- } else if responseCode >= 300 || err != nil {
- klog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err)
- }
-
- //If we got this far, there is no backoff required for this URL anymore.
- b.Backoff.Reset(b.baseUrlKey(actualUrl))
-}
-
-// CalculateBackoff takes a url and back's off exponentially,
-// based on its knowledge of existing failures.
-func (b *URLBackoff) CalculateBackoff(actualUrl *url.URL) time.Duration {
- return b.Backoff.Get(b.baseUrlKey(actualUrl))
-}
-
-func (b *URLBackoff) Sleep(d time.Duration) {
- b.Backoff.Clock.Sleep(d)
-}
diff --git a/vendor/k8s.io/client-go/rest/watch/decoder.go b/vendor/k8s.io/client-go/rest/watch/decoder.go
deleted file mode 100644
index e95c020b2..000000000
--- a/vendor/k8s.io/client-go/rest/watch/decoder.go
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package versioned
-
-import (
- "fmt"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/serializer/streaming"
- "k8s.io/apimachinery/pkg/watch"
-)
-
-// Decoder implements the watch.Decoder interface for io.ReadClosers that
-// have contents which consist of a series of watchEvent objects encoded
-// with the given streaming decoder. The internal objects will be then
-// decoded by the embedded decoder.
-type Decoder struct {
- decoder streaming.Decoder
- embeddedDecoder runtime.Decoder
-}
-
-// NewDecoder creates an Decoder for the given writer and codec.
-func NewDecoder(decoder streaming.Decoder, embeddedDecoder runtime.Decoder) *Decoder {
- return &Decoder{
- decoder: decoder,
- embeddedDecoder: embeddedDecoder,
- }
-}
-
-// Decode blocks until it can return the next object in the reader. Returns an error
-// if the reader is closed or an object can't be decoded.
-func (d *Decoder) Decode() (watch.EventType, runtime.Object, error) {
- var got metav1.WatchEvent
- res, _, err := d.decoder.Decode(nil, &got)
- if err != nil {
- return "", nil, err
- }
- if res != &got {
- return "", nil, fmt.Errorf("unable to decode to metav1.Event")
- }
- switch got.Type {
- case string(watch.Added), string(watch.Modified), string(watch.Deleted), string(watch.Error), string(watch.Bookmark):
- default:
- return "", nil, fmt.Errorf("got invalid watch event type: %v", got.Type)
- }
-
- obj, err := runtime.Decode(d.embeddedDecoder, got.Object.Raw)
- if err != nil {
- return "", nil, fmt.Errorf("unable to decode watch event: %v", err)
- }
- return watch.EventType(got.Type), obj, nil
-}
-
-// Close closes the underlying r.
-func (d *Decoder) Close() {
- d.decoder.Close()
-}
diff --git a/vendor/k8s.io/client-go/rest/watch/encoder.go b/vendor/k8s.io/client-go/rest/watch/encoder.go
deleted file mode 100644
index e55aa12d9..000000000
--- a/vendor/k8s.io/client-go/rest/watch/encoder.go
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package versioned
-
-import (
- "encoding/json"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/serializer/streaming"
- "k8s.io/apimachinery/pkg/watch"
-)
-
-// Encoder serializes watch.Events into io.Writer. The internal objects
-// are encoded using embedded encoder, and the outer Event is serialized
-// using encoder.
-// TODO: this type is only used by tests
-type Encoder struct {
- encoder streaming.Encoder
- embeddedEncoder runtime.Encoder
-}
-
-func NewEncoder(encoder streaming.Encoder, embeddedEncoder runtime.Encoder) *Encoder {
- return &Encoder{
- encoder: encoder,
- embeddedEncoder: embeddedEncoder,
- }
-}
-
-// Encode writes an event to the writer. Returns an error
-// if the writer is closed or an object can't be encoded.
-func (e *Encoder) Encode(event *watch.Event) error {
- data, err := runtime.Encode(e.embeddedEncoder, event.Object)
- if err != nil {
- return err
- }
- // FIXME: get rid of json.RawMessage.
- return e.encoder.Encode(&metav1.WatchEvent{
- Type: string(event.Type),
- Object: runtime.RawExtension{Raw: json.RawMessage(data)},
- })
-}
diff --git a/vendor/k8s.io/client-go/rest/zz_generated.deepcopy.go b/vendor/k8s.io/client-go/rest/zz_generated.deepcopy.go
deleted file mode 100644
index c1ab45f33..000000000
--- a/vendor/k8s.io/client-go/rest/zz_generated.deepcopy.go
+++ /dev/null
@@ -1,52 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Code generated by deepcopy-gen. DO NOT EDIT.
-
-package rest
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *TLSClientConfig) DeepCopyInto(out *TLSClientConfig) {
- *out = *in
- if in.CertData != nil {
- in, out := &in.CertData, &out.CertData
- *out = make([]byte, len(*in))
- copy(*out, *in)
- }
- if in.KeyData != nil {
- in, out := &in.KeyData, &out.KeyData
- *out = make([]byte, len(*in))
- copy(*out, *in)
- }
- if in.CAData != nil {
- in, out := &in.CAData, &out.CAData
- *out = make([]byte, len(*in))
- copy(*out, *in)
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TLSClientConfig.
-func (in *TLSClientConfig) DeepCopy() *TLSClientConfig {
- if in == nil {
- return nil
- }
- out := new(TLSClientConfig)
- in.DeepCopyInto(out)
- return out
-}
diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/doc.go b/vendor/k8s.io/client-go/tools/clientcmd/api/doc.go
deleted file mode 100644
index 5871575a6..000000000
--- a/vendor/k8s.io/client-go/tools/clientcmd/api/doc.go
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// +k8s:deepcopy-gen=package
-
-package api
diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/helpers.go b/vendor/k8s.io/client-go/tools/clientcmd/api/helpers.go
deleted file mode 100644
index 65a36936b..000000000
--- a/vendor/k8s.io/client-go/tools/clientcmd/api/helpers.go
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package api
-
-import (
- "encoding/base64"
- "errors"
- "fmt"
- "io/ioutil"
- "os"
- "path"
- "path/filepath"
-)
-
-func init() {
- sDec, _ := base64.StdEncoding.DecodeString("REDACTED+")
- redactedBytes = []byte(string(sDec))
- sDec, _ = base64.StdEncoding.DecodeString("DATA+OMITTED")
- dataOmittedBytes = []byte(string(sDec))
-}
-
-// IsConfigEmpty returns true if the config is empty.
-func IsConfigEmpty(config *Config) bool {
- return len(config.AuthInfos) == 0 && len(config.Clusters) == 0 && len(config.Contexts) == 0 &&
- len(config.CurrentContext) == 0 &&
- len(config.Preferences.Extensions) == 0 && !config.Preferences.Colors &&
- len(config.Extensions) == 0
-}
-
-// MinifyConfig read the current context and uses that to keep only the relevant pieces of config
-// This is useful for making secrets based on kubeconfig files
-func MinifyConfig(config *Config) error {
- if len(config.CurrentContext) == 0 {
- return errors.New("current-context must exist in order to minify")
- }
-
- currContext, exists := config.Contexts[config.CurrentContext]
- if !exists {
- return fmt.Errorf("cannot locate context %v", config.CurrentContext)
- }
-
- newContexts := map[string]*Context{}
- newContexts[config.CurrentContext] = currContext
-
- newClusters := map[string]*Cluster{}
- if len(currContext.Cluster) > 0 {
- if _, exists := config.Clusters[currContext.Cluster]; !exists {
- return fmt.Errorf("cannot locate cluster %v", currContext.Cluster)
- }
-
- newClusters[currContext.Cluster] = config.Clusters[currContext.Cluster]
- }
-
- newAuthInfos := map[string]*AuthInfo{}
- if len(currContext.AuthInfo) > 0 {
- if _, exists := config.AuthInfos[currContext.AuthInfo]; !exists {
- return fmt.Errorf("cannot locate user %v", currContext.AuthInfo)
- }
-
- newAuthInfos[currContext.AuthInfo] = config.AuthInfos[currContext.AuthInfo]
- }
-
- config.AuthInfos = newAuthInfos
- config.Clusters = newClusters
- config.Contexts = newContexts
-
- return nil
-}
-
-var (
- redactedBytes []byte
- dataOmittedBytes []byte
-)
-
-// Flatten redacts raw data entries from the config object for a human-readable view.
-func ShortenConfig(config *Config) {
- // trick json encoder into printing a human readable string in the raw data
- // by base64 decoding what we want to print. Relies on implementation of
- // http://golang.org/pkg/encoding/json/#Marshal using base64 to encode []byte
- for key, authInfo := range config.AuthInfos {
- if len(authInfo.ClientKeyData) > 0 {
- authInfo.ClientKeyData = redactedBytes
- }
- if len(authInfo.ClientCertificateData) > 0 {
- authInfo.ClientCertificateData = redactedBytes
- }
- config.AuthInfos[key] = authInfo
- }
- for key, cluster := range config.Clusters {
- if len(cluster.CertificateAuthorityData) > 0 {
- cluster.CertificateAuthorityData = dataOmittedBytes
- }
- config.Clusters[key] = cluster
- }
-}
-
-// Flatten changes the config object into a self contained config (useful for making secrets)
-func FlattenConfig(config *Config) error {
- for key, authInfo := range config.AuthInfos {
- baseDir, err := MakeAbs(path.Dir(authInfo.LocationOfOrigin), "")
- if err != nil {
- return err
- }
-
- if err := FlattenContent(&authInfo.ClientCertificate, &authInfo.ClientCertificateData, baseDir); err != nil {
- return err
- }
- if err := FlattenContent(&authInfo.ClientKey, &authInfo.ClientKeyData, baseDir); err != nil {
- return err
- }
-
- config.AuthInfos[key] = authInfo
- }
- for key, cluster := range config.Clusters {
- baseDir, err := MakeAbs(path.Dir(cluster.LocationOfOrigin), "")
- if err != nil {
- return err
- }
-
- if err := FlattenContent(&cluster.CertificateAuthority, &cluster.CertificateAuthorityData, baseDir); err != nil {
- return err
- }
-
- config.Clusters[key] = cluster
- }
-
- return nil
-}
-
-func FlattenContent(path *string, contents *[]byte, baseDir string) error {
- if len(*path) != 0 {
- if len(*contents) > 0 {
- return errors.New("cannot have values for both path and contents")
- }
-
- var err error
- absPath := ResolvePath(*path, baseDir)
- *contents, err = ioutil.ReadFile(absPath)
- if err != nil {
- return err
- }
-
- *path = ""
- }
-
- return nil
-}
-
-// ResolvePath returns the path as an absolute paths, relative to the given base directory
-func ResolvePath(path string, base string) string {
- // Don't resolve empty paths
- if len(path) > 0 {
- // Don't resolve absolute paths
- if !filepath.IsAbs(path) {
- return filepath.Join(base, path)
- }
- }
-
- return path
-}
-
-func MakeAbs(path, base string) (string, error) {
- if filepath.IsAbs(path) {
- return path, nil
- }
- if len(base) == 0 {
- cwd, err := os.Getwd()
- if err != nil {
- return "", err
- }
- base = cwd
- }
- return filepath.Join(base, path), nil
-}
diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/register.go b/vendor/k8s.io/client-go/tools/clientcmd/api/register.go
deleted file mode 100644
index 2eec3881c..000000000
--- a/vendor/k8s.io/client-go/tools/clientcmd/api/register.go
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package api
-
-import (
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// SchemeGroupVersion is group version used to register these objects
-// TODO this should be in the "kubeconfig" group
-var SchemeGroupVersion = schema.GroupVersion{Group: "", Version: runtime.APIVersionInternal}
-
-var (
- SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
- AddToScheme = SchemeBuilder.AddToScheme
-)
-
-func addKnownTypes(scheme *runtime.Scheme) error {
- scheme.AddKnownTypes(SchemeGroupVersion,
- &Config{},
- )
- return nil
-}
-
-func (obj *Config) GetObjectKind() schema.ObjectKind { return obj }
-func (obj *Config) SetGroupVersionKind(gvk schema.GroupVersionKind) {
- obj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind()
-}
-func (obj *Config) GroupVersionKind() schema.GroupVersionKind {
- return schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)
-}
diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/types.go b/vendor/k8s.io/client-go/tools/clientcmd/api/types.go
deleted file mode 100644
index 990a440c6..000000000
--- a/vendor/k8s.io/client-go/tools/clientcmd/api/types.go
+++ /dev/null
@@ -1,262 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package api
-
-import (
- "fmt"
-
- "k8s.io/apimachinery/pkg/runtime"
-)
-
-// Where possible, json tags match the cli argument names.
-// Top level config objects and all values required for proper functioning are not "omitempty". Any truly optional piece of config is allowed to be omitted.
-
-// Config holds the information needed to build connect to remote kubernetes clusters as a given user
-// IMPORTANT if you add fields to this struct, please update IsConfigEmpty()
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-type Config struct {
- // Legacy field from pkg/api/types.go TypeMeta.
- // TODO(jlowdermilk): remove this after eliminating downstream dependencies.
- // +optional
- Kind string `json:"kind,omitempty"`
- // Legacy field from pkg/api/types.go TypeMeta.
- // TODO(jlowdermilk): remove this after eliminating downstream dependencies.
- // +optional
- APIVersion string `json:"apiVersion,omitempty"`
- // Preferences holds general information to be use for cli interactions
- Preferences Preferences `json:"preferences"`
- // Clusters is a map of referencable names to cluster configs
- Clusters map[string]*Cluster `json:"clusters"`
- // AuthInfos is a map of referencable names to user configs
- AuthInfos map[string]*AuthInfo `json:"users"`
- // Contexts is a map of referencable names to context configs
- Contexts map[string]*Context `json:"contexts"`
- // CurrentContext is the name of the context that you would like to use by default
- CurrentContext string `json:"current-context"`
- // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields
- // +optional
- Extensions map[string]runtime.Object `json:"extensions,omitempty"`
-}
-
-// IMPORTANT if you add fields to this struct, please update IsConfigEmpty()
-type Preferences struct {
- // +optional
- Colors bool `json:"colors,omitempty"`
- // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields
- // +optional
- Extensions map[string]runtime.Object `json:"extensions,omitempty"`
-}
-
-// Cluster contains information about how to communicate with a kubernetes cluster
-type Cluster struct {
- // LocationOfOrigin indicates where this object came from. It is used for round tripping config post-merge, but never serialized.
- LocationOfOrigin string
- // Server is the address of the kubernetes cluster (https://hostname:port).
- Server string `json:"server"`
- // InsecureSkipTLSVerify skips the validity check for the server's certificate. This will make your HTTPS connections insecure.
- // +optional
- InsecureSkipTLSVerify bool `json:"insecure-skip-tls-verify,omitempty"`
- // CertificateAuthority is the path to a cert file for the certificate authority.
- // +optional
- CertificateAuthority string `json:"certificate-authority,omitempty"`
- // CertificateAuthorityData contains PEM-encoded certificate authority certificates. Overrides CertificateAuthority
- // +optional
- CertificateAuthorityData []byte `json:"certificate-authority-data,omitempty"`
- // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields
- // +optional
- Extensions map[string]runtime.Object `json:"extensions,omitempty"`
-}
-
-// AuthInfo contains information that describes identity information. This is use to tell the kubernetes cluster who you are.
-type AuthInfo struct {
- // LocationOfOrigin indicates where this object came from. It is used for round tripping config post-merge, but never serialized.
- LocationOfOrigin string
- // ClientCertificate is the path to a client cert file for TLS.
- // +optional
- ClientCertificate string `json:"client-certificate,omitempty"`
- // ClientCertificateData contains PEM-encoded data from a client cert file for TLS. Overrides ClientCertificate
- // +optional
- ClientCertificateData []byte `json:"client-certificate-data,omitempty"`
- // ClientKey is the path to a client key file for TLS.
- // +optional
- ClientKey string `json:"client-key,omitempty"`
- // ClientKeyData contains PEM-encoded data from a client key file for TLS. Overrides ClientKey
- // +optional
- ClientKeyData []byte `json:"client-key-data,omitempty"`
- // Token is the bearer token for authentication to the kubernetes cluster.
- // +optional
- Token string `json:"token,omitempty"`
- // TokenFile is a pointer to a file that contains a bearer token (as described above). If both Token and TokenFile are present, Token takes precedence.
- // +optional
- TokenFile string `json:"tokenFile,omitempty"`
- // Impersonate is the username to act-as.
- // +optional
- Impersonate string `json:"act-as,omitempty"`
- // ImpersonateGroups is the groups to imperonate.
- // +optional
- ImpersonateGroups []string `json:"act-as-groups,omitempty"`
- // ImpersonateUserExtra contains additional information for impersonated user.
- // +optional
- ImpersonateUserExtra map[string][]string `json:"act-as-user-extra,omitempty"`
- // Username is the username for basic authentication to the kubernetes cluster.
- // +optional
- Username string `json:"username,omitempty"`
- // Password is the password for basic authentication to the kubernetes cluster.
- // +optional
- Password string `json:"password,omitempty"`
- // AuthProvider specifies a custom authentication plugin for the kubernetes cluster.
- // +optional
- AuthProvider *AuthProviderConfig `json:"auth-provider,omitempty"`
- // Exec specifies a custom exec-based authentication plugin for the kubernetes cluster.
- // +optional
- Exec *ExecConfig `json:"exec,omitempty"`
- // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields
- // +optional
- Extensions map[string]runtime.Object `json:"extensions,omitempty"`
-}
-
-// Context is a tuple of references to a cluster (how do I communicate with a kubernetes cluster), a user (how do I identify myself), and a namespace (what subset of resources do I want to work with)
-type Context struct {
- // LocationOfOrigin indicates where this object came from. It is used for round tripping config post-merge, but never serialized.
- LocationOfOrigin string
- // Cluster is the name of the cluster for this context
- Cluster string `json:"cluster"`
- // AuthInfo is the name of the authInfo for this context
- AuthInfo string `json:"user"`
- // Namespace is the default namespace to use on unspecified requests
- // +optional
- Namespace string `json:"namespace,omitempty"`
- // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields
- // +optional
- Extensions map[string]runtime.Object `json:"extensions,omitempty"`
-}
-
-// AuthProviderConfig holds the configuration for a specified auth provider.
-type AuthProviderConfig struct {
- Name string `json:"name"`
- // +optional
- Config map[string]string `json:"config,omitempty"`
-}
-
-var _ fmt.Stringer = new(AuthProviderConfig)
-var _ fmt.GoStringer = new(AuthProviderConfig)
-
-// GoString implements fmt.GoStringer and sanitizes sensitive fields of
-// AuthProviderConfig to prevent accidental leaking via logs.
-func (c AuthProviderConfig) GoString() string {
- return c.String()
-}
-
-// String implements fmt.Stringer and sanitizes sensitive fields of
-// AuthProviderConfig to prevent accidental leaking via logs.
-func (c AuthProviderConfig) String() string {
- cfg := "<nil>"
- if c.Config != nil {
- cfg = "--- REDACTED ---"
- }
- return fmt.Sprintf("api.AuthProviderConfig{Name: %q, Config: map[string]string{%s}}", c.Name, cfg)
-}
-
-// ExecConfig specifies a command to provide client credentials. The command is exec'd
-// and outputs structured stdout holding credentials.
-//
-// See the client.authentiction.k8s.io API group for specifications of the exact input
-// and output format
-type ExecConfig struct {
- // Command to execute.
- Command string `json:"command"`
- // Arguments to pass to the command when executing it.
- // +optional
- Args []string `json:"args"`
- // Env defines additional environment variables to expose to the process. These
- // are unioned with the host's environment, as well as variables client-go uses
- // to pass argument to the plugin.
- // +optional
- Env []ExecEnvVar `json:"env"`
-
- // Preferred input version of the ExecInfo. The returned ExecCredentials MUST use
- // the same encoding version as the input.
- APIVersion string `json:"apiVersion,omitempty"`
-}
-
-var _ fmt.Stringer = new(ExecConfig)
-var _ fmt.GoStringer = new(ExecConfig)
-
-// GoString implements fmt.GoStringer and sanitizes sensitive fields of
-// ExecConfig to prevent accidental leaking via logs.
-func (c ExecConfig) GoString() string {
- return c.String()
-}
-
-// String implements fmt.Stringer and sanitizes sensitive fields of ExecConfig
-// to prevent accidental leaking via logs.
-func (c ExecConfig) String() string {
- var args []string
- if len(c.Args) > 0 {
- args = []string{"--- REDACTED ---"}
- }
- env := "[]ExecEnvVar(nil)"
- if len(c.Env) > 0 {
- env = "[]ExecEnvVar{--- REDACTED ---}"
- }
- return fmt.Sprintf("api.AuthProviderConfig{Command: %q, Args: %#v, Env: %s, APIVersion: %q}", c.Command, args, env, c.APIVersion)
-}
-
-// ExecEnvVar is used for setting environment variables when executing an exec-based
-// credential plugin.
-type ExecEnvVar struct {
- Name string `json:"name"`
- Value string `json:"value"`
-}
-
-// NewConfig is a convenience function that returns a new Config object with non-nil maps
-func NewConfig() *Config {
- return &Config{
- Preferences: *NewPreferences(),
- Clusters: make(map[string]*Cluster),
- AuthInfos: make(map[string]*AuthInfo),
- Contexts: make(map[string]*Context),
- Extensions: make(map[string]runtime.Object),
- }
-}
-
-// NewContext is a convenience function that returns a new Context
-// object with non-nil maps
-func NewContext() *Context {
- return &Context{Extensions: make(map[string]runtime.Object)}
-}
-
-// NewCluster is a convenience function that returns a new Cluster
-// object with non-nil maps
-func NewCluster() *Cluster {
- return &Cluster{Extensions: make(map[string]runtime.Object)}
-}
-
-// NewAuthInfo is a convenience function that returns a new AuthInfo
-// object with non-nil maps
-func NewAuthInfo() *AuthInfo {
- return &AuthInfo{
- Extensions: make(map[string]runtime.Object),
- ImpersonateUserExtra: make(map[string][]string),
- }
-}
-
-// NewPreferences is a convenience function that returns a new
-// Preferences object with non-nil maps
-func NewPreferences() *Preferences {
- return &Preferences{Extensions: make(map[string]runtime.Object)}
-}
diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/zz_generated.deepcopy.go b/vendor/k8s.io/client-go/tools/clientcmd/api/zz_generated.deepcopy.go
deleted file mode 100644
index 3240a7a98..000000000
--- a/vendor/k8s.io/client-go/tools/clientcmd/api/zz_generated.deepcopy.go
+++ /dev/null
@@ -1,324 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Code generated by deepcopy-gen. DO NOT EDIT.
-
-package api
-
-import (
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *AuthInfo) DeepCopyInto(out *AuthInfo) {
- *out = *in
- if in.ClientCertificateData != nil {
- in, out := &in.ClientCertificateData, &out.ClientCertificateData
- *out = make([]byte, len(*in))
- copy(*out, *in)
- }
- if in.ClientKeyData != nil {
- in, out := &in.ClientKeyData, &out.ClientKeyData
- *out = make([]byte, len(*in))
- copy(*out, *in)
- }
- if in.ImpersonateGroups != nil {
- in, out := &in.ImpersonateGroups, &out.ImpersonateGroups
- *out = make([]string, len(*in))
- copy(*out, *in)
- }
- if in.ImpersonateUserExtra != nil {
- in, out := &in.ImpersonateUserExtra, &out.ImpersonateUserExtra
- *out = make(map[string][]string, len(*in))
- for key, val := range *in {
- var outVal []string
- if val == nil {
- (*out)[key] = nil
- } else {
- in, out := &val, &outVal
- *out = make([]string, len(*in))
- copy(*out, *in)
- }
- (*out)[key] = outVal
- }
- }
- if in.AuthProvider != nil {
- in, out := &in.AuthProvider, &out.AuthProvider
- *out = new(AuthProviderConfig)
- (*in).DeepCopyInto(*out)
- }
- if in.Exec != nil {
- in, out := &in.Exec, &out.Exec
- *out = new(ExecConfig)
- (*in).DeepCopyInto(*out)
- }
- if in.Extensions != nil {
- in, out := &in.Extensions, &out.Extensions
- *out = make(map[string]runtime.Object, len(*in))
- for key, val := range *in {
- if val == nil {
- (*out)[key] = nil
- } else {
- (*out)[key] = val.DeepCopyObject()
- }
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AuthInfo.
-func (in *AuthInfo) DeepCopy() *AuthInfo {
- if in == nil {
- return nil
- }
- out := new(AuthInfo)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *AuthProviderConfig) DeepCopyInto(out *AuthProviderConfig) {
- *out = *in
- if in.Config != nil {
- in, out := &in.Config, &out.Config
- *out = make(map[string]string, len(*in))
- for key, val := range *in {
- (*out)[key] = val
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AuthProviderConfig.
-func (in *AuthProviderConfig) DeepCopy() *AuthProviderConfig {
- if in == nil {
- return nil
- }
- out := new(AuthProviderConfig)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *Cluster) DeepCopyInto(out *Cluster) {
- *out = *in
- if in.CertificateAuthorityData != nil {
- in, out := &in.CertificateAuthorityData, &out.CertificateAuthorityData
- *out = make([]byte, len(*in))
- copy(*out, *in)
- }
- if in.Extensions != nil {
- in, out := &in.Extensions, &out.Extensions
- *out = make(map[string]runtime.Object, len(*in))
- for key, val := range *in {
- if val == nil {
- (*out)[key] = nil
- } else {
- (*out)[key] = val.DeepCopyObject()
- }
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Cluster.
-func (in *Cluster) DeepCopy() *Cluster {
- if in == nil {
- return nil
- }
- out := new(Cluster)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *Config) DeepCopyInto(out *Config) {
- *out = *in
- in.Preferences.DeepCopyInto(&out.Preferences)
- if in.Clusters != nil {
- in, out := &in.Clusters, &out.Clusters
- *out = make(map[string]*Cluster, len(*in))
- for key, val := range *in {
- var outVal *Cluster
- if val == nil {
- (*out)[key] = nil
- } else {
- in, out := &val, &outVal
- *out = new(Cluster)
- (*in).DeepCopyInto(*out)
- }
- (*out)[key] = outVal
- }
- }
- if in.AuthInfos != nil {
- in, out := &in.AuthInfos, &out.AuthInfos
- *out = make(map[string]*AuthInfo, len(*in))
- for key, val := range *in {
- var outVal *AuthInfo
- if val == nil {
- (*out)[key] = nil
- } else {
- in, out := &val, &outVal
- *out = new(AuthInfo)
- (*in).DeepCopyInto(*out)
- }
- (*out)[key] = outVal
- }
- }
- if in.Contexts != nil {
- in, out := &in.Contexts, &out.Contexts
- *out = make(map[string]*Context, len(*in))
- for key, val := range *in {
- var outVal *Context
- if val == nil {
- (*out)[key] = nil
- } else {
- in, out := &val, &outVal
- *out = new(Context)
- (*in).DeepCopyInto(*out)
- }
- (*out)[key] = outVal
- }
- }
- if in.Extensions != nil {
- in, out := &in.Extensions, &out.Extensions
- *out = make(map[string]runtime.Object, len(*in))
- for key, val := range *in {
- if val == nil {
- (*out)[key] = nil
- } else {
- (*out)[key] = val.DeepCopyObject()
- }
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Config.
-func (in *Config) DeepCopy() *Config {
- if in == nil {
- return nil
- }
- out := new(Config)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *Config) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- }
- return nil
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *Context) DeepCopyInto(out *Context) {
- *out = *in
- if in.Extensions != nil {
- in, out := &in.Extensions, &out.Extensions
- *out = make(map[string]runtime.Object, len(*in))
- for key, val := range *in {
- if val == nil {
- (*out)[key] = nil
- } else {
- (*out)[key] = val.DeepCopyObject()
- }
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Context.
-func (in *Context) DeepCopy() *Context {
- if in == nil {
- return nil
- }
- out := new(Context)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ExecConfig) DeepCopyInto(out *ExecConfig) {
- *out = *in
- if in.Args != nil {
- in, out := &in.Args, &out.Args
- *out = make([]string, len(*in))
- copy(*out, *in)
- }
- if in.Env != nil {
- in, out := &in.Env, &out.Env
- *out = make([]ExecEnvVar, len(*in))
- copy(*out, *in)
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecConfig.
-func (in *ExecConfig) DeepCopy() *ExecConfig {
- if in == nil {
- return nil
- }
- out := new(ExecConfig)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ExecEnvVar) DeepCopyInto(out *ExecEnvVar) {
- *out = *in
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecEnvVar.
-func (in *ExecEnvVar) DeepCopy() *ExecEnvVar {
- if in == nil {
- return nil
- }
- out := new(ExecEnvVar)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *Preferences) DeepCopyInto(out *Preferences) {
- *out = *in
- if in.Extensions != nil {
- in, out := &in.Extensions, &out.Extensions
- *out = make(map[string]runtime.Object, len(*in))
- for key, val := range *in {
- if val == nil {
- (*out)[key] = nil
- } else {
- (*out)[key] = val.DeepCopyObject()
- }
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Preferences.
-func (in *Preferences) DeepCopy() *Preferences {
- if in == nil {
- return nil
- }
- out := new(Preferences)
- in.DeepCopyInto(out)
- return out
-}
diff --git a/vendor/k8s.io/client-go/tools/metrics/OWNERS b/vendor/k8s.io/client-go/tools/metrics/OWNERS
deleted file mode 100644
index f150be536..000000000
--- a/vendor/k8s.io/client-go/tools/metrics/OWNERS
+++ /dev/null
@@ -1,9 +0,0 @@
-# See the OWNERS docs at https://go.k8s.io/owners
-
-reviewers:
-- wojtek-t
-- eparis
-- krousey
-- jayunit100
-- fgrzadkowski
-- tmrts
diff --git a/vendor/k8s.io/client-go/tools/metrics/metrics.go b/vendor/k8s.io/client-go/tools/metrics/metrics.go
deleted file mode 100644
index a01306c65..000000000
--- a/vendor/k8s.io/client-go/tools/metrics/metrics.go
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package metrics provides abstractions for registering which metrics
-// to record.
-package metrics
-
-import (
- "net/url"
- "sync"
- "time"
-)
-
-var registerMetrics sync.Once
-
-// LatencyMetric observes client latency partitioned by verb and url.
-type LatencyMetric interface {
- Observe(verb string, u url.URL, latency time.Duration)
-}
-
-// ResultMetric counts response codes partitioned by method and host.
-type ResultMetric interface {
- Increment(code string, method string, host string)
-}
-
-var (
- // RequestLatency is the latency metric that rest clients will update.
- RequestLatency LatencyMetric = noopLatency{}
- // RequestResult is the result metric that rest clients will update.
- RequestResult ResultMetric = noopResult{}
-)
-
-// Register registers metrics for the rest client to use. This can
-// only be called once.
-func Register(lm LatencyMetric, rm ResultMetric) {
- registerMetrics.Do(func() {
- RequestLatency = lm
- RequestResult = rm
- })
-}
-
-type noopLatency struct{}
-
-func (noopLatency) Observe(string, url.URL, time.Duration) {}
-
-type noopResult struct{}
-
-func (noopResult) Increment(string, string, string) {}
diff --git a/vendor/k8s.io/client-go/tools/remotecommand/doc.go b/vendor/k8s.io/client-go/tools/remotecommand/doc.go
deleted file mode 100644
index ac06a9cd3..000000000
--- a/vendor/k8s.io/client-go/tools/remotecommand/doc.go
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package remotecommand adds support for executing commands in containers,
-// with support for separate stdin, stdout, and stderr streams, as well as
-// TTY.
-package remotecommand // import "k8s.io/client-go/tools/remotecommand"
diff --git a/vendor/k8s.io/client-go/tools/remotecommand/errorstream.go b/vendor/k8s.io/client-go/tools/remotecommand/errorstream.go
deleted file mode 100644
index 360276b65..000000000
--- a/vendor/k8s.io/client-go/tools/remotecommand/errorstream.go
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
-Copyright 2016 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package remotecommand
-
-import (
- "fmt"
- "io"
- "io/ioutil"
-
- "k8s.io/apimachinery/pkg/util/runtime"
-)
-
-// errorStreamDecoder interprets the data on the error channel and creates a go error object from it.
-type errorStreamDecoder interface {
- decode(message []byte) error
-}
-
-// watchErrorStream watches the errorStream for remote command error data,
-// decodes it with the given errorStreamDecoder, sends the decoded error (or nil if the remote
-// command exited successfully) to the returned error channel, and closes it.
-// This function returns immediately.
-func watchErrorStream(errorStream io.Reader, d errorStreamDecoder) chan error {
- errorChan := make(chan error)
-
- go func() {
- defer runtime.HandleCrash()
-
- message, err := ioutil.ReadAll(errorStream)
- switch {
- case err != nil && err != io.EOF:
- errorChan <- fmt.Errorf("error reading from error stream: %s", err)
- case len(message) > 0:
- errorChan <- d.decode(message)
- default:
- errorChan <- nil
- }
- close(errorChan)
- }()
-
- return errorChan
-}
diff --git a/vendor/k8s.io/client-go/tools/remotecommand/reader.go b/vendor/k8s.io/client-go/tools/remotecommand/reader.go
deleted file mode 100644
index d1f1be34c..000000000
--- a/vendor/k8s.io/client-go/tools/remotecommand/reader.go
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package remotecommand
-
-import (
- "io"
-)
-
-// readerWrapper delegates to an io.Reader so that only the io.Reader interface is implemented,
-// to keep io.Copy from doing things we don't want when copying from the reader to the data stream.
-//
-// If the Stdin io.Reader provided to remotecommand implements a WriteTo function (like bytes.Buffer does[1]),
-// io.Copy calls that method[2] to attempt to write the entire buffer to the stream in one call.
-// That results in an oversized call to spdystream.Stream#Write [3],
-// which results in a single oversized data frame[4] that is too large.
-//
-// [1] https://golang.org/pkg/bytes/#Buffer.WriteTo
-// [2] https://golang.org/pkg/io/#Copy
-// [3] https://github.com/kubernetes/kubernetes/blob/90295640ef87db9daa0144c5617afe889e7992b2/vendor/github.com/docker/spdystream/stream.go#L66-L73
-// [4] https://github.com/kubernetes/kubernetes/blob/90295640ef87db9daa0144c5617afe889e7992b2/vendor/github.com/docker/spdystream/spdy/write.go#L302-L304
-type readerWrapper struct {
- reader io.Reader
-}
-
-func (r readerWrapper) Read(p []byte) (int, error) {
- return r.reader.Read(p)
-}
diff --git a/vendor/k8s.io/client-go/tools/remotecommand/remotecommand.go b/vendor/k8s.io/client-go/tools/remotecommand/remotecommand.go
deleted file mode 100644
index 892d8d105..000000000
--- a/vendor/k8s.io/client-go/tools/remotecommand/remotecommand.go
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package remotecommand
-
-import (
- "fmt"
- "io"
- "net/http"
- "net/url"
-
- "k8s.io/klog"
-
- "k8s.io/apimachinery/pkg/util/httpstream"
- "k8s.io/apimachinery/pkg/util/remotecommand"
- restclient "k8s.io/client-go/rest"
- spdy "k8s.io/client-go/transport/spdy"
-)
-
-// StreamOptions holds information pertaining to the current streaming session:
-// input/output streams, if the client is requesting a TTY, and a terminal size queue to
-// support terminal resizing.
-type StreamOptions struct {
- Stdin io.Reader
- Stdout io.Writer
- Stderr io.Writer
- Tty bool
- TerminalSizeQueue TerminalSizeQueue
-}
-
-// Executor is an interface for transporting shell-style streams.
-type Executor interface {
- // Stream initiates the transport of the standard shell streams. It will transport any
- // non-nil stream to a remote system, and return an error if a problem occurs. If tty
- // is set, the stderr stream is not used (raw TTY manages stdout and stderr over the
- // stdout stream).
- Stream(options StreamOptions) error
-}
-
-type streamCreator interface {
- CreateStream(headers http.Header) (httpstream.Stream, error)
-}
-
-type streamProtocolHandler interface {
- stream(conn streamCreator) error
-}
-
-// streamExecutor handles transporting standard shell streams over an httpstream connection.
-type streamExecutor struct {
- upgrader spdy.Upgrader
- transport http.RoundTripper
-
- method string
- url *url.URL
- protocols []string
-}
-
-// NewSPDYExecutor connects to the provided server and upgrades the connection to
-// multiplexed bidirectional streams.
-func NewSPDYExecutor(config *restclient.Config, method string, url *url.URL) (Executor, error) {
- wrapper, upgradeRoundTripper, err := spdy.RoundTripperFor(config)
- if err != nil {
- return nil, err
- }
- return NewSPDYExecutorForTransports(wrapper, upgradeRoundTripper, method, url)
-}
-
-// NewSPDYExecutorForTransports connects to the provided server using the given transport,
-// upgrades the response using the given upgrader to multiplexed bidirectional streams.
-func NewSPDYExecutorForTransports(transport http.RoundTripper, upgrader spdy.Upgrader, method string, url *url.URL) (Executor, error) {
- return NewSPDYExecutorForProtocols(
- transport, upgrader, method, url,
- remotecommand.StreamProtocolV4Name,
- remotecommand.StreamProtocolV3Name,
- remotecommand.StreamProtocolV2Name,
- remotecommand.StreamProtocolV1Name,
- )
-}
-
-// NewSPDYExecutorForProtocols connects to the provided server and upgrades the connection to
-// multiplexed bidirectional streams using only the provided protocols. Exposed for testing, most
-// callers should use NewSPDYExecutor or NewSPDYExecutorForTransports.
-func NewSPDYExecutorForProtocols(transport http.RoundTripper, upgrader spdy.Upgrader, method string, url *url.URL, protocols ...string) (Executor, error) {
- return &streamExecutor{
- upgrader: upgrader,
- transport: transport,
- method: method,
- url: url,
- protocols: protocols,
- }, nil
-}
-
-// Stream opens a protocol streamer to the server and streams until a client closes
-// the connection or the server disconnects.
-func (e *streamExecutor) Stream(options StreamOptions) error {
- req, err := http.NewRequest(e.method, e.url.String(), nil)
- if err != nil {
- return fmt.Errorf("error creating request: %v", err)
- }
-
- conn, protocol, err := spdy.Negotiate(
- e.upgrader,
- &http.Client{Transport: e.transport},
- req,
- e.protocols...,
- )
- if err != nil {
- return err
- }
- defer conn.Close()
-
- var streamer streamProtocolHandler
-
- switch protocol {
- case remotecommand.StreamProtocolV4Name:
- streamer = newStreamProtocolV4(options)
- case remotecommand.StreamProtocolV3Name:
- streamer = newStreamProtocolV3(options)
- case remotecommand.StreamProtocolV2Name:
- streamer = newStreamProtocolV2(options)
- case "":
- klog.V(4).Infof("The server did not negotiate a streaming protocol version. Falling back to %s", remotecommand.StreamProtocolV1Name)
- fallthrough
- case remotecommand.StreamProtocolV1Name:
- streamer = newStreamProtocolV1(options)
- }
-
- return streamer.stream(conn)
-}
diff --git a/vendor/k8s.io/client-go/tools/remotecommand/resize.go b/vendor/k8s.io/client-go/tools/remotecommand/resize.go
deleted file mode 100644
index c838f21ba..000000000
--- a/vendor/k8s.io/client-go/tools/remotecommand/resize.go
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
-Copyright 2017 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package remotecommand
-
-// TerminalSize and TerminalSizeQueue was a part of k8s.io/kubernetes/pkg/util/term
-// and were moved in order to decouple client from other term dependencies
-
-// TerminalSize represents the width and height of a terminal.
-type TerminalSize struct {
- Width uint16
- Height uint16
-}
-
-// TerminalSizeQueue is capable of returning terminal resize events as they occur.
-type TerminalSizeQueue interface {
- // Next returns the new terminal size after the terminal has been resized. It returns nil when
- // monitoring has been stopped.
- Next() *TerminalSize
-}
diff --git a/vendor/k8s.io/client-go/tools/remotecommand/v1.go b/vendor/k8s.io/client-go/tools/remotecommand/v1.go
deleted file mode 100644
index 4120f1f5f..000000000
--- a/vendor/k8s.io/client-go/tools/remotecommand/v1.go
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package remotecommand
-
-import (
- "fmt"
- "io"
- "io/ioutil"
- "net/http"
-
- "k8s.io/api/core/v1"
- "k8s.io/apimachinery/pkg/util/httpstream"
- "k8s.io/klog"
-)
-
-// streamProtocolV1 implements the first version of the streaming exec & attach
-// protocol. This version has some bugs, such as not being able to detect when
-// non-interactive stdin data has ended. See http://issues.k8s.io/13394 and
-// http://issues.k8s.io/13395 for more details.
-type streamProtocolV1 struct {
- StreamOptions
-
- errorStream httpstream.Stream
- remoteStdin httpstream.Stream
- remoteStdout httpstream.Stream
- remoteStderr httpstream.Stream
-}
-
-var _ streamProtocolHandler = &streamProtocolV1{}
-
-func newStreamProtocolV1(options StreamOptions) streamProtocolHandler {
- return &streamProtocolV1{
- StreamOptions: options,
- }
-}
-
-func (p *streamProtocolV1) stream(conn streamCreator) error {
- doneChan := make(chan struct{}, 2)
- errorChan := make(chan error)
-
- cp := func(s string, dst io.Writer, src io.Reader) {
- klog.V(6).Infof("Copying %s", s)
- defer klog.V(6).Infof("Done copying %s", s)
- if _, err := io.Copy(dst, src); err != nil && err != io.EOF {
- klog.Errorf("Error copying %s: %v", s, err)
- }
- if s == v1.StreamTypeStdout || s == v1.StreamTypeStderr {
- doneChan <- struct{}{}
- }
- }
-
- // set up all the streams first
- var err error
- headers := http.Header{}
- headers.Set(v1.StreamType, v1.StreamTypeError)
- p.errorStream, err = conn.CreateStream(headers)
- if err != nil {
- return err
- }
- defer p.errorStream.Reset()
-
- // Create all the streams first, then start the copy goroutines. The server doesn't start its copy
- // goroutines until it's received all of the streams. If the client creates the stdin stream and
- // immediately begins copying stdin data to the server, it's possible to overwhelm and wedge the
- // spdy frame handler in the server so that it is full of unprocessed frames. The frames aren't
- // getting processed because the server hasn't started its copying, and it won't do that until it
- // gets all the streams. By creating all the streams first, we ensure that the server is ready to
- // process data before the client starts sending any. See https://issues.k8s.io/16373 for more info.
- if p.Stdin != nil {
- headers.Set(v1.StreamType, v1.StreamTypeStdin)
- p.remoteStdin, err = conn.CreateStream(headers)
- if err != nil {
- return err
- }
- defer p.remoteStdin.Reset()
- }
-
- if p.Stdout != nil {
- headers.Set(v1.StreamType, v1.StreamTypeStdout)
- p.remoteStdout, err = conn.CreateStream(headers)
- if err != nil {
- return err
- }
- defer p.remoteStdout.Reset()
- }
-
- if p.Stderr != nil && !p.Tty {
- headers.Set(v1.StreamType, v1.StreamTypeStderr)
- p.remoteStderr, err = conn.CreateStream(headers)
- if err != nil {
- return err
- }
- defer p.remoteStderr.Reset()
- }
-
- // now that all the streams have been created, proceed with reading & copying
-
- // always read from errorStream
- go func() {
- message, err := ioutil.ReadAll(p.errorStream)
- if err != nil && err != io.EOF {
- errorChan <- fmt.Errorf("Error reading from error stream: %s", err)
- return
- }
- if len(message) > 0 {
- errorChan <- fmt.Errorf("Error executing remote command: %s", message)
- return
- }
- }()
-
- if p.Stdin != nil {
- // TODO this goroutine will never exit cleanly (the io.Copy never unblocks)
- // because stdin is not closed until the process exits. If we try to call
- // stdin.Close(), it returns no error but doesn't unblock the copy. It will
- // exit when the process exits, instead.
- go cp(v1.StreamTypeStdin, p.remoteStdin, readerWrapper{p.Stdin})
- }
-
- waitCount := 0
- completedStreams := 0
-
- if p.Stdout != nil {
- waitCount++
- go cp(v1.StreamTypeStdout, p.Stdout, p.remoteStdout)
- }
-
- if p.Stderr != nil && !p.Tty {
- waitCount++
- go cp(v1.StreamTypeStderr, p.Stderr, p.remoteStderr)
- }
-
-Loop:
- for {
- select {
- case <-doneChan:
- completedStreams++
- if completedStreams == waitCount {
- break Loop
- }
- case err := <-errorChan:
- return err
- }
- }
-
- return nil
-}
diff --git a/vendor/k8s.io/client-go/tools/remotecommand/v2.go b/vendor/k8s.io/client-go/tools/remotecommand/v2.go
deleted file mode 100644
index 4b0001502..000000000
--- a/vendor/k8s.io/client-go/tools/remotecommand/v2.go
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package remotecommand
-
-import (
- "fmt"
- "io"
- "io/ioutil"
- "net/http"
- "sync"
-
- "k8s.io/api/core/v1"
- "k8s.io/apimachinery/pkg/util/runtime"
-)
-
-// streamProtocolV2 implements version 2 of the streaming protocol for attach
-// and exec. The original streaming protocol was metav1. As a result, this
-// version is referred to as version 2, even though it is the first actual
-// numbered version.
-type streamProtocolV2 struct {
- StreamOptions
-
- errorStream io.Reader
- remoteStdin io.ReadWriteCloser
- remoteStdout io.Reader
- remoteStderr io.Reader
-}
-
-var _ streamProtocolHandler = &streamProtocolV2{}
-
-func newStreamProtocolV2(options StreamOptions) streamProtocolHandler {
- return &streamProtocolV2{
- StreamOptions: options,
- }
-}
-
-func (p *streamProtocolV2) createStreams(conn streamCreator) error {
- var err error
- headers := http.Header{}
-
- // set up error stream
- headers.Set(v1.StreamType, v1.StreamTypeError)
- p.errorStream, err = conn.CreateStream(headers)
- if err != nil {
- return err
- }
-
- // set up stdin stream
- if p.Stdin != nil {
- headers.Set(v1.StreamType, v1.StreamTypeStdin)
- p.remoteStdin, err = conn.CreateStream(headers)
- if err != nil {
- return err
- }
- }
-
- // set up stdout stream
- if p.Stdout != nil {
- headers.Set(v1.StreamType, v1.StreamTypeStdout)
- p.remoteStdout, err = conn.CreateStream(headers)
- if err != nil {
- return err
- }
- }
-
- // set up stderr stream
- if p.Stderr != nil && !p.Tty {
- headers.Set(v1.StreamType, v1.StreamTypeStderr)
- p.remoteStderr, err = conn.CreateStream(headers)
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-func (p *streamProtocolV2) copyStdin() {
- if p.Stdin != nil {
- var once sync.Once
-
- // copy from client's stdin to container's stdin
- go func() {
- defer runtime.HandleCrash()
-
- // if p.stdin is noninteractive, p.g. `echo abc | kubectl exec -i <pod> -- cat`, make sure
- // we close remoteStdin as soon as the copy from p.stdin to remoteStdin finishes. Otherwise
- // the executed command will remain running.
- defer once.Do(func() { p.remoteStdin.Close() })
-
- if _, err := io.Copy(p.remoteStdin, readerWrapper{p.Stdin}); err != nil {
- runtime.HandleError(err)
- }
- }()
-
- // read from remoteStdin until the stream is closed. this is essential to
- // be able to exit interactive sessions cleanly and not leak goroutines or
- // hang the client's terminal.
- //
- // TODO we aren't using go-dockerclient any more; revisit this to determine if it's still
- // required by engine-api.
- //
- // go-dockerclient's current hijack implementation
- // (https://github.com/fsouza/go-dockerclient/blob/89f3d56d93788dfe85f864a44f85d9738fca0670/client.go#L564)
- // waits for all three streams (stdin/stdout/stderr) to finish copying
- // before returning. When hijack finishes copying stdout/stderr, it calls
- // Close() on its side of remoteStdin, which allows this copy to complete.
- // When that happens, we must Close() on our side of remoteStdin, to
- // allow the copy in hijack to complete, and hijack to return.
- go func() {
- defer runtime.HandleCrash()
- defer once.Do(func() { p.remoteStdin.Close() })
-
- // this "copy" doesn't actually read anything - it's just here to wait for
- // the server to close remoteStdin.
- if _, err := io.Copy(ioutil.Discard, p.remoteStdin); err != nil {
- runtime.HandleError(err)
- }
- }()
- }
-}
-
-func (p *streamProtocolV2) copyStdout(wg *sync.WaitGroup) {
- if p.Stdout == nil {
- return
- }
-
- wg.Add(1)
- go func() {
- defer runtime.HandleCrash()
- defer wg.Done()
-
- if _, err := io.Copy(p.Stdout, p.remoteStdout); err != nil {
- runtime.HandleError(err)
- }
- }()
-}
-
-func (p *streamProtocolV2) copyStderr(wg *sync.WaitGroup) {
- if p.Stderr == nil || p.Tty {
- return
- }
-
- wg.Add(1)
- go func() {
- defer runtime.HandleCrash()
- defer wg.Done()
-
- if _, err := io.Copy(p.Stderr, p.remoteStderr); err != nil {
- runtime.HandleError(err)
- }
- }()
-}
-
-func (p *streamProtocolV2) stream(conn streamCreator) error {
- if err := p.createStreams(conn); err != nil {
- return err
- }
-
- // now that all the streams have been created, proceed with reading & copying
-
- errorChan := watchErrorStream(p.errorStream, &errorDecoderV2{})
-
- p.copyStdin()
-
- var wg sync.WaitGroup
- p.copyStdout(&wg)
- p.copyStderr(&wg)
-
- // we're waiting for stdout/stderr to finish copying
- wg.Wait()
-
- // waits for errorStream to finish reading with an error or nil
- return <-errorChan
-}
-
-// errorDecoderV2 interprets the error channel data as plain text.
-type errorDecoderV2 struct{}
-
-func (d *errorDecoderV2) decode(message []byte) error {
- return fmt.Errorf("error executing remote command: %s", message)
-}
diff --git a/vendor/k8s.io/client-go/tools/remotecommand/v3.go b/vendor/k8s.io/client-go/tools/remotecommand/v3.go
deleted file mode 100644
index 846dd24a5..000000000
--- a/vendor/k8s.io/client-go/tools/remotecommand/v3.go
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
-Copyright 2016 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package remotecommand
-
-import (
- "encoding/json"
- "io"
- "net/http"
- "sync"
-
- "k8s.io/api/core/v1"
- "k8s.io/apimachinery/pkg/util/runtime"
-)
-
-// streamProtocolV3 implements version 3 of the streaming protocol for attach
-// and exec. This version adds support for resizing the container's terminal.
-type streamProtocolV3 struct {
- *streamProtocolV2
-
- resizeStream io.Writer
-}
-
-var _ streamProtocolHandler = &streamProtocolV3{}
-
-func newStreamProtocolV3(options StreamOptions) streamProtocolHandler {
- return &streamProtocolV3{
- streamProtocolV2: newStreamProtocolV2(options).(*streamProtocolV2),
- }
-}
-
-func (p *streamProtocolV3) createStreams(conn streamCreator) error {
- // set up the streams from v2
- if err := p.streamProtocolV2.createStreams(conn); err != nil {
- return err
- }
-
- // set up resize stream
- if p.Tty {
- headers := http.Header{}
- headers.Set(v1.StreamType, v1.StreamTypeResize)
- var err error
- p.resizeStream, err = conn.CreateStream(headers)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (p *streamProtocolV3) handleResizes() {
- if p.resizeStream == nil || p.TerminalSizeQueue == nil {
- return
- }
- go func() {
- defer runtime.HandleCrash()
-
- encoder := json.NewEncoder(p.resizeStream)
- for {
- size := p.TerminalSizeQueue.Next()
- if size == nil {
- return
- }
- if err := encoder.Encode(&size); err != nil {
- runtime.HandleError(err)
- }
- }
- }()
-}
-
-func (p *streamProtocolV3) stream(conn streamCreator) error {
- if err := p.createStreams(conn); err != nil {
- return err
- }
-
- // now that all the streams have been created, proceed with reading & copying
-
- errorChan := watchErrorStream(p.errorStream, &errorDecoderV3{})
-
- p.handleResizes()
-
- p.copyStdin()
-
- var wg sync.WaitGroup
- p.copyStdout(&wg)
- p.copyStderr(&wg)
-
- // we're waiting for stdout/stderr to finish copying
- wg.Wait()
-
- // waits for errorStream to finish reading with an error or nil
- return <-errorChan
-}
-
-type errorDecoderV3 struct {
- errorDecoderV2
-}
diff --git a/vendor/k8s.io/client-go/tools/remotecommand/v4.go b/vendor/k8s.io/client-go/tools/remotecommand/v4.go
deleted file mode 100644
index 69ca934a0..000000000
--- a/vendor/k8s.io/client-go/tools/remotecommand/v4.go
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
-Copyright 2016 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package remotecommand
-
-import (
- "encoding/json"
- "errors"
- "fmt"
- "strconv"
- "sync"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/util/remotecommand"
- "k8s.io/client-go/util/exec"
-)
-
-// streamProtocolV4 implements version 4 of the streaming protocol for attach
-// and exec. This version adds support for exit codes on the error stream through
-// the use of metav1.Status instead of plain text messages.
-type streamProtocolV4 struct {
- *streamProtocolV3
-}
-
-var _ streamProtocolHandler = &streamProtocolV4{}
-
-func newStreamProtocolV4(options StreamOptions) streamProtocolHandler {
- return &streamProtocolV4{
- streamProtocolV3: newStreamProtocolV3(options).(*streamProtocolV3),
- }
-}
-
-func (p *streamProtocolV4) createStreams(conn streamCreator) error {
- return p.streamProtocolV3.createStreams(conn)
-}
-
-func (p *streamProtocolV4) handleResizes() {
- p.streamProtocolV3.handleResizes()
-}
-
-func (p *streamProtocolV4) stream(conn streamCreator) error {
- if err := p.createStreams(conn); err != nil {
- return err
- }
-
- // now that all the streams have been created, proceed with reading & copying
-
- errorChan := watchErrorStream(p.errorStream, &errorDecoderV4{})
-
- p.handleResizes()
-
- p.copyStdin()
-
- var wg sync.WaitGroup
- p.copyStdout(&wg)
- p.copyStderr(&wg)
-
- // we're waiting for stdout/stderr to finish copying
- wg.Wait()
-
- // waits for errorStream to finish reading with an error or nil
- return <-errorChan
-}
-
-// errorDecoderV4 interprets the json-marshaled metav1.Status on the error channel
-// and creates an exec.ExitError from it.
-type errorDecoderV4 struct{}
-
-func (d *errorDecoderV4) decode(message []byte) error {
- status := metav1.Status{}
- err := json.Unmarshal(message, &status)
- if err != nil {
- return fmt.Errorf("error stream protocol error: %v in %q", err, string(message))
- }
- switch status.Status {
- case metav1.StatusSuccess:
- return nil
- case metav1.StatusFailure:
- if status.Reason == remotecommand.NonZeroExitCodeReason {
- if status.Details == nil {
- return errors.New("error stream protocol error: details must be set")
- }
- for i := range status.Details.Causes {
- c := &status.Details.Causes[i]
- if c.Type != remotecommand.ExitCodeCauseType {
- continue
- }
-
- rc, err := strconv.ParseUint(c.Message, 10, 8)
- if err != nil {
- return fmt.Errorf("error stream protocol error: invalid exit code value %q", c.Message)
- }
- return exec.CodeExitError{
- Err: fmt.Errorf("command terminated with exit code %d", rc),
- Code: int(rc),
- }
- }
-
- return fmt.Errorf("error stream protocol error: no %s cause given", remotecommand.ExitCodeCauseType)
- }
- default:
- return errors.New("error stream protocol error: unknown error")
- }
-
- return fmt.Errorf(status.Message)
-}
diff --git a/vendor/k8s.io/client-go/transport/OWNERS b/vendor/k8s.io/client-go/transport/OWNERS
deleted file mode 100644
index a52176903..000000000
--- a/vendor/k8s.io/client-go/transport/OWNERS
+++ /dev/null
@@ -1,9 +0,0 @@
-# See the OWNERS docs at https://go.k8s.io/owners
-
-reviewers:
-- smarterclayton
-- wojtek-t
-- deads2k
-- liggitt
-- krousey
-- caesarxuchao
diff --git a/vendor/k8s.io/client-go/transport/cache.go b/vendor/k8s.io/client-go/transport/cache.go
deleted file mode 100644
index 7cffe2a5f..000000000
--- a/vendor/k8s.io/client-go/transport/cache.go
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package transport
-
-import (
- "fmt"
- "net"
- "net/http"
- "sync"
- "time"
-
- utilnet "k8s.io/apimachinery/pkg/util/net"
-)
-
-// TlsTransportCache caches TLS http.RoundTrippers different configurations. The
-// same RoundTripper will be returned for configs with identical TLS options If
-// the config has no custom TLS options, http.DefaultTransport is returned.
-type tlsTransportCache struct {
- mu sync.Mutex
- transports map[tlsCacheKey]*http.Transport
-}
-
-const idleConnsPerHost = 25
-
-var tlsCache = &tlsTransportCache{transports: make(map[tlsCacheKey]*http.Transport)}
-
-type tlsCacheKey struct {
- insecure bool
- caData string
- certData string
- keyData string
- getCert string
- serverName string
- dial string
-}
-
-func (t tlsCacheKey) String() string {
- keyText := "<none>"
- if len(t.keyData) > 0 {
- keyText = "<redacted>"
- }
- return fmt.Sprintf("insecure:%v, caData:%#v, certData:%#v, keyData:%s, getCert: %s, serverName:%s, dial:%s", t.insecure, t.caData, t.certData, keyText, t.getCert, t.serverName, t.dial)
-}
-
-func (c *tlsTransportCache) get(config *Config) (http.RoundTripper, error) {
- key, err := tlsConfigKey(config)
- if err != nil {
- return nil, err
- }
-
- // Ensure we only create a single transport for the given TLS options
- c.mu.Lock()
- defer c.mu.Unlock()
-
- // See if we already have a custom transport for this config
- if t, ok := c.transports[key]; ok {
- return t, nil
- }
-
- // Get the TLS options for this client config
- tlsConfig, err := TLSConfigFor(config)
- if err != nil {
- return nil, err
- }
- // The options didn't require a custom TLS config
- if tlsConfig == nil && config.Dial == nil {
- return http.DefaultTransport, nil
- }
-
- dial := config.Dial
- if dial == nil {
- dial = (&net.Dialer{
- Timeout: 30 * time.Second,
- KeepAlive: 30 * time.Second,
- }).DialContext
- }
- // Cache a single transport for these options
- c.transports[key] = utilnet.SetTransportDefaults(&http.Transport{
- Proxy: http.ProxyFromEnvironment,
- TLSHandshakeTimeout: 10 * time.Second,
- TLSClientConfig: tlsConfig,
- MaxIdleConnsPerHost: idleConnsPerHost,
- DialContext: dial,
- })
- return c.transports[key], nil
-}
-
-// tlsConfigKey returns a unique key for tls.Config objects returned from TLSConfigFor
-func tlsConfigKey(c *Config) (tlsCacheKey, error) {
- // Make sure ca/key/cert content is loaded
- if err := loadTLSFiles(c); err != nil {
- return tlsCacheKey{}, err
- }
- return tlsCacheKey{
- insecure: c.TLS.Insecure,
- caData: string(c.TLS.CAData),
- certData: string(c.TLS.CertData),
- keyData: string(c.TLS.KeyData),
- getCert: fmt.Sprintf("%p", c.TLS.GetCert),
- serverName: c.TLS.ServerName,
- dial: fmt.Sprintf("%p", c.Dial),
- }, nil
-}
diff --git a/vendor/k8s.io/client-go/transport/config.go b/vendor/k8s.io/client-go/transport/config.go
deleted file mode 100644
index 5de0a2cb1..000000000
--- a/vendor/k8s.io/client-go/transport/config.go
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package transport
-
-import (
- "context"
- "crypto/tls"
- "net"
- "net/http"
-)
-
-// Config holds various options for establishing a transport.
-type Config struct {
- // UserAgent is an optional field that specifies the caller of this
- // request.
- UserAgent string
-
- // The base TLS configuration for this transport.
- TLS TLSConfig
-
- // Username and password for basic authentication
- Username string
- Password string
-
- // Bearer token for authentication
- BearerToken string
-
- // Path to a file containing a BearerToken.
- // If set, the contents are periodically read.
- // The last successfully read value takes precedence over BearerToken.
- BearerTokenFile string
-
- // Impersonate is the config that this Config will impersonate using
- Impersonate ImpersonationConfig
-
- // Transport may be used for custom HTTP behavior. This attribute may
- // not be specified with the TLS client certificate options. Use
- // WrapTransport for most client level operations.
- Transport http.RoundTripper
-
- // WrapTransport will be invoked for custom HTTP behavior after the
- // underlying transport is initialized (either the transport created
- // from TLSClientConfig, Transport, or http.DefaultTransport). The
- // config may layer other RoundTrippers on top of the returned
- // RoundTripper.
- //
- // A future release will change this field to an array. Use config.Wrap()
- // instead of setting this value directly.
- WrapTransport WrapperFunc
-
- // Dial specifies the dial function for creating unencrypted TCP connections.
- Dial func(ctx context.Context, network, address string) (net.Conn, error)
-}
-
-// ImpersonationConfig has all the available impersonation options
-type ImpersonationConfig struct {
- // UserName matches user.Info.GetName()
- UserName string
- // Groups matches user.Info.GetGroups()
- Groups []string
- // Extra matches user.Info.GetExtra()
- Extra map[string][]string
-}
-
-// HasCA returns whether the configuration has a certificate authority or not.
-func (c *Config) HasCA() bool {
- return len(c.TLS.CAData) > 0 || len(c.TLS.CAFile) > 0
-}
-
-// HasBasicAuth returns whether the configuration has basic authentication or not.
-func (c *Config) HasBasicAuth() bool {
- return len(c.Username) != 0
-}
-
-// HasTokenAuth returns whether the configuration has token authentication or not.
-func (c *Config) HasTokenAuth() bool {
- return len(c.BearerToken) != 0 || len(c.BearerTokenFile) != 0
-}
-
-// HasCertAuth returns whether the configuration has certificate authentication or not.
-func (c *Config) HasCertAuth() bool {
- return (len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0) && (len(c.TLS.KeyData) != 0 || len(c.TLS.KeyFile) != 0)
-}
-
-// HasCertCallbacks returns whether the configuration has certificate callback or not.
-func (c *Config) HasCertCallback() bool {
- return c.TLS.GetCert != nil
-}
-
-// Wrap adds a transport middleware function that will give the caller
-// an opportunity to wrap the underlying http.RoundTripper prior to the
-// first API call being made. The provided function is invoked after any
-// existing transport wrappers are invoked.
-func (c *Config) Wrap(fn WrapperFunc) {
- c.WrapTransport = Wrappers(c.WrapTransport, fn)
-}
-
-// TLSConfig holds the information needed to set up a TLS transport.
-type TLSConfig struct {
- CAFile string // Path of the PEM-encoded server trusted root certificates.
- CertFile string // Path of the PEM-encoded client certificate.
- KeyFile string // Path of the PEM-encoded client key.
-
- Insecure bool // Server should be accessed without verifying the certificate. For testing only.
- ServerName string // Override for the server name passed to the server for SNI and used to verify certificates.
-
- CAData []byte // Bytes of the PEM-encoded server trusted root certificates. Supercedes CAFile.
- CertData []byte // Bytes of the PEM-encoded client certificate. Supercedes CertFile.
- KeyData []byte // Bytes of the PEM-encoded client key. Supercedes KeyFile.
-
- GetCert func() (*tls.Certificate, error) // Callback that returns a TLS client certificate. CertData, CertFile, KeyData and KeyFile supercede this field.
-}
diff --git a/vendor/k8s.io/client-go/transport/round_trippers.go b/vendor/k8s.io/client-go/transport/round_trippers.go
deleted file mode 100644
index 117a9c8c4..000000000
--- a/vendor/k8s.io/client-go/transport/round_trippers.go
+++ /dev/null
@@ -1,564 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package transport
-
-import (
- "fmt"
- "net/http"
- "strings"
- "time"
-
- "golang.org/x/oauth2"
- "k8s.io/klog"
-
- utilnet "k8s.io/apimachinery/pkg/util/net"
-)
-
-// HTTPWrappersForConfig wraps a round tripper with any relevant layered
-// behavior from the config. Exposed to allow more clients that need HTTP-like
-// behavior but then must hijack the underlying connection (like WebSocket or
-// HTTP2 clients). Pure HTTP clients should use the RoundTripper returned from
-// New.
-func HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTripper, error) {
- if config.WrapTransport != nil {
- rt = config.WrapTransport(rt)
- }
-
- rt = DebugWrappers(rt)
-
- // Set authentication wrappers
- switch {
- case config.HasBasicAuth() && config.HasTokenAuth():
- return nil, fmt.Errorf("username/password or bearer token may be set, but not both")
- case config.HasTokenAuth():
- var err error
- rt, err = NewBearerAuthWithRefreshRoundTripper(config.BearerToken, config.BearerTokenFile, rt)
- if err != nil {
- return nil, err
- }
- case config.HasBasicAuth():
- rt = NewBasicAuthRoundTripper(config.Username, config.Password, rt)
- }
- if len(config.UserAgent) > 0 {
- rt = NewUserAgentRoundTripper(config.UserAgent, rt)
- }
- if len(config.Impersonate.UserName) > 0 ||
- len(config.Impersonate.Groups) > 0 ||
- len(config.Impersonate.Extra) > 0 {
- rt = NewImpersonatingRoundTripper(config.Impersonate, rt)
- }
- return rt, nil
-}
-
-// DebugWrappers wraps a round tripper and logs based on the current log level.
-func DebugWrappers(rt http.RoundTripper) http.RoundTripper {
- switch {
- case bool(klog.V(9)):
- rt = newDebuggingRoundTripper(rt, debugCurlCommand, debugURLTiming, debugResponseHeaders)
- case bool(klog.V(8)):
- rt = newDebuggingRoundTripper(rt, debugJustURL, debugRequestHeaders, debugResponseStatus, debugResponseHeaders)
- case bool(klog.V(7)):
- rt = newDebuggingRoundTripper(rt, debugJustURL, debugRequestHeaders, debugResponseStatus)
- case bool(klog.V(6)):
- rt = newDebuggingRoundTripper(rt, debugURLTiming)
- }
-
- return rt
-}
-
-type requestCanceler interface {
- CancelRequest(*http.Request)
-}
-
-type authProxyRoundTripper struct {
- username string
- groups []string
- extra map[string][]string
-
- rt http.RoundTripper
-}
-
-// NewAuthProxyRoundTripper provides a roundtripper which will add auth proxy fields to requests for
-// authentication terminating proxy cases
-// assuming you pull the user from the context:
-// username is the user.Info.GetName() of the user
-// groups is the user.Info.GetGroups() of the user
-// extra is the user.Info.GetExtra() of the user
-// extra can contain any additional information that the authenticator
-// thought was interesting, for example authorization scopes.
-// In order to faithfully round-trip through an impersonation flow, these keys
-// MUST be lowercase.
-func NewAuthProxyRoundTripper(username string, groups []string, extra map[string][]string, rt http.RoundTripper) http.RoundTripper {
- return &authProxyRoundTripper{
- username: username,
- groups: groups,
- extra: extra,
- rt: rt,
- }
-}
-
-func (rt *authProxyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
- req = utilnet.CloneRequest(req)
- SetAuthProxyHeaders(req, rt.username, rt.groups, rt.extra)
-
- return rt.rt.RoundTrip(req)
-}
-
-// SetAuthProxyHeaders stomps the auth proxy header fields. It mutates its argument.
-func SetAuthProxyHeaders(req *http.Request, username string, groups []string, extra map[string][]string) {
- req.Header.Del("X-Remote-User")
- req.Header.Del("X-Remote-Group")
- for key := range req.Header {
- if strings.HasPrefix(strings.ToLower(key), strings.ToLower("X-Remote-Extra-")) {
- req.Header.Del(key)
- }
- }
-
- req.Header.Set("X-Remote-User", username)
- for _, group := range groups {
- req.Header.Add("X-Remote-Group", group)
- }
- for key, values := range extra {
- for _, value := range values {
- req.Header.Add("X-Remote-Extra-"+headerKeyEscape(key), value)
- }
- }
-}
-
-func (rt *authProxyRoundTripper) CancelRequest(req *http.Request) {
- if canceler, ok := rt.rt.(requestCanceler); ok {
- canceler.CancelRequest(req)
- } else {
- klog.Errorf("CancelRequest not implemented by %T", rt.rt)
- }
-}
-
-func (rt *authProxyRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }
-
-type userAgentRoundTripper struct {
- agent string
- rt http.RoundTripper
-}
-
-func NewUserAgentRoundTripper(agent string, rt http.RoundTripper) http.RoundTripper {
- return &userAgentRoundTripper{agent, rt}
-}
-
-func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
- if len(req.Header.Get("User-Agent")) != 0 {
- return rt.rt.RoundTrip(req)
- }
- req = utilnet.CloneRequest(req)
- req.Header.Set("User-Agent", rt.agent)
- return rt.rt.RoundTrip(req)
-}
-
-func (rt *userAgentRoundTripper) CancelRequest(req *http.Request) {
- if canceler, ok := rt.rt.(requestCanceler); ok {
- canceler.CancelRequest(req)
- } else {
- klog.Errorf("CancelRequest not implemented by %T", rt.rt)
- }
-}
-
-func (rt *userAgentRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }
-
-type basicAuthRoundTripper struct {
- username string
- password string
- rt http.RoundTripper
-}
-
-// NewBasicAuthRoundTripper will apply a BASIC auth authorization header to a
-// request unless it has already been set.
-func NewBasicAuthRoundTripper(username, password string, rt http.RoundTripper) http.RoundTripper {
- return &basicAuthRoundTripper{username, password, rt}
-}
-
-func (rt *basicAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
- if len(req.Header.Get("Authorization")) != 0 {
- return rt.rt.RoundTrip(req)
- }
- req = utilnet.CloneRequest(req)
- req.SetBasicAuth(rt.username, rt.password)
- return rt.rt.RoundTrip(req)
-}
-
-func (rt *basicAuthRoundTripper) CancelRequest(req *http.Request) {
- if canceler, ok := rt.rt.(requestCanceler); ok {
- canceler.CancelRequest(req)
- } else {
- klog.Errorf("CancelRequest not implemented by %T", rt.rt)
- }
-}
-
-func (rt *basicAuthRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }
-
-// These correspond to the headers used in pkg/apis/authentication. We don't want the package dependency,
-// but you must not change the values.
-const (
- // ImpersonateUserHeader is used to impersonate a particular user during an API server request
- ImpersonateUserHeader = "Impersonate-User"
-
- // ImpersonateGroupHeader is used to impersonate a particular group during an API server request.
- // It can be repeated multiplied times for multiple groups.
- ImpersonateGroupHeader = "Impersonate-Group"
-
- // ImpersonateUserExtraHeaderPrefix is a prefix for a header used to impersonate an entry in the
- // extra map[string][]string for user.Info. The key for the `extra` map is suffix.
- // The same key can be repeated multiple times to have multiple elements in the slice under a single key.
- // For instance:
- // Impersonate-Extra-Foo: one
- // Impersonate-Extra-Foo: two
- // results in extra["Foo"] = []string{"one", "two"}
- ImpersonateUserExtraHeaderPrefix = "Impersonate-Extra-"
-)
-
-type impersonatingRoundTripper struct {
- impersonate ImpersonationConfig
- delegate http.RoundTripper
-}
-
-// NewImpersonatingRoundTripper will add an Act-As header to a request unless it has already been set.
-func NewImpersonatingRoundTripper(impersonate ImpersonationConfig, delegate http.RoundTripper) http.RoundTripper {
- return &impersonatingRoundTripper{impersonate, delegate}
-}
-
-func (rt *impersonatingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
- // use the user header as marker for the rest.
- if len(req.Header.Get(ImpersonateUserHeader)) != 0 {
- return rt.delegate.RoundTrip(req)
- }
- req = utilnet.CloneRequest(req)
- req.Header.Set(ImpersonateUserHeader, rt.impersonate.UserName)
-
- for _, group := range rt.impersonate.Groups {
- req.Header.Add(ImpersonateGroupHeader, group)
- }
- for k, vv := range rt.impersonate.Extra {
- for _, v := range vv {
- req.Header.Add(ImpersonateUserExtraHeaderPrefix+headerKeyEscape(k), v)
- }
- }
-
- return rt.delegate.RoundTrip(req)
-}
-
-func (rt *impersonatingRoundTripper) CancelRequest(req *http.Request) {
- if canceler, ok := rt.delegate.(requestCanceler); ok {
- canceler.CancelRequest(req)
- } else {
- klog.Errorf("CancelRequest not implemented by %T", rt.delegate)
- }
-}
-
-func (rt *impersonatingRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.delegate }
-
-type bearerAuthRoundTripper struct {
- bearer string
- source oauth2.TokenSource
- rt http.RoundTripper
-}
-
-// NewBearerAuthRoundTripper adds the provided bearer token to a request
-// unless the authorization header has already been set.
-func NewBearerAuthRoundTripper(bearer string, rt http.RoundTripper) http.RoundTripper {
- return &bearerAuthRoundTripper{bearer, nil, rt}
-}
-
-// NewBearerAuthRoundTripper adds the provided bearer token to a request
-// unless the authorization header has already been set.
-// If tokenFile is non-empty, it is periodically read,
-// and the last successfully read content is used as the bearer token.
-// If tokenFile is non-empty and bearer is empty, the tokenFile is read
-// immediately to populate the initial bearer token.
-func NewBearerAuthWithRefreshRoundTripper(bearer string, tokenFile string, rt http.RoundTripper) (http.RoundTripper, error) {
- if len(tokenFile) == 0 {
- return &bearerAuthRoundTripper{bearer, nil, rt}, nil
- }
- source := NewCachedFileTokenSource(tokenFile)
- if len(bearer) == 0 {
- token, err := source.Token()
- if err != nil {
- return nil, err
- }
- bearer = token.AccessToken
- }
- return &bearerAuthRoundTripper{bearer, source, rt}, nil
-}
-
-func (rt *bearerAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
- if len(req.Header.Get("Authorization")) != 0 {
- return rt.rt.RoundTrip(req)
- }
-
- req = utilnet.CloneRequest(req)
- token := rt.bearer
- if rt.source != nil {
- if refreshedToken, err := rt.source.Token(); err == nil {
- token = refreshedToken.AccessToken
- }
- }
- req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
- return rt.rt.RoundTrip(req)
-}
-
-func (rt *bearerAuthRoundTripper) CancelRequest(req *http.Request) {
- if canceler, ok := rt.rt.(requestCanceler); ok {
- canceler.CancelRequest(req)
- } else {
- klog.Errorf("CancelRequest not implemented by %T", rt.rt)
- }
-}
-
-func (rt *bearerAuthRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }
-
-// requestInfo keeps track of information about a request/response combination
-type requestInfo struct {
- RequestHeaders http.Header
- RequestVerb string
- RequestURL string
-
- ResponseStatus string
- ResponseHeaders http.Header
- ResponseErr error
-
- Duration time.Duration
-}
-
-// newRequestInfo creates a new RequestInfo based on an http request
-func newRequestInfo(req *http.Request) *requestInfo {
- return &requestInfo{
- RequestURL: req.URL.String(),
- RequestVerb: req.Method,
- RequestHeaders: req.Header,
- }
-}
-
-// complete adds information about the response to the requestInfo
-func (r *requestInfo) complete(response *http.Response, err error) {
- if err != nil {
- r.ResponseErr = err
- return
- }
- r.ResponseStatus = response.Status
- r.ResponseHeaders = response.Header
-}
-
-// toCurl returns a string that can be run as a command in a terminal (minus the body)
-func (r *requestInfo) toCurl() string {
- headers := ""
- for key, values := range r.RequestHeaders {
- for _, value := range values {
- headers += fmt.Sprintf(` -H %q`, fmt.Sprintf("%s: %s", key, value))
- }
- }
-
- return fmt.Sprintf("curl -k -v -X%s %s '%s'", r.RequestVerb, headers, r.RequestURL)
-}
-
-// debuggingRoundTripper will display information about the requests passing
-// through it based on what is configured
-type debuggingRoundTripper struct {
- delegatedRoundTripper http.RoundTripper
-
- levels map[debugLevel]bool
-}
-
-type debugLevel int
-
-const (
- debugJustURL debugLevel = iota
- debugURLTiming
- debugCurlCommand
- debugRequestHeaders
- debugResponseStatus
- debugResponseHeaders
-)
-
-func newDebuggingRoundTripper(rt http.RoundTripper, levels ...debugLevel) *debuggingRoundTripper {
- drt := &debuggingRoundTripper{
- delegatedRoundTripper: rt,
- levels: make(map[debugLevel]bool, len(levels)),
- }
- for _, v := range levels {
- drt.levels[v] = true
- }
- return drt
-}
-
-func (rt *debuggingRoundTripper) CancelRequest(req *http.Request) {
- if canceler, ok := rt.delegatedRoundTripper.(requestCanceler); ok {
- canceler.CancelRequest(req)
- } else {
- klog.Errorf("CancelRequest not implemented by %T", rt.delegatedRoundTripper)
- }
-}
-
-func (rt *debuggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
- reqInfo := newRequestInfo(req)
-
- if rt.levels[debugJustURL] {
- klog.Infof("%s %s", reqInfo.RequestVerb, reqInfo.RequestURL)
- }
- if rt.levels[debugCurlCommand] {
- klog.Infof("%s", reqInfo.toCurl())
-
- }
- if rt.levels[debugRequestHeaders] {
- klog.Infof("Request Headers:")
- for key, values := range reqInfo.RequestHeaders {
- for _, value := range values {
- klog.Infof(" %s: %s", key, value)
- }
- }
- }
-
- startTime := time.Now()
- response, err := rt.delegatedRoundTripper.RoundTrip(req)
- reqInfo.Duration = time.Since(startTime)
-
- reqInfo.complete(response, err)
-
- if rt.levels[debugURLTiming] {
- klog.Infof("%s %s %s in %d milliseconds", reqInfo.RequestVerb, reqInfo.RequestURL, reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond))
- }
- if rt.levels[debugResponseStatus] {
- klog.Infof("Response Status: %s in %d milliseconds", reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond))
- }
- if rt.levels[debugResponseHeaders] {
- klog.Infof("Response Headers:")
- for key, values := range reqInfo.ResponseHeaders {
- for _, value := range values {
- klog.Infof(" %s: %s", key, value)
- }
- }
- }
-
- return response, err
-}
-
-func (rt *debuggingRoundTripper) WrappedRoundTripper() http.RoundTripper {
- return rt.delegatedRoundTripper
-}
-
-func legalHeaderByte(b byte) bool {
- return int(b) < len(legalHeaderKeyBytes) && legalHeaderKeyBytes[b]
-}
-
-func shouldEscape(b byte) bool {
- // url.PathUnescape() returns an error if any '%' is not followed by two
- // hexadecimal digits, so we'll intentionally encode it.
- return !legalHeaderByte(b) || b == '%'
-}
-
-func headerKeyEscape(key string) string {
- buf := strings.Builder{}
- for i := 0; i < len(key); i++ {
- b := key[i]
- if shouldEscape(b) {
- // %-encode bytes that should be escaped:
- // https://tools.ietf.org/html/rfc3986#section-2.1
- fmt.Fprintf(&buf, "%%%02X", b)
- continue
- }
- buf.WriteByte(b)
- }
- return buf.String()
-}
-
-// legalHeaderKeyBytes was copied from net/http/lex.go's isTokenTable.
-// See https://httpwg.github.io/specs/rfc7230.html#rule.token.separators
-var legalHeaderKeyBytes = [127]bool{
- '%': true,
- '!': true,
- '#': true,
- '$': true,
- '&': true,
- '\'': true,
- '*': true,
- '+': true,
- '-': true,
- '.': true,
- '0': true,
- '1': true,
- '2': true,
- '3': true,
- '4': true,
- '5': true,
- '6': true,
- '7': true,
- '8': true,
- '9': true,
- 'A': true,
- 'B': true,
- 'C': true,
- 'D': true,
- 'E': true,
- 'F': true,
- 'G': true,
- 'H': true,
- 'I': true,
- 'J': true,
- 'K': true,
- 'L': true,
- 'M': true,
- 'N': true,
- 'O': true,
- 'P': true,
- 'Q': true,
- 'R': true,
- 'S': true,
- 'T': true,
- 'U': true,
- 'W': true,
- 'V': true,
- 'X': true,
- 'Y': true,
- 'Z': true,
- '^': true,
- '_': true,
- '`': true,
- 'a': true,
- 'b': true,
- 'c': true,
- 'd': true,
- 'e': true,
- 'f': true,
- 'g': true,
- 'h': true,
- 'i': true,
- 'j': true,
- 'k': true,
- 'l': true,
- 'm': true,
- 'n': true,
- 'o': true,
- 'p': true,
- 'q': true,
- 'r': true,
- 's': true,
- 't': true,
- 'u': true,
- 'v': true,
- 'w': true,
- 'x': true,
- 'y': true,
- 'z': true,
- '|': true,
- '~': true,
-}
diff --git a/vendor/k8s.io/client-go/transport/spdy/spdy.go b/vendor/k8s.io/client-go/transport/spdy/spdy.go
deleted file mode 100644
index 53cc7ee18..000000000
--- a/vendor/k8s.io/client-go/transport/spdy/spdy.go
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
-Copyright 2017 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package spdy
-
-import (
- "fmt"
- "net/http"
- "net/url"
-
- "k8s.io/apimachinery/pkg/util/httpstream"
- "k8s.io/apimachinery/pkg/util/httpstream/spdy"
- restclient "k8s.io/client-go/rest"
-)
-
-// Upgrader validates a response from the server after a SPDY upgrade.
-type Upgrader interface {
- // NewConnection validates the response and creates a new Connection.
- NewConnection(resp *http.Response) (httpstream.Connection, error)
-}
-
-// RoundTripperFor returns a round tripper and upgrader to use with SPDY.
-func RoundTripperFor(config *restclient.Config) (http.RoundTripper, Upgrader, error) {
- tlsConfig, err := restclient.TLSConfigFor(config)
- if err != nil {
- return nil, nil, err
- }
- upgradeRoundTripper := spdy.NewRoundTripper(tlsConfig, true, false)
- wrapper, err := restclient.HTTPWrappersForConfig(config, upgradeRoundTripper)
- if err != nil {
- return nil, nil, err
- }
- return wrapper, upgradeRoundTripper, nil
-}
-
-// dialer implements the httpstream.Dialer interface.
-type dialer struct {
- client *http.Client
- upgrader Upgrader
- method string
- url *url.URL
-}
-
-var _ httpstream.Dialer = &dialer{}
-
-// NewDialer will create a dialer that connects to the provided URL and upgrades the connection to SPDY.
-func NewDialer(upgrader Upgrader, client *http.Client, method string, url *url.URL) httpstream.Dialer {
- return &dialer{
- client: client,
- upgrader: upgrader,
- method: method,
- url: url,
- }
-}
-
-func (d *dialer) Dial(protocols ...string) (httpstream.Connection, string, error) {
- req, err := http.NewRequest(d.method, d.url.String(), nil)
- if err != nil {
- return nil, "", fmt.Errorf("error creating request: %v", err)
- }
- return Negotiate(d.upgrader, d.client, req, protocols...)
-}
-
-// Negotiate opens a connection to a remote server and attempts to negotiate
-// a SPDY connection. Upon success, it returns the connection and the protocol selected by
-// the server. The client transport must use the upgradeRoundTripper - see RoundTripperFor.
-func Negotiate(upgrader Upgrader, client *http.Client, req *http.Request, protocols ...string) (httpstream.Connection, string, error) {
- for i := range protocols {
- req.Header.Add(httpstream.HeaderProtocolVersion, protocols[i])
- }
- resp, err := client.Do(req)
- if err != nil {
- return nil, "", fmt.Errorf("error sending request: %v", err)
- }
- defer resp.Body.Close()
- conn, err := upgrader.NewConnection(resp)
- if err != nil {
- return nil, "", err
- }
- return conn, resp.Header.Get(httpstream.HeaderProtocolVersion), nil
-}
diff --git a/vendor/k8s.io/client-go/transport/token_source.go b/vendor/k8s.io/client-go/transport/token_source.go
deleted file mode 100644
index b8cadd382..000000000
--- a/vendor/k8s.io/client-go/transport/token_source.go
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package transport
-
-import (
- "fmt"
- "io/ioutil"
- "net/http"
- "strings"
- "sync"
- "time"
-
- "golang.org/x/oauth2"
- "k8s.io/klog"
-)
-
-// TokenSourceWrapTransport returns a WrapTransport that injects bearer tokens
-// authentication from an oauth2.TokenSource.
-func TokenSourceWrapTransport(ts oauth2.TokenSource) func(http.RoundTripper) http.RoundTripper {
- return func(rt http.RoundTripper) http.RoundTripper {
- return &tokenSourceTransport{
- base: rt,
- ort: &oauth2.Transport{
- Source: ts,
- Base: rt,
- },
- }
- }
-}
-
-// NewCachedFileTokenSource returns a oauth2.TokenSource reads a token from a
-// file at a specified path and periodically reloads it.
-func NewCachedFileTokenSource(path string) oauth2.TokenSource {
- return &cachingTokenSource{
- now: time.Now,
- leeway: 10 * time.Second,
- base: &fileTokenSource{
- path: path,
- // This period was picked because it is half of the duration between when the kubelet
- // refreshes a projected service account token and when the original token expires.
- // Default token lifetime is 10 minutes, and the kubelet starts refreshing at 80% of lifetime.
- // This should induce re-reading at a frequency that works with the token volume source.
- period: time.Minute,
- },
- }
-}
-
-// NewCachedTokenSource returns a oauth2.TokenSource reads a token from a
-// designed TokenSource. The ts would provide the source of token.
-func NewCachedTokenSource(ts oauth2.TokenSource) oauth2.TokenSource {
- return &cachingTokenSource{
- now: time.Now,
- base: ts,
- }
-}
-
-type tokenSourceTransport struct {
- base http.RoundTripper
- ort http.RoundTripper
-}
-
-func (tst *tokenSourceTransport) RoundTrip(req *http.Request) (*http.Response, error) {
- // This is to allow --token to override other bearer token providers.
- if req.Header.Get("Authorization") != "" {
- return tst.base.RoundTrip(req)
- }
- return tst.ort.RoundTrip(req)
-}
-
-type fileTokenSource struct {
- path string
- period time.Duration
-}
-
-var _ = oauth2.TokenSource(&fileTokenSource{})
-
-func (ts *fileTokenSource) Token() (*oauth2.Token, error) {
- tokb, err := ioutil.ReadFile(ts.path)
- if err != nil {
- return nil, fmt.Errorf("failed to read token file %q: %v", ts.path, err)
- }
- tok := strings.TrimSpace(string(tokb))
- if len(tok) == 0 {
- return nil, fmt.Errorf("read empty token from file %q", ts.path)
- }
-
- return &oauth2.Token{
- AccessToken: tok,
- Expiry: time.Now().Add(ts.period),
- }, nil
-}
-
-type cachingTokenSource struct {
- base oauth2.TokenSource
- leeway time.Duration
-
- sync.RWMutex
- tok *oauth2.Token
-
- // for testing
- now func() time.Time
-}
-
-var _ = oauth2.TokenSource(&cachingTokenSource{})
-
-func (ts *cachingTokenSource) Token() (*oauth2.Token, error) {
- now := ts.now()
- // fast path
- ts.RLock()
- tok := ts.tok
- ts.RUnlock()
-
- if tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {
- return tok, nil
- }
-
- // slow path
- ts.Lock()
- defer ts.Unlock()
- if tok := ts.tok; tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {
- return tok, nil
- }
-
- tok, err := ts.base.Token()
- if err != nil {
- if ts.tok == nil {
- return nil, err
- }
- klog.Errorf("Unable to rotate token: %v", err)
- return ts.tok, nil
- }
-
- ts.tok = tok
- return tok, nil
-}
diff --git a/vendor/k8s.io/client-go/transport/transport.go b/vendor/k8s.io/client-go/transport/transport.go
deleted file mode 100644
index 2a145c971..000000000
--- a/vendor/k8s.io/client-go/transport/transport.go
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package transport
-
-import (
- "context"
- "crypto/tls"
- "crypto/x509"
- "fmt"
- "io/ioutil"
- "net/http"
-)
-
-// New returns an http.RoundTripper that will provide the authentication
-// or transport level security defined by the provided Config.
-func New(config *Config) (http.RoundTripper, error) {
- // Set transport level security
- if config.Transport != nil && (config.HasCA() || config.HasCertAuth() || config.HasCertCallback() || config.TLS.Insecure) {
- return nil, fmt.Errorf("using a custom transport with TLS certificate options or the insecure flag is not allowed")
- }
-
- var (
- rt http.RoundTripper
- err error
- )
-
- if config.Transport != nil {
- rt = config.Transport
- } else {
- rt, err = tlsCache.get(config)
- if err != nil {
- return nil, err
- }
- }
-
- return HTTPWrappersForConfig(config, rt)
-}
-
-// TLSConfigFor returns a tls.Config that will provide the transport level security defined
-// by the provided Config. Will return nil if no transport level security is requested.
-func TLSConfigFor(c *Config) (*tls.Config, error) {
- if !(c.HasCA() || c.HasCertAuth() || c.HasCertCallback() || c.TLS.Insecure || len(c.TLS.ServerName) > 0) {
- return nil, nil
- }
- if c.HasCA() && c.TLS.Insecure {
- return nil, fmt.Errorf("specifying a root certificates file with the insecure flag is not allowed")
- }
- if err := loadTLSFiles(c); err != nil {
- return nil, err
- }
-
- tlsConfig := &tls.Config{
- // Can't use SSLv3 because of POODLE and BEAST
- // Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher
- // Can't use TLSv1.1 because of RC4 cipher usage
- MinVersion: tls.VersionTLS12,
- InsecureSkipVerify: c.TLS.Insecure,
- ServerName: c.TLS.ServerName,
- }
-
- if c.HasCA() {
- tlsConfig.RootCAs = rootCertPool(c.TLS.CAData)
- }
-
- var staticCert *tls.Certificate
- if c.HasCertAuth() {
- // If key/cert were provided, verify them before setting up
- // tlsConfig.GetClientCertificate.
- cert, err := tls.X509KeyPair(c.TLS.CertData, c.TLS.KeyData)
- if err != nil {
- return nil, err
- }
- staticCert = &cert
- }
-
- if c.HasCertAuth() || c.HasCertCallback() {
- tlsConfig.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
- // Note: static key/cert data always take precedence over cert
- // callback.
- if staticCert != nil {
- return staticCert, nil
- }
- if c.HasCertCallback() {
- cert, err := c.TLS.GetCert()
- if err != nil {
- return nil, err
- }
- // GetCert may return empty value, meaning no cert.
- if cert != nil {
- return cert, nil
- }
- }
-
- // Both c.TLS.CertData/KeyData were unset and GetCert didn't return
- // anything. Return an empty tls.Certificate, no client cert will
- // be sent to the server.
- return &tls.Certificate{}, nil
- }
- }
-
- return tlsConfig, nil
-}
-
-// loadTLSFiles copies the data from the CertFile, KeyFile, and CAFile fields into the CertData,
-// KeyData, and CAFile fields, or returns an error. If no error is returned, all three fields are
-// either populated or were empty to start.
-func loadTLSFiles(c *Config) error {
- var err error
- c.TLS.CAData, err = dataFromSliceOrFile(c.TLS.CAData, c.TLS.CAFile)
- if err != nil {
- return err
- }
-
- c.TLS.CertData, err = dataFromSliceOrFile(c.TLS.CertData, c.TLS.CertFile)
- if err != nil {
- return err
- }
-
- c.TLS.KeyData, err = dataFromSliceOrFile(c.TLS.KeyData, c.TLS.KeyFile)
- if err != nil {
- return err
- }
- return nil
-}
-
-// dataFromSliceOrFile returns data from the slice (if non-empty), or from the file,
-// or an error if an error occurred reading the file
-func dataFromSliceOrFile(data []byte, file string) ([]byte, error) {
- if len(data) > 0 {
- return data, nil
- }
- if len(file) > 0 {
- fileData, err := ioutil.ReadFile(file)
- if err != nil {
- return []byte{}, err
- }
- return fileData, nil
- }
- return nil, nil
-}
-
-// rootCertPool returns nil if caData is empty. When passed along, this will mean "use system CAs".
-// When caData is not empty, it will be the ONLY information used in the CertPool.
-func rootCertPool(caData []byte) *x509.CertPool {
- // What we really want is a copy of x509.systemRootsPool, but that isn't exposed. It's difficult to build (see the go
- // code for a look at the platform specific insanity), so we'll use the fact that RootCAs == nil gives us the system values
- // It doesn't allow trusting either/or, but hopefully that won't be an issue
- if len(caData) == 0 {
- return nil
- }
-
- // if we have caData, use it
- certPool := x509.NewCertPool()
- certPool.AppendCertsFromPEM(caData)
- return certPool
-}
-
-// WrapperFunc wraps an http.RoundTripper when a new transport
-// is created for a client, allowing per connection behavior
-// to be injected.
-type WrapperFunc func(rt http.RoundTripper) http.RoundTripper
-
-// Wrappers accepts any number of wrappers and returns a wrapper
-// function that is the equivalent of calling each of them in order. Nil
-// values are ignored, which makes this function convenient for incrementally
-// wrapping a function.
-func Wrappers(fns ...WrapperFunc) WrapperFunc {
- if len(fns) == 0 {
- return nil
- }
- // optimize the common case of wrapping a possibly nil transport wrapper
- // with an additional wrapper
- if len(fns) == 2 && fns[0] == nil {
- return fns[1]
- }
- return func(rt http.RoundTripper) http.RoundTripper {
- base := rt
- for _, fn := range fns {
- if fn != nil {
- base = fn(base)
- }
- }
- return base
- }
-}
-
-// ContextCanceller prevents new requests after the provided context is finished.
-// err is returned when the context is closed, allowing the caller to provide a context
-// appropriate error.
-func ContextCanceller(ctx context.Context, err error) WrapperFunc {
- return func(rt http.RoundTripper) http.RoundTripper {
- return &contextCanceller{
- ctx: ctx,
- rt: rt,
- err: err,
- }
- }
-}
-
-type contextCanceller struct {
- ctx context.Context
- rt http.RoundTripper
- err error
-}
-
-func (b *contextCanceller) RoundTrip(req *http.Request) (*http.Response, error) {
- select {
- case <-b.ctx.Done():
- return nil, b.err
- default:
- return b.rt.RoundTrip(req)
- }
-}
diff --git a/vendor/k8s.io/client-go/util/cert/OWNERS b/vendor/k8s.io/client-go/util/cert/OWNERS
deleted file mode 100644
index 3cf036438..000000000
--- a/vendor/k8s.io/client-go/util/cert/OWNERS
+++ /dev/null
@@ -1,9 +0,0 @@
-# See the OWNERS docs at https://go.k8s.io/owners
-
-approvers:
-- sig-auth-certificates-approvers
-reviewers:
-- sig-auth-certificates-reviewers
-labels:
-- sig/auth
-
diff --git a/vendor/k8s.io/client-go/util/cert/cert.go b/vendor/k8s.io/client-go/util/cert/cert.go
deleted file mode 100644
index 9fd097af5..000000000
--- a/vendor/k8s.io/client-go/util/cert/cert.go
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package cert
-
-import (
- "bytes"
- "crypto"
- cryptorand "crypto/rand"
- "crypto/rsa"
- "crypto/x509"
- "crypto/x509/pkix"
- "encoding/pem"
- "fmt"
- "io/ioutil"
- "math/big"
- "net"
- "path"
- "strings"
- "time"
-
- "k8s.io/client-go/util/keyutil"
-)
-
-const duration365d = time.Hour * 24 * 365
-
-// Config contains the basic fields required for creating a certificate
-type Config struct {
- CommonName string
- Organization []string
- AltNames AltNames
- Usages []x509.ExtKeyUsage
-}
-
-// AltNames contains the domain names and IP addresses that will be added
-// to the API Server's x509 certificate SubAltNames field. The values will
-// be passed directly to the x509.Certificate object.
-type AltNames struct {
- DNSNames []string
- IPs []net.IP
-}
-
-// NewSelfSignedCACert creates a CA certificate
-func NewSelfSignedCACert(cfg Config, key crypto.Signer) (*x509.Certificate, error) {
- now := time.Now()
- tmpl := x509.Certificate{
- SerialNumber: new(big.Int).SetInt64(0),
- Subject: pkix.Name{
- CommonName: cfg.CommonName,
- Organization: cfg.Organization,
- },
- NotBefore: now.UTC(),
- NotAfter: now.Add(duration365d * 10).UTC(),
- KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
- BasicConstraintsValid: true,
- IsCA: true,
- }
-
- certDERBytes, err := x509.CreateCertificate(cryptorand.Reader, &tmpl, &tmpl, key.Public(), key)
- if err != nil {
- return nil, err
- }
- return x509.ParseCertificate(certDERBytes)
-}
-
-// GenerateSelfSignedCertKey creates a self-signed certificate and key for the given host.
-// Host may be an IP or a DNS name
-// You may also specify additional subject alt names (either ip or dns names) for the certificate.
-func GenerateSelfSignedCertKey(host string, alternateIPs []net.IP, alternateDNS []string) ([]byte, []byte, error) {
- return GenerateSelfSignedCertKeyWithFixtures(host, alternateIPs, alternateDNS, "")
-}
-
-// GenerateSelfSignedCertKeyWithFixtures creates a self-signed certificate and key for the given host.
-// Host may be an IP or a DNS name. You may also specify additional subject alt names (either ip or dns names)
-// for the certificate.
-//
-// If fixtureDirectory is non-empty, it is a directory path which can contain pre-generated certs. The format is:
-// <host>_<ip>-<ip>_<alternateDNS>-<alternateDNS>.crt
-// <host>_<ip>-<ip>_<alternateDNS>-<alternateDNS>.key
-// Certs/keys not existing in that directory are created.
-func GenerateSelfSignedCertKeyWithFixtures(host string, alternateIPs []net.IP, alternateDNS []string, fixtureDirectory string) ([]byte, []byte, error) {
- validFrom := time.Now().Add(-time.Hour) // valid an hour earlier to avoid flakes due to clock skew
- maxAge := time.Hour * 24 * 365 // one year self-signed certs
-
- baseName := fmt.Sprintf("%s_%s_%s", host, strings.Join(ipsToStrings(alternateIPs), "-"), strings.Join(alternateDNS, "-"))
- certFixturePath := path.Join(fixtureDirectory, baseName+".crt")
- keyFixturePath := path.Join(fixtureDirectory, baseName+".key")
- if len(fixtureDirectory) > 0 {
- cert, err := ioutil.ReadFile(certFixturePath)
- if err == nil {
- key, err := ioutil.ReadFile(keyFixturePath)
- if err == nil {
- return cert, key, nil
- }
- return nil, nil, fmt.Errorf("cert %s can be read, but key %s cannot: %v", certFixturePath, keyFixturePath, err)
- }
- maxAge = 100 * time.Hour * 24 * 365 // 100 years fixtures
- }
-
- caKey, err := rsa.GenerateKey(cryptorand.Reader, 2048)
- if err != nil {
- return nil, nil, err
- }
-
- caTemplate := x509.Certificate{
- SerialNumber: big.NewInt(1),
- Subject: pkix.Name{
- CommonName: fmt.Sprintf("%s-ca@%d", host, time.Now().Unix()),
- },
- NotBefore: validFrom,
- NotAfter: validFrom.Add(maxAge),
-
- KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
- BasicConstraintsValid: true,
- IsCA: true,
- }
-
- caDERBytes, err := x509.CreateCertificate(cryptorand.Reader, &caTemplate, &caTemplate, &caKey.PublicKey, caKey)
- if err != nil {
- return nil, nil, err
- }
-
- caCertificate, err := x509.ParseCertificate(caDERBytes)
- if err != nil {
- return nil, nil, err
- }
-
- priv, err := rsa.GenerateKey(cryptorand.Reader, 2048)
- if err != nil {
- return nil, nil, err
- }
-
- template := x509.Certificate{
- SerialNumber: big.NewInt(2),
- Subject: pkix.Name{
- CommonName: fmt.Sprintf("%s@%d", host, time.Now().Unix()),
- },
- NotBefore: validFrom,
- NotAfter: validFrom.Add(maxAge),
-
- KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
- ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
- BasicConstraintsValid: true,
- }
-
- if ip := net.ParseIP(host); ip != nil {
- template.IPAddresses = append(template.IPAddresses, ip)
- } else {
- template.DNSNames = append(template.DNSNames, host)
- }
-
- template.IPAddresses = append(template.IPAddresses, alternateIPs...)
- template.DNSNames = append(template.DNSNames, alternateDNS...)
-
- derBytes, err := x509.CreateCertificate(cryptorand.Reader, &template, caCertificate, &priv.PublicKey, caKey)
- if err != nil {
- return nil, nil, err
- }
-
- // Generate cert, followed by ca
- certBuffer := bytes.Buffer{}
- if err := pem.Encode(&certBuffer, &pem.Block{Type: CertificateBlockType, Bytes: derBytes}); err != nil {
- return nil, nil, err
- }
- if err := pem.Encode(&certBuffer, &pem.Block{Type: CertificateBlockType, Bytes: caDERBytes}); err != nil {
- return nil, nil, err
- }
-
- // Generate key
- keyBuffer := bytes.Buffer{}
- if err := pem.Encode(&keyBuffer, &pem.Block{Type: keyutil.RSAPrivateKeyBlockType, Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
- return nil, nil, err
- }
-
- if len(fixtureDirectory) > 0 {
- if err := ioutil.WriteFile(certFixturePath, certBuffer.Bytes(), 0644); err != nil {
- return nil, nil, fmt.Errorf("failed to write cert fixture to %s: %v", certFixturePath, err)
- }
- if err := ioutil.WriteFile(keyFixturePath, keyBuffer.Bytes(), 0644); err != nil {
- return nil, nil, fmt.Errorf("failed to write key fixture to %s: %v", certFixturePath, err)
- }
- }
-
- return certBuffer.Bytes(), keyBuffer.Bytes(), nil
-}
-
-func ipsToStrings(ips []net.IP) []string {
- ss := make([]string, 0, len(ips))
- for _, ip := range ips {
- ss = append(ss, ip.String())
- }
- return ss
-}
diff --git a/vendor/k8s.io/client-go/util/cert/csr.go b/vendor/k8s.io/client-go/util/cert/csr.go
deleted file mode 100644
index 39a6751f7..000000000
--- a/vendor/k8s.io/client-go/util/cert/csr.go
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
-Copyright 2016 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package cert
-
-import (
- cryptorand "crypto/rand"
- "crypto/rsa"
- "crypto/x509"
- "crypto/x509/pkix"
- "encoding/pem"
- "net"
-)
-
-// MakeCSR generates a PEM-encoded CSR using the supplied private key, subject, and SANs.
-// All key types that are implemented via crypto.Signer are supported (This includes *rsa.PrivateKey and *ecdsa.PrivateKey.)
-func MakeCSR(privateKey interface{}, subject *pkix.Name, dnsSANs []string, ipSANs []net.IP) (csr []byte, err error) {
- template := &x509.CertificateRequest{
- Subject: *subject,
- DNSNames: dnsSANs,
- IPAddresses: ipSANs,
- }
-
- return MakeCSRFromTemplate(privateKey, template)
-}
-
-// MakeCSRFromTemplate generates a PEM-encoded CSR using the supplied private
-// key and certificate request as a template. All key types that are
-// implemented via crypto.Signer are supported (This includes *rsa.PrivateKey
-// and *ecdsa.PrivateKey.)
-func MakeCSRFromTemplate(privateKey interface{}, template *x509.CertificateRequest) ([]byte, error) {
- t := *template
- t.SignatureAlgorithm = sigType(privateKey)
-
- csrDER, err := x509.CreateCertificateRequest(cryptorand.Reader, &t, privateKey)
- if err != nil {
- return nil, err
- }
-
- csrPemBlock := &pem.Block{
- Type: CertificateRequestBlockType,
- Bytes: csrDER,
- }
-
- return pem.EncodeToMemory(csrPemBlock), nil
-}
-
-func sigType(privateKey interface{}) x509.SignatureAlgorithm {
- // Customize the signature for RSA keys, depending on the key size
- if privateKey, ok := privateKey.(*rsa.PrivateKey); ok {
- keySize := privateKey.N.BitLen()
- switch {
- case keySize >= 4096:
- return x509.SHA512WithRSA
- case keySize >= 3072:
- return x509.SHA384WithRSA
- default:
- return x509.SHA256WithRSA
- }
- }
- return x509.UnknownSignatureAlgorithm
-}
diff --git a/vendor/k8s.io/client-go/util/cert/io.go b/vendor/k8s.io/client-go/util/cert/io.go
deleted file mode 100644
index 5efb24894..000000000
--- a/vendor/k8s.io/client-go/util/cert/io.go
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package cert
-
-import (
- "crypto/x509"
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
-)
-
-// CanReadCertAndKey returns true if the certificate and key files already exists,
-// otherwise returns false. If lost one of cert and key, returns error.
-func CanReadCertAndKey(certPath, keyPath string) (bool, error) {
- certReadable := canReadFile(certPath)
- keyReadable := canReadFile(keyPath)
-
- if certReadable == false && keyReadable == false {
- return false, nil
- }
-
- if certReadable == false {
- return false, fmt.Errorf("error reading %s, certificate and key must be supplied as a pair", certPath)
- }
-
- if keyReadable == false {
- return false, fmt.Errorf("error reading %s, certificate and key must be supplied as a pair", keyPath)
- }
-
- return true, nil
-}
-
-// If the file represented by path exists and
-// readable, returns true otherwise returns false.
-func canReadFile(path string) bool {
- f, err := os.Open(path)
- if err != nil {
- return false
- }
-
- defer f.Close()
-
- return true
-}
-
-// WriteCert writes the pem-encoded certificate data to certPath.
-// The certificate file will be created with file mode 0644.
-// If the certificate file already exists, it will be overwritten.
-// The parent directory of the certPath will be created as needed with file mode 0755.
-func WriteCert(certPath string, data []byte) error {
- if err := os.MkdirAll(filepath.Dir(certPath), os.FileMode(0755)); err != nil {
- return err
- }
- return ioutil.WriteFile(certPath, data, os.FileMode(0644))
-}
-
-// NewPool returns an x509.CertPool containing the certificates in the given PEM-encoded file.
-// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates
-func NewPool(filename string) (*x509.CertPool, error) {
- certs, err := CertsFromFile(filename)
- if err != nil {
- return nil, err
- }
- pool := x509.NewCertPool()
- for _, cert := range certs {
- pool.AddCert(cert)
- }
- return pool, nil
-}
-
-// CertsFromFile returns the x509.Certificates contained in the given PEM-encoded file.
-// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates
-func CertsFromFile(file string) ([]*x509.Certificate, error) {
- pemBlock, err := ioutil.ReadFile(file)
- if err != nil {
- return nil, err
- }
- certs, err := ParseCertsPEM(pemBlock)
- if err != nil {
- return nil, fmt.Errorf("error reading %s: %s", file, err)
- }
- return certs, nil
-}
diff --git a/vendor/k8s.io/client-go/util/cert/pem.go b/vendor/k8s.io/client-go/util/cert/pem.go
deleted file mode 100644
index 9185e2e22..000000000
--- a/vendor/k8s.io/client-go/util/cert/pem.go
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package cert
-
-import (
- "crypto/x509"
- "encoding/pem"
- "errors"
-)
-
-const (
- // CertificateBlockType is a possible value for pem.Block.Type.
- CertificateBlockType = "CERTIFICATE"
- // CertificateRequestBlockType is a possible value for pem.Block.Type.
- CertificateRequestBlockType = "CERTIFICATE REQUEST"
-)
-
-// ParseCertsPEM returns the x509.Certificates contained in the given PEM-encoded byte array
-// Returns an error if a certificate could not be parsed, or if the data does not contain any certificates
-func ParseCertsPEM(pemCerts []byte) ([]*x509.Certificate, error) {
- ok := false
- certs := []*x509.Certificate{}
- for len(pemCerts) > 0 {
- var block *pem.Block
- block, pemCerts = pem.Decode(pemCerts)
- if block == nil {
- break
- }
- // Only use PEM "CERTIFICATE" blocks without extra headers
- if block.Type != CertificateBlockType || len(block.Headers) != 0 {
- continue
- }
-
- cert, err := x509.ParseCertificate(block.Bytes)
- if err != nil {
- return certs, err
- }
-
- certs = append(certs, cert)
- ok = true
- }
-
- if !ok {
- return certs, errors.New("data does not contain any valid RSA or ECDSA certificates")
- }
- return certs, nil
-}
diff --git a/vendor/k8s.io/client-go/util/connrotation/connrotation.go b/vendor/k8s.io/client-go/util/connrotation/connrotation.go
deleted file mode 100644
index 235a9e019..000000000
--- a/vendor/k8s.io/client-go/util/connrotation/connrotation.go
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package connrotation implements a connection dialer that tracks and can close
-// all created connections.
-//
-// This is used for credential rotation of long-lived connections, when there's
-// no way to re-authenticate on a live connection.
-package connrotation
-
-import (
- "context"
- "net"
- "sync"
-)
-
-// DialFunc is a shorthand for signature of net.DialContext.
-type DialFunc func(ctx context.Context, network, address string) (net.Conn, error)
-
-// Dialer opens connections through Dial and tracks them.
-type Dialer struct {
- dial DialFunc
-
- mu sync.Mutex
- conns map[*closableConn]struct{}
-}
-
-// NewDialer creates a new Dialer instance.
-//
-// If dial is not nil, it will be used to create new underlying connections.
-// Otherwise net.DialContext is used.
-func NewDialer(dial DialFunc) *Dialer {
- return &Dialer{
- dial: dial,
- conns: make(map[*closableConn]struct{}),
- }
-}
-
-// CloseAll forcibly closes all tracked connections.
-//
-// Note: new connections may get created before CloseAll returns.
-func (d *Dialer) CloseAll() {
- d.mu.Lock()
- conns := d.conns
- d.conns = make(map[*closableConn]struct{})
- d.mu.Unlock()
-
- for conn := range conns {
- conn.Close()
- }
-}
-
-// Dial creates a new tracked connection.
-func (d *Dialer) Dial(network, address string) (net.Conn, error) {
- return d.DialContext(context.Background(), network, address)
-}
-
-// DialContext creates a new tracked connection.
-func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
- conn, err := d.dial(ctx, network, address)
- if err != nil {
- return nil, err
- }
-
- closable := &closableConn{Conn: conn}
-
- // Start tracking the connection
- d.mu.Lock()
- d.conns[closable] = struct{}{}
- d.mu.Unlock()
-
- // When the connection is closed, remove it from the map. This will
- // be no-op if the connection isn't in the map, e.g. if CloseAll()
- // is called.
- closable.onClose = func() {
- d.mu.Lock()
- delete(d.conns, closable)
- d.mu.Unlock()
- }
-
- return closable, nil
-}
-
-type closableConn struct {
- onClose func()
- net.Conn
-}
-
-func (c *closableConn) Close() error {
- go c.onClose()
- return c.Conn.Close()
-}
diff --git a/vendor/k8s.io/client-go/util/exec/exec.go b/vendor/k8s.io/client-go/util/exec/exec.go
deleted file mode 100644
index d170badb6..000000000
--- a/vendor/k8s.io/client-go/util/exec/exec.go
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package exec
-
-// ExitError is an interface that presents an API similar to os.ProcessState, which is
-// what ExitError from os/exec is. This is designed to make testing a bit easier and
-// probably loses some of the cross-platform properties of the underlying library.
-type ExitError interface {
- String() string
- Error() string
- Exited() bool
- ExitStatus() int
-}
-
-// CodeExitError is an implementation of ExitError consisting of an error object
-// and an exit code (the upper bits of os.exec.ExitStatus).
-type CodeExitError struct {
- Err error
- Code int
-}
-
-var _ ExitError = CodeExitError{}
-
-func (e CodeExitError) Error() string {
- return e.Err.Error()
-}
-
-func (e CodeExitError) String() string {
- return e.Err.Error()
-}
-
-func (e CodeExitError) Exited() bool {
- return true
-}
-
-func (e CodeExitError) ExitStatus() int {
- return e.Code
-}
diff --git a/vendor/k8s.io/client-go/util/flowcontrol/backoff.go b/vendor/k8s.io/client-go/util/flowcontrol/backoff.go
deleted file mode 100644
index 39cd72f95..000000000
--- a/vendor/k8s.io/client-go/util/flowcontrol/backoff.go
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package flowcontrol
-
-import (
- "sync"
- "time"
-
- "k8s.io/apimachinery/pkg/util/clock"
- "k8s.io/utils/integer"
-)
-
-type backoffEntry struct {
- backoff time.Duration
- lastUpdate time.Time
-}
-
-type Backoff struct {
- sync.Mutex
- Clock clock.Clock
- defaultDuration time.Duration
- maxDuration time.Duration
- perItemBackoff map[string]*backoffEntry
-}
-
-func NewFakeBackOff(initial, max time.Duration, tc *clock.FakeClock) *Backoff {
- return &Backoff{
- perItemBackoff: map[string]*backoffEntry{},
- Clock: tc,
- defaultDuration: initial,
- maxDuration: max,
- }
-}
-
-func NewBackOff(initial, max time.Duration) *Backoff {
- return &Backoff{
- perItemBackoff: map[string]*backoffEntry{},
- Clock: clock.RealClock{},
- defaultDuration: initial,
- maxDuration: max,
- }
-}
-
-// Get the current backoff Duration
-func (p *Backoff) Get(id string) time.Duration {
- p.Lock()
- defer p.Unlock()
- var delay time.Duration
- entry, ok := p.perItemBackoff[id]
- if ok {
- delay = entry.backoff
- }
- return delay
-}
-
-// move backoff to the next mark, capping at maxDuration
-func (p *Backoff) Next(id string, eventTime time.Time) {
- p.Lock()
- defer p.Unlock()
- entry, ok := p.perItemBackoff[id]
- if !ok || hasExpired(eventTime, entry.lastUpdate, p.maxDuration) {
- entry = p.initEntryUnsafe(id)
- } else {
- delay := entry.backoff * 2 // exponential
- entry.backoff = time.Duration(integer.Int64Min(int64(delay), int64(p.maxDuration)))
- }
- entry.lastUpdate = p.Clock.Now()
-}
-
-// Reset forces clearing of all backoff data for a given key.
-func (p *Backoff) Reset(id string) {
- p.Lock()
- defer p.Unlock()
- delete(p.perItemBackoff, id)
-}
-
-// Returns True if the elapsed time since eventTime is smaller than the current backoff window
-func (p *Backoff) IsInBackOffSince(id string, eventTime time.Time) bool {
- p.Lock()
- defer p.Unlock()
- entry, ok := p.perItemBackoff[id]
- if !ok {
- return false
- }
- if hasExpired(eventTime, entry.lastUpdate, p.maxDuration) {
- return false
- }
- return p.Clock.Since(eventTime) < entry.backoff
-}
-
-// Returns True if time since lastupdate is less than the current backoff window.
-func (p *Backoff) IsInBackOffSinceUpdate(id string, eventTime time.Time) bool {
- p.Lock()
- defer p.Unlock()
- entry, ok := p.perItemBackoff[id]
- if !ok {
- return false
- }
- if hasExpired(eventTime, entry.lastUpdate, p.maxDuration) {
- return false
- }
- return eventTime.Sub(entry.lastUpdate) < entry.backoff
-}
-
-// Garbage collect records that have aged past maxDuration. Backoff users are expected
-// to invoke this periodically.
-func (p *Backoff) GC() {
- p.Lock()
- defer p.Unlock()
- now := p.Clock.Now()
- for id, entry := range p.perItemBackoff {
- if now.Sub(entry.lastUpdate) > p.maxDuration*2 {
- // GC when entry has not been updated for 2*maxDuration
- delete(p.perItemBackoff, id)
- }
- }
-}
-
-func (p *Backoff) DeleteEntry(id string) {
- p.Lock()
- defer p.Unlock()
- delete(p.perItemBackoff, id)
-}
-
-// Take a lock on *Backoff, before calling initEntryUnsafe
-func (p *Backoff) initEntryUnsafe(id string) *backoffEntry {
- entry := &backoffEntry{backoff: p.defaultDuration}
- p.perItemBackoff[id] = entry
- return entry
-}
-
-// After 2*maxDuration we restart the backoff factor to the beginning
-func hasExpired(eventTime time.Time, lastUpdate time.Time, maxDuration time.Duration) bool {
- return eventTime.Sub(lastUpdate) > maxDuration*2 // consider stable if it's ok for twice the maxDuration
-}
diff --git a/vendor/k8s.io/client-go/util/flowcontrol/throttle.go b/vendor/k8s.io/client-go/util/flowcontrol/throttle.go
deleted file mode 100644
index e671c044d..000000000
--- a/vendor/k8s.io/client-go/util/flowcontrol/throttle.go
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package flowcontrol
-
-import (
- "sync"
- "time"
-
- "golang.org/x/time/rate"
-)
-
-type RateLimiter interface {
- // TryAccept returns true if a token is taken immediately. Otherwise,
- // it returns false.
- TryAccept() bool
- // Accept returns once a token becomes available.
- Accept()
- // Stop stops the rate limiter, subsequent calls to CanAccept will return false
- Stop()
- // QPS returns QPS of this rate limiter
- QPS() float32
-}
-
-type tokenBucketRateLimiter struct {
- limiter *rate.Limiter
- clock Clock
- qps float32
-}
-
-// NewTokenBucketRateLimiter creates a rate limiter which implements a token bucket approach.
-// The rate limiter allows bursts of up to 'burst' to exceed the QPS, while still maintaining a
-// smoothed qps rate of 'qps'.
-// The bucket is initially filled with 'burst' tokens, and refills at a rate of 'qps'.
-// The maximum number of tokens in the bucket is capped at 'burst'.
-func NewTokenBucketRateLimiter(qps float32, burst int) RateLimiter {
- limiter := rate.NewLimiter(rate.Limit(qps), burst)
- return newTokenBucketRateLimiter(limiter, realClock{}, qps)
-}
-
-// An injectable, mockable clock interface.
-type Clock interface {
- Now() time.Time
- Sleep(time.Duration)
-}
-
-type realClock struct{}
-
-func (realClock) Now() time.Time {
- return time.Now()
-}
-func (realClock) Sleep(d time.Duration) {
- time.Sleep(d)
-}
-
-// NewTokenBucketRateLimiterWithClock is identical to NewTokenBucketRateLimiter
-// but allows an injectable clock, for testing.
-func NewTokenBucketRateLimiterWithClock(qps float32, burst int, c Clock) RateLimiter {
- limiter := rate.NewLimiter(rate.Limit(qps), burst)
- return newTokenBucketRateLimiter(limiter, c, qps)
-}
-
-func newTokenBucketRateLimiter(limiter *rate.Limiter, c Clock, qps float32) RateLimiter {
- return &tokenBucketRateLimiter{
- limiter: limiter,
- clock: c,
- qps: qps,
- }
-}
-
-func (t *tokenBucketRateLimiter) TryAccept() bool {
- return t.limiter.AllowN(t.clock.Now(), 1)
-}
-
-// Accept will block until a token becomes available
-func (t *tokenBucketRateLimiter) Accept() {
- now := t.clock.Now()
- t.clock.Sleep(t.limiter.ReserveN(now, 1).DelayFrom(now))
-}
-
-func (t *tokenBucketRateLimiter) Stop() {
-}
-
-func (t *tokenBucketRateLimiter) QPS() float32 {
- return t.qps
-}
-
-type fakeAlwaysRateLimiter struct{}
-
-func NewFakeAlwaysRateLimiter() RateLimiter {
- return &fakeAlwaysRateLimiter{}
-}
-
-func (t *fakeAlwaysRateLimiter) TryAccept() bool {
- return true
-}
-
-func (t *fakeAlwaysRateLimiter) Stop() {}
-
-func (t *fakeAlwaysRateLimiter) Accept() {}
-
-func (t *fakeAlwaysRateLimiter) QPS() float32 {
- return 1
-}
-
-type fakeNeverRateLimiter struct {
- wg sync.WaitGroup
-}
-
-func NewFakeNeverRateLimiter() RateLimiter {
- rl := fakeNeverRateLimiter{}
- rl.wg.Add(1)
- return &rl
-}
-
-func (t *fakeNeverRateLimiter) TryAccept() bool {
- return false
-}
-
-func (t *fakeNeverRateLimiter) Stop() {
- t.wg.Done()
-}
-
-func (t *fakeNeverRateLimiter) Accept() {
- t.wg.Wait()
-}
-
-func (t *fakeNeverRateLimiter) QPS() float32 {
- return 1
-}
diff --git a/vendor/k8s.io/client-go/util/keyutil/OWNERS b/vendor/k8s.io/client-go/util/keyutil/OWNERS
deleted file mode 100644
index 470b7a1c9..000000000
--- a/vendor/k8s.io/client-go/util/keyutil/OWNERS
+++ /dev/null
@@ -1,7 +0,0 @@
-approvers:
-- sig-auth-certificates-approvers
-reviewers:
-- sig-auth-certificates-reviewers
-labels:
-- sig/auth
-
diff --git a/vendor/k8s.io/client-go/util/keyutil/key.go b/vendor/k8s.io/client-go/util/keyutil/key.go
deleted file mode 100644
index 83c2c6254..000000000
--- a/vendor/k8s.io/client-go/util/keyutil/key.go
+++ /dev/null
@@ -1,323 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package keyutil contains utilities for managing public/private key pairs.
-package keyutil
-
-import (
- "crypto"
- "crypto/ecdsa"
- "crypto/elliptic"
- cryptorand "crypto/rand"
- "crypto/rsa"
- "crypto/x509"
- "encoding/pem"
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
-)
-
-const (
- // ECPrivateKeyBlockType is a possible value for pem.Block.Type.
- ECPrivateKeyBlockType = "EC PRIVATE KEY"
- // RSAPrivateKeyBlockType is a possible value for pem.Block.Type.
- RSAPrivateKeyBlockType = "RSA PRIVATE KEY"
- // PrivateKeyBlockType is a possible value for pem.Block.Type.
- PrivateKeyBlockType = "PRIVATE KEY"
- // PublicKeyBlockType is a possible value for pem.Block.Type.
- PublicKeyBlockType = "PUBLIC KEY"
-)
-
-// MakeEllipticPrivateKeyPEM creates an ECDSA private key
-func MakeEllipticPrivateKeyPEM() ([]byte, error) {
- privateKey, err := ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader)
- if err != nil {
- return nil, err
- }
-
- derBytes, err := x509.MarshalECPrivateKey(privateKey)
- if err != nil {
- return nil, err
- }
-
- privateKeyPemBlock := &pem.Block{
- Type: ECPrivateKeyBlockType,
- Bytes: derBytes,
- }
- return pem.EncodeToMemory(privateKeyPemBlock), nil
-}
-
-// WriteKey writes the pem-encoded key data to keyPath.
-// The key file will be created with file mode 0600.
-// If the key file already exists, it will be overwritten.
-// The parent directory of the keyPath will be created as needed with file mode 0755.
-func WriteKey(keyPath string, data []byte) error {
- if err := os.MkdirAll(filepath.Dir(keyPath), os.FileMode(0755)); err != nil {
- return err
- }
- return ioutil.WriteFile(keyPath, data, os.FileMode(0600))
-}
-
-// LoadOrGenerateKeyFile looks for a key in the file at the given path. If it
-// can't find one, it will generate a new key and store it there.
-func LoadOrGenerateKeyFile(keyPath string) (data []byte, wasGenerated bool, err error) {
- loadedData, err := ioutil.ReadFile(keyPath)
- // Call verifyKeyData to ensure the file wasn't empty/corrupt.
- if err == nil && verifyKeyData(loadedData) {
- return loadedData, false, err
- }
- if !os.IsNotExist(err) {
- return nil, false, fmt.Errorf("error loading key from %s: %v", keyPath, err)
- }
-
- generatedData, err := MakeEllipticPrivateKeyPEM()
- if err != nil {
- return nil, false, fmt.Errorf("error generating key: %v", err)
- }
- if err := WriteKey(keyPath, generatedData); err != nil {
- return nil, false, fmt.Errorf("error writing key to %s: %v", keyPath, err)
- }
- return generatedData, true, nil
-}
-
-// MarshalPrivateKeyToPEM converts a known private key type of RSA or ECDSA to
-// a PEM encoded block or returns an error.
-func MarshalPrivateKeyToPEM(privateKey crypto.PrivateKey) ([]byte, error) {
- switch t := privateKey.(type) {
- case *ecdsa.PrivateKey:
- derBytes, err := x509.MarshalECPrivateKey(t)
- if err != nil {
- return nil, err
- }
- block := &pem.Block{
- Type: ECPrivateKeyBlockType,
- Bytes: derBytes,
- }
- return pem.EncodeToMemory(block), nil
- case *rsa.PrivateKey:
- block := &pem.Block{
- Type: RSAPrivateKeyBlockType,
- Bytes: x509.MarshalPKCS1PrivateKey(t),
- }
- return pem.EncodeToMemory(block), nil
- default:
- return nil, fmt.Errorf("private key is not a recognized type: %T", privateKey)
- }
-}
-
-// PrivateKeyFromFile returns the private key in rsa.PrivateKey or ecdsa.PrivateKey format from a given PEM-encoded file.
-// Returns an error if the file could not be read or if the private key could not be parsed.
-func PrivateKeyFromFile(file string) (interface{}, error) {
- data, err := ioutil.ReadFile(file)
- if err != nil {
- return nil, err
- }
- key, err := ParsePrivateKeyPEM(data)
- if err != nil {
- return nil, fmt.Errorf("error reading private key file %s: %v", file, err)
- }
- return key, nil
-}
-
-// PublicKeysFromFile returns the public keys in rsa.PublicKey or ecdsa.PublicKey format from a given PEM-encoded file.
-// Reads public keys from both public and private key files.
-func PublicKeysFromFile(file string) ([]interface{}, error) {
- data, err := ioutil.ReadFile(file)
- if err != nil {
- return nil, err
- }
- keys, err := ParsePublicKeysPEM(data)
- if err != nil {
- return nil, fmt.Errorf("error reading public key file %s: %v", file, err)
- }
- return keys, nil
-}
-
-// verifyKeyData returns true if the provided data appears to be a valid private key.
-func verifyKeyData(data []byte) bool {
- if len(data) == 0 {
- return false
- }
- _, err := ParsePrivateKeyPEM(data)
- return err == nil
-}
-
-// ParsePrivateKeyPEM returns a private key parsed from a PEM block in the supplied data.
-// Recognizes PEM blocks for "EC PRIVATE KEY", "RSA PRIVATE KEY", or "PRIVATE KEY"
-func ParsePrivateKeyPEM(keyData []byte) (interface{}, error) {
- var privateKeyPemBlock *pem.Block
- for {
- privateKeyPemBlock, keyData = pem.Decode(keyData)
- if privateKeyPemBlock == nil {
- break
- }
-
- switch privateKeyPemBlock.Type {
- case ECPrivateKeyBlockType:
- // ECDSA Private Key in ASN.1 format
- if key, err := x509.ParseECPrivateKey(privateKeyPemBlock.Bytes); err == nil {
- return key, nil
- }
- case RSAPrivateKeyBlockType:
- // RSA Private Key in PKCS#1 format
- if key, err := x509.ParsePKCS1PrivateKey(privateKeyPemBlock.Bytes); err == nil {
- return key, nil
- }
- case PrivateKeyBlockType:
- // RSA or ECDSA Private Key in unencrypted PKCS#8 format
- if key, err := x509.ParsePKCS8PrivateKey(privateKeyPemBlock.Bytes); err == nil {
- return key, nil
- }
- }
-
- // tolerate non-key PEM blocks for compatibility with things like "EC PARAMETERS" blocks
- // originally, only the first PEM block was parsed and expected to be a key block
- }
-
- // we read all the PEM blocks and didn't recognize one
- return nil, fmt.Errorf("data does not contain a valid RSA or ECDSA private key")
-}
-
-// ParsePublicKeysPEM is a helper function for reading an array of rsa.PublicKey or ecdsa.PublicKey from a PEM-encoded byte array.
-// Reads public keys from both public and private key files.
-func ParsePublicKeysPEM(keyData []byte) ([]interface{}, error) {
- var block *pem.Block
- keys := []interface{}{}
- for {
- // read the next block
- block, keyData = pem.Decode(keyData)
- if block == nil {
- break
- }
-
- // test block against parsing functions
- if privateKey, err := parseRSAPrivateKey(block.Bytes); err == nil {
- keys = append(keys, &privateKey.PublicKey)
- continue
- }
- if publicKey, err := parseRSAPublicKey(block.Bytes); err == nil {
- keys = append(keys, publicKey)
- continue
- }
- if privateKey, err := parseECPrivateKey(block.Bytes); err == nil {
- keys = append(keys, &privateKey.PublicKey)
- continue
- }
- if publicKey, err := parseECPublicKey(block.Bytes); err == nil {
- keys = append(keys, publicKey)
- continue
- }
-
- // tolerate non-key PEM blocks for backwards compatibility
- // originally, only the first PEM block was parsed and expected to be a key block
- }
-
- if len(keys) == 0 {
- return nil, fmt.Errorf("data does not contain any valid RSA or ECDSA public keys")
- }
- return keys, nil
-}
-
-// parseRSAPublicKey parses a single RSA public key from the provided data
-func parseRSAPublicKey(data []byte) (*rsa.PublicKey, error) {
- var err error
-
- // Parse the key
- var parsedKey interface{}
- if parsedKey, err = x509.ParsePKIXPublicKey(data); err != nil {
- if cert, err := x509.ParseCertificate(data); err == nil {
- parsedKey = cert.PublicKey
- } else {
- return nil, err
- }
- }
-
- // Test if parsed key is an RSA Public Key
- var pubKey *rsa.PublicKey
- var ok bool
- if pubKey, ok = parsedKey.(*rsa.PublicKey); !ok {
- return nil, fmt.Errorf("data doesn't contain valid RSA Public Key")
- }
-
- return pubKey, nil
-}
-
-// parseRSAPrivateKey parses a single RSA private key from the provided data
-func parseRSAPrivateKey(data []byte) (*rsa.PrivateKey, error) {
- var err error
-
- // Parse the key
- var parsedKey interface{}
- if parsedKey, err = x509.ParsePKCS1PrivateKey(data); err != nil {
- if parsedKey, err = x509.ParsePKCS8PrivateKey(data); err != nil {
- return nil, err
- }
- }
-
- // Test if parsed key is an RSA Private Key
- var privKey *rsa.PrivateKey
- var ok bool
- if privKey, ok = parsedKey.(*rsa.PrivateKey); !ok {
- return nil, fmt.Errorf("data doesn't contain valid RSA Private Key")
- }
-
- return privKey, nil
-}
-
-// parseECPublicKey parses a single ECDSA public key from the provided data
-func parseECPublicKey(data []byte) (*ecdsa.PublicKey, error) {
- var err error
-
- // Parse the key
- var parsedKey interface{}
- if parsedKey, err = x509.ParsePKIXPublicKey(data); err != nil {
- if cert, err := x509.ParseCertificate(data); err == nil {
- parsedKey = cert.PublicKey
- } else {
- return nil, err
- }
- }
-
- // Test if parsed key is an ECDSA Public Key
- var pubKey *ecdsa.PublicKey
- var ok bool
- if pubKey, ok = parsedKey.(*ecdsa.PublicKey); !ok {
- return nil, fmt.Errorf("data doesn't contain valid ECDSA Public Key")
- }
-
- return pubKey, nil
-}
-
-// parseECPrivateKey parses a single ECDSA private key from the provided data
-func parseECPrivateKey(data []byte) (*ecdsa.PrivateKey, error) {
- var err error
-
- // Parse the key
- var parsedKey interface{}
- if parsedKey, err = x509.ParseECPrivateKey(data); err != nil {
- return nil, err
- }
-
- // Test if parsed key is an ECDSA Private Key
- var privKey *ecdsa.PrivateKey
- var ok bool
- if privKey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {
- return nil, fmt.Errorf("data doesn't contain valid ECDSA Private Key")
- }
-
- return privKey, nil
-}
diff --git a/vendor/k8s.io/klog/.travis.yml b/vendor/k8s.io/klog/.travis.yml
deleted file mode 100644
index 5677664c2..000000000
--- a/vendor/k8s.io/klog/.travis.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-language: go
-go_import_path: k8s.io/klog
-dist: xenial
-go:
- - 1.9.x
- - 1.10.x
- - 1.11.x
- - 1.12.x
-script:
- - go get -t -v ./...
- - diff -u <(echo -n) <(gofmt -d .)
- - diff -u <(echo -n) <(golint $(go list -e ./...))
- - go tool vet . || go vet .
- - go test -v -race ./...
-install:
- - go get golang.org/x/lint/golint
diff --git a/vendor/k8s.io/klog/CONTRIBUTING.md b/vendor/k8s.io/klog/CONTRIBUTING.md
deleted file mode 100644
index 574a56abb..000000000
--- a/vendor/k8s.io/klog/CONTRIBUTING.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# Contributing Guidelines
-
-Welcome to Kubernetes. We are excited about the prospect of you joining our [community](https://github.com/kubernetes/community)! The Kubernetes community abides by the CNCF [code of conduct](code-of-conduct.md). Here is an excerpt:
-
-_As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities._
-
-## Getting Started
-
-We have full documentation on how to get started contributing here:
-
-- [Contributor License Agreement](https://git.k8s.io/community/CLA.md) Kubernetes projects require that you sign a Contributor License Agreement (CLA) before we can accept your pull requests
-- [Kubernetes Contributor Guide](http://git.k8s.io/community/contributors/guide) - Main contributor documentation, or you can just jump directly to the [contributing section](http://git.k8s.io/community/contributors/guide#contributing)
-- [Contributor Cheat Sheet](https://git.k8s.io/community/contributors/guide/contributor-cheatsheet.md) - Common resources for existing developers
-
-## Mentorship
-
-- [Mentoring Initiatives](https://git.k8s.io/community/mentoring) - We have a diverse set of mentorship programs available that are always looking for volunteers!
-
-## Contact Information
-
-- [Slack](https://kubernetes.slack.com/messages/sig-architecture)
-- [Mailing List](https://groups.google.com/forum/#!forum/kubernetes-sig-architecture)
diff --git a/vendor/k8s.io/klog/LICENSE b/vendor/k8s.io/klog/LICENSE
deleted file mode 100644
index 37ec93a14..000000000
--- a/vendor/k8s.io/klog/LICENSE
+++ /dev/null
@@ -1,191 +0,0 @@
-Apache License
-Version 2.0, January 2004
-http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-"License" shall mean the terms and conditions for use, reproduction, and
-distribution as defined by Sections 1 through 9 of this document.
-
-"Licensor" shall mean the copyright owner or entity authorized by the copyright
-owner that is granting the License.
-
-"Legal Entity" shall mean the union of the acting entity and all other entities
-that control, are controlled by, or are under common control with that entity.
-For the purposes of this definition, "control" means (i) the power, direct or
-indirect, to cause the direction or management of such entity, whether by
-contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
-outstanding shares, or (iii) beneficial ownership of such entity.
-
-"You" (or "Your") shall mean an individual or Legal Entity exercising
-permissions granted by this License.
-
-"Source" form shall mean the preferred form for making modifications, including
-but not limited to software source code, documentation source, and configuration
-files.
-
-"Object" form shall mean any form resulting from mechanical transformation or
-translation of a Source form, including but not limited to compiled object code,
-generated documentation, and conversions to other media types.
-
-"Work" shall mean the work of authorship, whether in Source or Object form, made
-available under the License, as indicated by a copyright notice that is included
-in or attached to the work (an example is provided in the Appendix below).
-
-"Derivative Works" shall mean any work, whether in Source or Object form, that
-is based on (or derived from) the Work and for which the editorial revisions,
-annotations, elaborations, or other modifications represent, as a whole, an
-original work of authorship. For the purposes of this License, Derivative Works
-shall not include works that remain separable from, or merely link (or bind by
-name) to the interfaces of, the Work and Derivative Works thereof.
-
-"Contribution" shall mean any work of authorship, including the original version
-of the Work and any modifications or additions to that Work or Derivative Works
-thereof, that is intentionally submitted to Licensor for inclusion in the Work
-by the copyright owner or by an individual or Legal Entity authorized to submit
-on behalf of the copyright owner. For the purposes of this definition,
-"submitted" means any form of electronic, verbal, or written communication sent
-to the Licensor or its representatives, including but not limited to
-communication on electronic mailing lists, source code control systems, and
-issue tracking systems that are managed by, or on behalf of, the Licensor for
-the purpose of discussing and improving the Work, but excluding communication
-that is conspicuously marked or otherwise designated in writing by the copyright
-owner as "Not a Contribution."
-
-"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
-of whom a Contribution has been received by Licensor and subsequently
-incorporated within the Work.
-
-2. Grant of Copyright License.
-
-Subject to the terms and conditions of this License, each Contributor hereby
-grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
-irrevocable copyright license to reproduce, prepare Derivative Works of,
-publicly display, publicly perform, sublicense, and distribute the Work and such
-Derivative Works in Source or Object form.
-
-3. Grant of Patent License.
-
-Subject to the terms and conditions of this License, each Contributor hereby
-grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
-irrevocable (except as stated in this section) patent license to make, have
-made, use, offer to sell, sell, import, and otherwise transfer the Work, where
-such license applies only to those patent claims licensable by such Contributor
-that are necessarily infringed by their Contribution(s) alone or by combination
-of their Contribution(s) with the Work to which such Contribution(s) was
-submitted. If You institute patent litigation against any entity (including a
-cross-claim or counterclaim in a lawsuit) alleging that the Work or a
-Contribution incorporated within the Work constitutes direct or contributory
-patent infringement, then any patent licenses granted to You under this License
-for that Work shall terminate as of the date such litigation is filed.
-
-4. Redistribution.
-
-You may reproduce and distribute copies of the Work or Derivative Works thereof
-in any medium, with or without modifications, and in Source or Object form,
-provided that You meet the following conditions:
-
-You must give any other recipients of the Work or Derivative Works a copy of
-this License; and
-You must cause any modified files to carry prominent notices stating that You
-changed the files; and
-You must retain, in the Source form of any Derivative Works that You distribute,
-all copyright, patent, trademark, and attribution notices from the Source form
-of the Work, excluding those notices that do not pertain to any part of the
-Derivative Works; and
-If the Work includes a "NOTICE" text file as part of its distribution, then any
-Derivative Works that You distribute must include a readable copy of the
-attribution notices contained within such NOTICE file, excluding those notices
-that do not pertain to any part of the Derivative Works, in at least one of the
-following places: within a NOTICE text file distributed as part of the
-Derivative Works; within the Source form or documentation, if provided along
-with the Derivative Works; or, within a display generated by the Derivative
-Works, if and wherever such third-party notices normally appear. The contents of
-the NOTICE file are for informational purposes only and do not modify the
-License. You may add Your own attribution notices within Derivative Works that
-You distribute, alongside or as an addendum to the NOTICE text from the Work,
-provided that such additional attribution notices cannot be construed as
-modifying the License.
-You may add Your own copyright statement to Your modifications and may provide
-additional or different license terms and conditions for use, reproduction, or
-distribution of Your modifications, or for any such Derivative Works as a whole,
-provided Your use, reproduction, and distribution of the Work otherwise complies
-with the conditions stated in this License.
-
-5. Submission of Contributions.
-
-Unless You explicitly state otherwise, any Contribution intentionally submitted
-for inclusion in the Work by You to the Licensor shall be under the terms and
-conditions of this License, without any additional terms or conditions.
-Notwithstanding the above, nothing herein shall supersede or modify the terms of
-any separate license agreement you may have executed with Licensor regarding
-such Contributions.
-
-6. Trademarks.
-
-This License does not grant permission to use the trade names, trademarks,
-service marks, or product names of the Licensor, except as required for
-reasonable and customary use in describing the origin of the Work and
-reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty.
-
-Unless required by applicable law or agreed to in writing, Licensor provides the
-Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
-including, without limitation, any warranties or conditions of TITLE,
-NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
-solely responsible for determining the appropriateness of using or
-redistributing the Work and assume any risks associated with Your exercise of
-permissions under this License.
-
-8. Limitation of Liability.
-
-In no event and under no legal theory, whether in tort (including negligence),
-contract, or otherwise, unless required by applicable law (such as deliberate
-and grossly negligent acts) or agreed to in writing, shall any Contributor be
-liable to You for damages, including any direct, indirect, special, incidental,
-or consequential damages of any character arising as a result of this License or
-out of the use or inability to use the Work (including but not limited to
-damages for loss of goodwill, work stoppage, computer failure or malfunction, or
-any and all other commercial damages or losses), even if such Contributor has
-been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability.
-
-While redistributing the Work or Derivative Works thereof, You may choose to
-offer, and charge a fee for, acceptance of support, warranty, indemnity, or
-other liability obligations and/or rights consistent with this License. However,
-in accepting such obligations, You may act only on Your own behalf and on Your
-sole responsibility, not on behalf of any other Contributor, and only if You
-agree to indemnify, defend, and hold each Contributor harmless for any liability
-incurred by, or claims asserted against, such Contributor by reason of your
-accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
-
-APPENDIX: How to apply the Apache License to your work
-
-To apply the Apache License to your work, attach the following boilerplate
-notice, with the fields enclosed by brackets "[]" replaced with your own
-identifying information. (Don't include the brackets!) The text should be
-enclosed in the appropriate comment syntax for the file format. We also
-recommend that a file or class name and description of purpose be included on
-the same "printed page" as the copyright notice for easier identification within
-third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/vendor/k8s.io/klog/OWNERS b/vendor/k8s.io/klog/OWNERS
deleted file mode 100644
index 380e514f2..000000000
--- a/vendor/k8s.io/klog/OWNERS
+++ /dev/null
@@ -1,19 +0,0 @@
-# See the OWNERS docs at https://go.k8s.io/owners
-reviewers:
- - jayunit100
- - hoegaarden
- - andyxning
- - neolit123
- - pohly
- - yagonobre
- - vincepri
- - detiber
-approvers:
- - dims
- - thockin
- - justinsb
- - tallclair
- - piosz
- - brancz
- - DirectXMan12
- - lavalamp
diff --git a/vendor/k8s.io/klog/README.md b/vendor/k8s.io/klog/README.md
deleted file mode 100644
index 841468b4b..000000000
--- a/vendor/k8s.io/klog/README.md
+++ /dev/null
@@ -1,97 +0,0 @@
-klog
-====
-
-klog is a permanent fork of https://github.com/golang/glog.
-
-## Why was klog created?
-
-The decision to create klog was one that wasn't made lightly, but it was necessary due to some
-drawbacks that are present in [glog](https://github.com/golang/glog). Ultimately, the fork was created due to glog not being under active development; this can be seen in the glog README:
-
-> The code in this repo [...] is not itself under development
-
-This makes us unable to solve many use cases without a fork. The factors that contributed to needing feature development are listed below:
-
- * `glog` [presents a lot "gotchas"](https://github.com/kubernetes/kubernetes/issues/61006) and introduces challenges in containerized environments, all of which aren't well documented.
- * `glog` doesn't provide an easy way to test logs, which detracts from the stability of software using it
- * A long term goal is to implement a logging interface that allows us to add context, change output format, etc.
-
-Historical context is available here:
-
- * https://github.com/kubernetes/kubernetes/issues/61006
- * https://github.com/kubernetes/kubernetes/issues/70264
- * https://groups.google.com/forum/#!msg/kubernetes-sig-architecture/wCWiWf3Juzs/hXRVBH90CgAJ
- * https://groups.google.com/forum/#!msg/kubernetes-dev/7vnijOMhLS0/1oRiNtigBgAJ
-
-----
-
-How to use klog
-===============
-- Replace imports for `github.com/golang/glog` with `k8s.io/klog`
-- Use `klog.InitFlags(nil)` explicitly for initializing global flags as we no longer use `init()` method to register the flags
-- You can now use `log-file` instead of `log-dir` for logging to a single file (See `examples/log_file/usage_log_file.go`)
-- If you want to redirect everything logged using klog somewhere else (say syslog!), you can use `klog.SetOutput()` method and supply a `io.Writer`. (See `examples/set_output/usage_set_output.go`)
-- For more logging conventions (See [Logging Conventions](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md))
-
-### Coexisting with glog
-This package can be used side by side with glog. [This example](examples/coexist_glog/coexist_glog.go) shows how to initialize and syncronize flags from the global `flag.CommandLine` FlagSet. In addition, the example makes use of stderr as combined output by setting `alsologtostderr` (or `logtostderr`) to `true`.
-
-## Community, discussion, contribution, and support
-
-Learn how to engage with the Kubernetes community on the [community page](http://kubernetes.io/community/).
-
-You can reach the maintainers of this project at:
-
-- [Slack](https://kubernetes.slack.com/messages/sig-architecture)
-- [Mailing List](https://groups.google.com/forum/#!forum/kubernetes-sig-architecture)
-
-### Code of conduct
-
-Participation in the Kubernetes community is governed by the [Kubernetes Code of Conduct](code-of-conduct.md).
-
-----
-
-glog
-====
-
-Leveled execution logs for Go.
-
-This is an efficient pure Go implementation of leveled logs in the
-manner of the open source C++ package
- https://github.com/google/glog
-
-By binding methods to booleans it is possible to use the log package
-without paying the expense of evaluating the arguments to the log.
-Through the -vmodule flag, the package also provides fine-grained
-control over logging at the file level.
-
-The comment from glog.go introduces the ideas:
-
- Package glog implements logging analogous to the Google-internal
- C++ INFO/ERROR/V setup. It provides functions Info, Warning,
- Error, Fatal, plus formatting variants such as Infof. It
- also provides V-style logging controlled by the -v and
- -vmodule=file=2 flags.
-
- Basic examples:
-
- glog.Info("Prepare to repel boarders")
-
- glog.Fatalf("Initialization failed: %s", err)
-
- See the documentation for the V function for an explanation
- of these examples:
-
- if glog.V(2) {
- glog.Info("Starting transaction...")
- }
-
- glog.V(2).Infoln("Processed", nItems, "elements")
-
-
-The repository contains an open source version of the log package
-used inside Google. The master copy of the source lives inside
-Google, not here. The code in this repo is for export only and is not itself
-under development. Feature requests will be ignored.
-
-Send bug reports to golang-nuts@googlegroups.com.
diff --git a/vendor/k8s.io/klog/RELEASE.md b/vendor/k8s.io/klog/RELEASE.md
deleted file mode 100644
index b53eb960c..000000000
--- a/vendor/k8s.io/klog/RELEASE.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Release Process
-
-The `klog` is released on an as-needed basis. The process is as follows:
-
-1. An issue is proposing a new release with a changelog since the last release
-1. All [OWNERS](OWNERS) must LGTM this release
-1. An OWNER runs `git tag -s $VERSION` and inserts the changelog and pushes the tag with `git push $VERSION`
-1. The release issue is closed
-1. An announcement email is sent to `kubernetes-dev@googlegroups.com` with the subject `[ANNOUNCE] kubernetes-template-project $VERSION is released`
diff --git a/vendor/k8s.io/klog/SECURITY_CONTACTS b/vendor/k8s.io/klog/SECURITY_CONTACTS
deleted file mode 100644
index 6128a5869..000000000
--- a/vendor/k8s.io/klog/SECURITY_CONTACTS
+++ /dev/null
@@ -1,20 +0,0 @@
-# Defined below are the security contacts for this repo.
-#
-# They are the contact point for the Product Security Committee to reach out
-# to for triaging and handling of incoming issues.
-#
-# The below names agree to abide by the
-# [Embargo Policy](https://git.k8s.io/security/private-distributors-list.md#embargo-policy)
-# and will be removed and replaced if they violate that agreement.
-#
-# DO NOT REPORT SECURITY VULNERABILITIES DIRECTLY TO THESE NAMES, FOLLOW THE
-# INSTRUCTIONS AT https://kubernetes.io/security/
-
-dims
-thockin
-justinsb
-tallclair
-piosz
-brancz
-DirectXMan12
-lavalamp
diff --git a/vendor/k8s.io/klog/code-of-conduct.md b/vendor/k8s.io/klog/code-of-conduct.md
deleted file mode 100644
index 0d15c00cf..000000000
--- a/vendor/k8s.io/klog/code-of-conduct.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# Kubernetes Community Code of Conduct
-
-Please refer to our [Kubernetes Community Code of Conduct](https://git.k8s.io/community/code-of-conduct.md)
diff --git a/vendor/k8s.io/klog/go.mod b/vendor/k8s.io/klog/go.mod
deleted file mode 100644
index 3877d8546..000000000
--- a/vendor/k8s.io/klog/go.mod
+++ /dev/null
@@ -1,5 +0,0 @@
-module k8s.io/klog
-
-go 1.12
-
-require github.com/go-logr/logr v0.1.0
diff --git a/vendor/k8s.io/klog/go.sum b/vendor/k8s.io/klog/go.sum
deleted file mode 100644
index fb64d277a..000000000
--- a/vendor/k8s.io/klog/go.sum
+++ /dev/null
@@ -1,2 +0,0 @@
-github.com/go-logr/logr v0.1.0 h1:M1Tv3VzNlEHg6uyACnRdtrploV2P7wZqH8BoQMtz0cg=
-github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas=
diff --git a/vendor/k8s.io/klog/klog.go b/vendor/k8s.io/klog/klog.go
deleted file mode 100644
index 2712ce0af..000000000
--- a/vendor/k8s.io/klog/klog.go
+++ /dev/null
@@ -1,1308 +0,0 @@
-// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/
-//
-// Copyright 2013 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 klog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup.
-// It provides functions Info, Warning, Error, Fatal, plus formatting variants such as
-// Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags.
-//
-// Basic examples:
-//
-// klog.Info("Prepare to repel boarders")
-//
-// klog.Fatalf("Initialization failed: %s", err)
-//
-// See the documentation for the V function for an explanation of these examples:
-//
-// if klog.V(2) {
-// klog.Info("Starting transaction...")
-// }
-//
-// klog.V(2).Infoln("Processed", nItems, "elements")
-//
-// Log output is buffered and written periodically using Flush. Programs
-// should call Flush before exiting to guarantee all log output is written.
-//
-// By default, all log statements write to standard error.
-// This package provides several flags that modify this behavior.
-// As a result, flag.Parse must be called before any logging is done.
-//
-// -logtostderr=true
-// Logs are written to standard error instead of to files.
-// -alsologtostderr=false
-// Logs are written to standard error as well as to files.
-// -stderrthreshold=ERROR
-// Log events at or above this severity are logged to standard
-// error as well as to files.
-// -log_dir=""
-// Log files will be written to this directory instead of the
-// default temporary directory.
-//
-// Other flags provide aids to debugging.
-//
-// -log_backtrace_at=""
-// When set to a file and line number holding a logging statement,
-// such as
-// -log_backtrace_at=gopherflakes.go:234
-// a stack trace will be written to the Info log whenever execution
-// hits that statement. (Unlike with -vmodule, the ".go" must be
-// present.)
-// -v=0
-// Enable V-leveled logging at the specified level.
-// -vmodule=""
-// The syntax of the argument is a comma-separated list of pattern=N,
-// where pattern is a literal file name (minus the ".go" suffix) or
-// "glob" pattern and N is a V level. For instance,
-// -vmodule=gopher*=3
-// sets the V level to 3 in all Go files whose names begin "gopher".
-//
-package klog
-
-import (
- "bufio"
- "bytes"
- "errors"
- "flag"
- "fmt"
- "io"
- stdLog "log"
- "math"
- "os"
- "path/filepath"
- "runtime"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "time"
-)
-
-// severity identifies the sort of log: info, warning etc. It also implements
-// the flag.Value interface. The -stderrthreshold flag is of type severity and
-// should be modified only through the flag.Value interface. The values match
-// the corresponding constants in C++.
-type severity int32 // sync/atomic int32
-
-// These constants identify the log levels in order of increasing severity.
-// A message written to a high-severity log file is also written to each
-// lower-severity log file.
-const (
- infoLog severity = iota
- warningLog
- errorLog
- fatalLog
- numSeverity = 4
-)
-
-const severityChar = "IWEF"
-
-var severityName = []string{
- infoLog: "INFO",
- warningLog: "WARNING",
- errorLog: "ERROR",
- fatalLog: "FATAL",
-}
-
-// get returns the value of the severity.
-func (s *severity) get() severity {
- return severity(atomic.LoadInt32((*int32)(s)))
-}
-
-// set sets the value of the severity.
-func (s *severity) set(val severity) {
- atomic.StoreInt32((*int32)(s), int32(val))
-}
-
-// String is part of the flag.Value interface.
-func (s *severity) String() string {
- return strconv.FormatInt(int64(*s), 10)
-}
-
-// Get is part of the flag.Value interface.
-func (s *severity) Get() interface{} {
- return *s
-}
-
-// Set is part of the flag.Value interface.
-func (s *severity) Set(value string) error {
- var threshold severity
- // Is it a known name?
- if v, ok := severityByName(value); ok {
- threshold = v
- } else {
- v, err := strconv.ParseInt(value, 10, 32)
- if err != nil {
- return err
- }
- threshold = severity(v)
- }
- logging.stderrThreshold.set(threshold)
- return nil
-}
-
-func severityByName(s string) (severity, bool) {
- s = strings.ToUpper(s)
- for i, name := range severityName {
- if name == s {
- return severity(i), true
- }
- }
- return 0, false
-}
-
-// OutputStats tracks the number of output lines and bytes written.
-type OutputStats struct {
- lines int64
- bytes int64
-}
-
-// Lines returns the number of lines written.
-func (s *OutputStats) Lines() int64 {
- return atomic.LoadInt64(&s.lines)
-}
-
-// Bytes returns the number of bytes written.
-func (s *OutputStats) Bytes() int64 {
- return atomic.LoadInt64(&s.bytes)
-}
-
-// Stats tracks the number of lines of output and number of bytes
-// per severity level. Values must be read with atomic.LoadInt64.
-var Stats struct {
- Info, Warning, Error OutputStats
-}
-
-var severityStats = [numSeverity]*OutputStats{
- infoLog: &Stats.Info,
- warningLog: &Stats.Warning,
- errorLog: &Stats.Error,
-}
-
-// Level is exported because it appears in the arguments to V and is
-// the type of the v flag, which can be set programmatically.
-// It's a distinct type because we want to discriminate it from logType.
-// Variables of type level are only changed under logging.mu.
-// The -v flag is read only with atomic ops, so the state of the logging
-// module is consistent.
-
-// Level is treated as a sync/atomic int32.
-
-// Level specifies a level of verbosity for V logs. *Level implements
-// flag.Value; the -v flag is of type Level and should be modified
-// only through the flag.Value interface.
-type Level int32
-
-// get returns the value of the Level.
-func (l *Level) get() Level {
- return Level(atomic.LoadInt32((*int32)(l)))
-}
-
-// set sets the value of the Level.
-func (l *Level) set(val Level) {
- atomic.StoreInt32((*int32)(l), int32(val))
-}
-
-// String is part of the flag.Value interface.
-func (l *Level) String() string {
- return strconv.FormatInt(int64(*l), 10)
-}
-
-// Get is part of the flag.Value interface.
-func (l *Level) Get() interface{} {
- return *l
-}
-
-// Set is part of the flag.Value interface.
-func (l *Level) Set(value string) error {
- v, err := strconv.ParseInt(value, 10, 32)
- if err != nil {
- return err
- }
- logging.mu.Lock()
- defer logging.mu.Unlock()
- logging.setVState(Level(v), logging.vmodule.filter, false)
- return nil
-}
-
-// moduleSpec represents the setting of the -vmodule flag.
-type moduleSpec struct {
- filter []modulePat
-}
-
-// modulePat contains a filter for the -vmodule flag.
-// It holds a verbosity level and a file pattern to match.
-type modulePat struct {
- pattern string
- literal bool // The pattern is a literal string
- level Level
-}
-
-// match reports whether the file matches the pattern. It uses a string
-// comparison if the pattern contains no metacharacters.
-func (m *modulePat) match(file string) bool {
- if m.literal {
- return file == m.pattern
- }
- match, _ := filepath.Match(m.pattern, file)
- return match
-}
-
-func (m *moduleSpec) String() string {
- // Lock because the type is not atomic. TODO: clean this up.
- logging.mu.Lock()
- defer logging.mu.Unlock()
- var b bytes.Buffer
- for i, f := range m.filter {
- if i > 0 {
- b.WriteRune(',')
- }
- fmt.Fprintf(&b, "%s=%d", f.pattern, f.level)
- }
- return b.String()
-}
-
-// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the
-// struct is not exported.
-func (m *moduleSpec) Get() interface{} {
- return nil
-}
-
-var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N")
-
-// Syntax: -vmodule=recordio=2,file=1,gfs*=3
-func (m *moduleSpec) Set(value string) error {
- var filter []modulePat
- for _, pat := range strings.Split(value, ",") {
- if len(pat) == 0 {
- // Empty strings such as from a trailing comma can be ignored.
- continue
- }
- patLev := strings.Split(pat, "=")
- if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 {
- return errVmoduleSyntax
- }
- pattern := patLev[0]
- v, err := strconv.ParseInt(patLev[1], 10, 32)
- if err != nil {
- return errors.New("syntax error: expect comma-separated list of filename=N")
- }
- if v < 0 {
- return errors.New("negative value for vmodule level")
- }
- if v == 0 {
- continue // Ignore. It's harmless but no point in paying the overhead.
- }
- // TODO: check syntax of filter?
- filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)})
- }
- logging.mu.Lock()
- defer logging.mu.Unlock()
- logging.setVState(logging.verbosity, filter, true)
- return nil
-}
-
-// isLiteral reports whether the pattern is a literal string, that is, has no metacharacters
-// that require filepath.Match to be called to match the pattern.
-func isLiteral(pattern string) bool {
- return !strings.ContainsAny(pattern, `\*?[]`)
-}
-
-// traceLocation represents the setting of the -log_backtrace_at flag.
-type traceLocation struct {
- file string
- line int
-}
-
-// isSet reports whether the trace location has been specified.
-// logging.mu is held.
-func (t *traceLocation) isSet() bool {
- return t.line > 0
-}
-
-// match reports whether the specified file and line matches the trace location.
-// The argument file name is the full path, not the basename specified in the flag.
-// logging.mu is held.
-func (t *traceLocation) match(file string, line int) bool {
- if t.line != line {
- return false
- }
- if i := strings.LastIndex(file, "/"); i >= 0 {
- file = file[i+1:]
- }
- return t.file == file
-}
-
-func (t *traceLocation) String() string {
- // Lock because the type is not atomic. TODO: clean this up.
- logging.mu.Lock()
- defer logging.mu.Unlock()
- return fmt.Sprintf("%s:%d", t.file, t.line)
-}
-
-// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the
-// struct is not exported
-func (t *traceLocation) Get() interface{} {
- return nil
-}
-
-var errTraceSyntax = errors.New("syntax error: expect file.go:234")
-
-// Syntax: -log_backtrace_at=gopherflakes.go:234
-// Note that unlike vmodule the file extension is included here.
-func (t *traceLocation) Set(value string) error {
- if value == "" {
- // Unset.
- t.line = 0
- t.file = ""
- }
- fields := strings.Split(value, ":")
- if len(fields) != 2 {
- return errTraceSyntax
- }
- file, line := fields[0], fields[1]
- if !strings.Contains(file, ".") {
- return errTraceSyntax
- }
- v, err := strconv.Atoi(line)
- if err != nil {
- return errTraceSyntax
- }
- if v <= 0 {
- return errors.New("negative or zero value for level")
- }
- logging.mu.Lock()
- defer logging.mu.Unlock()
- t.line = v
- t.file = file
- return nil
-}
-
-// flushSyncWriter is the interface satisfied by logging destinations.
-type flushSyncWriter interface {
- Flush() error
- Sync() error
- io.Writer
-}
-
-// init sets up the defaults and runs flushDaemon.
-func init() {
- logging.stderrThreshold = errorLog // Default stderrThreshold is ERROR.
- logging.setVState(0, nil, false)
- logging.logDir = ""
- logging.logFile = ""
- logging.logFileMaxSizeMB = 1800
- logging.toStderr = true
- logging.alsoToStderr = false
- logging.skipHeaders = false
- logging.addDirHeader = false
- logging.skipLogHeaders = false
- go logging.flushDaemon()
-}
-
-// InitFlags is for explicitly initializing the flags.
-func InitFlags(flagset *flag.FlagSet) {
- if flagset == nil {
- flagset = flag.CommandLine
- }
-
- flagset.StringVar(&logging.logDir, "log_dir", logging.logDir, "If non-empty, write log files in this directory")
- flagset.StringVar(&logging.logFile, "log_file", logging.logFile, "If non-empty, use this log file")
- flagset.Uint64Var(&logging.logFileMaxSizeMB, "log_file_max_size", logging.logFileMaxSizeMB,
- "Defines the maximum size a log file can grow to. Unit is megabytes. "+
- "If the value is 0, the maximum file size is unlimited.")
- flagset.BoolVar(&logging.toStderr, "logtostderr", logging.toStderr, "log to standard error instead of files")
- flagset.BoolVar(&logging.alsoToStderr, "alsologtostderr", logging.alsoToStderr, "log to standard error as well as files")
- flagset.Var(&logging.verbosity, "v", "number for the log level verbosity")
- flagset.BoolVar(&logging.skipHeaders, "add_dir_header", logging.addDirHeader, "If true, adds the file directory to the header")
- flagset.BoolVar(&logging.skipHeaders, "skip_headers", logging.skipHeaders, "If true, avoid header prefixes in the log messages")
- flagset.BoolVar(&logging.skipLogHeaders, "skip_log_headers", logging.skipLogHeaders, "If true, avoid headers when opening log files")
- flagset.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr")
- flagset.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging")
- flagset.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace")
-}
-
-// Flush flushes all pending log I/O.
-func Flush() {
- logging.lockAndFlushAll()
-}
-
-// loggingT collects all the global state of the logging setup.
-type loggingT struct {
- // Boolean flags. Not handled atomically because the flag.Value interface
- // does not let us avoid the =true, and that shorthand is necessary for
- // compatibility. TODO: does this matter enough to fix? Seems unlikely.
- toStderr bool // The -logtostderr flag.
- alsoToStderr bool // The -alsologtostderr flag.
-
- // Level flag. Handled atomically.
- stderrThreshold severity // The -stderrthreshold flag.
-
- // freeList is a list of byte buffers, maintained under freeListMu.
- freeList *buffer
- // freeListMu maintains the free list. It is separate from the main mutex
- // so buffers can be grabbed and printed to without holding the main lock,
- // for better parallelization.
- freeListMu sync.Mutex
-
- // mu protects the remaining elements of this structure and is
- // used to synchronize logging.
- mu sync.Mutex
- // file holds writer for each of the log types.
- file [numSeverity]flushSyncWriter
- // pcs is used in V to avoid an allocation when computing the caller's PC.
- pcs [1]uintptr
- // vmap is a cache of the V Level for each V() call site, identified by PC.
- // It is wiped whenever the vmodule flag changes state.
- vmap map[uintptr]Level
- // filterLength stores the length of the vmodule filter chain. If greater
- // than zero, it means vmodule is enabled. It may be read safely
- // using sync.LoadInt32, but is only modified under mu.
- filterLength int32
- // traceLocation is the state of the -log_backtrace_at flag.
- traceLocation traceLocation
- // These flags are modified only under lock, although verbosity may be fetched
- // safely using atomic.LoadInt32.
- vmodule moduleSpec // The state of the -vmodule flag.
- verbosity Level // V logging level, the value of the -v flag/
-
- // If non-empty, overrides the choice of directory in which to write logs.
- // See createLogDirs for the full list of possible destinations.
- logDir string
-
- // If non-empty, specifies the path of the file to write logs. mutually exclusive
- // with the log-dir option.
- logFile string
-
- // When logFile is specified, this limiter makes sure the logFile won't exceeds a certain size. When exceeds, the
- // logFile will be cleaned up. If this value is 0, no size limitation will be applied to logFile.
- logFileMaxSizeMB uint64
-
- // If true, do not add the prefix headers, useful when used with SetOutput
- skipHeaders bool
-
- // If true, do not add the headers to log files
- skipLogHeaders bool
-
- // If true, add the file directory to the header
- addDirHeader bool
-}
-
-// buffer holds a byte Buffer for reuse. The zero value is ready for use.
-type buffer struct {
- bytes.Buffer
- tmp [64]byte // temporary byte array for creating headers.
- next *buffer
-}
-
-var logging loggingT
-
-// setVState sets a consistent state for V logging.
-// l.mu is held.
-func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) {
- // Turn verbosity off so V will not fire while we are in transition.
- logging.verbosity.set(0)
- // Ditto for filter length.
- atomic.StoreInt32(&logging.filterLength, 0)
-
- // Set the new filters and wipe the pc->Level map if the filter has changed.
- if setFilter {
- logging.vmodule.filter = filter
- logging.vmap = make(map[uintptr]Level)
- }
-
- // Things are consistent now, so enable filtering and verbosity.
- // They are enabled in order opposite to that in V.
- atomic.StoreInt32(&logging.filterLength, int32(len(filter)))
- logging.verbosity.set(verbosity)
-}
-
-// getBuffer returns a new, ready-to-use buffer.
-func (l *loggingT) getBuffer() *buffer {
- l.freeListMu.Lock()
- b := l.freeList
- if b != nil {
- l.freeList = b.next
- }
- l.freeListMu.Unlock()
- if b == nil {
- b = new(buffer)
- } else {
- b.next = nil
- b.Reset()
- }
- return b
-}
-
-// putBuffer returns a buffer to the free list.
-func (l *loggingT) putBuffer(b *buffer) {
- if b.Len() >= 256 {
- // Let big buffers die a natural death.
- return
- }
- l.freeListMu.Lock()
- b.next = l.freeList
- l.freeList = b
- l.freeListMu.Unlock()
-}
-
-var timeNow = time.Now // Stubbed out for testing.
-
-/*
-header formats a log header as defined by the C++ implementation.
-It returns a buffer containing the formatted header and the user's file and line number.
-The depth specifies how many stack frames above lives the source line to be identified in the log message.
-
-Log lines have this form:
- Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
-where the fields are defined as follows:
- L A single character, representing the log level (eg 'I' for INFO)
- mm The month (zero padded; ie May is '05')
- dd The day (zero padded)
- hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
- threadid The space-padded thread ID as returned by GetTID()
- file The file name
- line The line number
- msg The user-supplied message
-*/
-func (l *loggingT) header(s severity, depth int) (*buffer, string, int) {
- _, file, line, ok := runtime.Caller(3 + depth)
- if !ok {
- file = "???"
- line = 1
- } else {
- if slash := strings.LastIndex(file, "/"); slash >= 0 {
- path := file
- file = path[slash+1:]
- if l.addDirHeader {
- if dirsep := strings.LastIndex(path[:slash], "/"); dirsep >= 0 {
- file = path[dirsep+1:]
- }
- }
- }
- }
- return l.formatHeader(s, file, line), file, line
-}
-
-// formatHeader formats a log header using the provided file name and line number.
-func (l *loggingT) formatHeader(s severity, file string, line int) *buffer {
- now := timeNow()
- if line < 0 {
- line = 0 // not a real line number, but acceptable to someDigits
- }
- if s > fatalLog {
- s = infoLog // for safety.
- }
- buf := l.getBuffer()
- if l.skipHeaders {
- return buf
- }
-
- // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand.
- // It's worth about 3X. Fprintf is hard.
- _, month, day := now.Date()
- hour, minute, second := now.Clock()
- // Lmmdd hh:mm:ss.uuuuuu threadid file:line]
- buf.tmp[0] = severityChar[s]
- buf.twoDigits(1, int(month))
- buf.twoDigits(3, day)
- buf.tmp[5] = ' '
- buf.twoDigits(6, hour)
- buf.tmp[8] = ':'
- buf.twoDigits(9, minute)
- buf.tmp[11] = ':'
- buf.twoDigits(12, second)
- buf.tmp[14] = '.'
- buf.nDigits(6, 15, now.Nanosecond()/1000, '0')
- buf.tmp[21] = ' '
- buf.nDigits(7, 22, pid, ' ') // TODO: should be TID
- buf.tmp[29] = ' '
- buf.Write(buf.tmp[:30])
- buf.WriteString(file)
- buf.tmp[0] = ':'
- n := buf.someDigits(1, line)
- buf.tmp[n+1] = ']'
- buf.tmp[n+2] = ' '
- buf.Write(buf.tmp[:n+3])
- return buf
-}
-
-// Some custom tiny helper functions to print the log header efficiently.
-
-const digits = "0123456789"
-
-// twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i].
-func (buf *buffer) twoDigits(i, d int) {
- buf.tmp[i+1] = digits[d%10]
- d /= 10
- buf.tmp[i] = digits[d%10]
-}
-
-// nDigits formats an n-digit integer at buf.tmp[i],
-// padding with pad on the left.
-// It assumes d >= 0.
-func (buf *buffer) nDigits(n, i, d int, pad byte) {
- j := n - 1
- for ; j >= 0 && d > 0; j-- {
- buf.tmp[i+j] = digits[d%10]
- d /= 10
- }
- for ; j >= 0; j-- {
- buf.tmp[i+j] = pad
- }
-}
-
-// someDigits formats a zero-prefixed variable-width integer at buf.tmp[i].
-func (buf *buffer) someDigits(i, d int) int {
- // Print into the top, then copy down. We know there's space for at least
- // a 10-digit number.
- j := len(buf.tmp)
- for {
- j--
- buf.tmp[j] = digits[d%10]
- d /= 10
- if d == 0 {
- break
- }
- }
- return copy(buf.tmp[i:], buf.tmp[j:])
-}
-
-func (l *loggingT) println(s severity, args ...interface{}) {
- buf, file, line := l.header(s, 0)
- fmt.Fprintln(buf, args...)
- l.output(s, buf, file, line, false)
-}
-
-func (l *loggingT) print(s severity, args ...interface{}) {
- l.printDepth(s, 1, args...)
-}
-
-func (l *loggingT) printDepth(s severity, depth int, args ...interface{}) {
- buf, file, line := l.header(s, depth)
- fmt.Fprint(buf, args...)
- if buf.Bytes()[buf.Len()-1] != '\n' {
- buf.WriteByte('\n')
- }
- l.output(s, buf, file, line, false)
-}
-
-func (l *loggingT) printf(s severity, format string, args ...interface{}) {
- buf, file, line := l.header(s, 0)
- fmt.Fprintf(buf, format, args...)
- if buf.Bytes()[buf.Len()-1] != '\n' {
- buf.WriteByte('\n')
- }
- l.output(s, buf, file, line, false)
-}
-
-// printWithFileLine behaves like print but uses the provided file and line number. If
-// alsoLogToStderr is true, the log message always appears on standard error; it
-// will also appear in the log file unless --logtostderr is set.
-func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToStderr bool, args ...interface{}) {
- buf := l.formatHeader(s, file, line)
- fmt.Fprint(buf, args...)
- if buf.Bytes()[buf.Len()-1] != '\n' {
- buf.WriteByte('\n')
- }
- l.output(s, buf, file, line, alsoToStderr)
-}
-
-// redirectBuffer is used to set an alternate destination for the logs
-type redirectBuffer struct {
- w io.Writer
-}
-
-func (rb *redirectBuffer) Sync() error {
- return nil
-}
-
-func (rb *redirectBuffer) Flush() error {
- return nil
-}
-
-func (rb *redirectBuffer) Write(bytes []byte) (n int, err error) {
- return rb.w.Write(bytes)
-}
-
-// SetOutput sets the output destination for all severities
-func SetOutput(w io.Writer) {
- logging.mu.Lock()
- defer logging.mu.Unlock()
- for s := fatalLog; s >= infoLog; s-- {
- rb := &redirectBuffer{
- w: w,
- }
- logging.file[s] = rb
- }
-}
-
-// SetOutputBySeverity sets the output destination for specific severity
-func SetOutputBySeverity(name string, w io.Writer) {
- logging.mu.Lock()
- defer logging.mu.Unlock()
- sev, ok := severityByName(name)
- if !ok {
- panic(fmt.Sprintf("SetOutputBySeverity(%q): unrecognized severity name", name))
- }
- rb := &redirectBuffer{
- w: w,
- }
- logging.file[sev] = rb
-}
-
-// output writes the data to the log files and releases the buffer.
-func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) {
- l.mu.Lock()
- if l.traceLocation.isSet() {
- if l.traceLocation.match(file, line) {
- buf.Write(stacks(false))
- }
- }
- data := buf.Bytes()
- if l.toStderr {
- os.Stderr.Write(data)
- } else {
- if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() {
- os.Stderr.Write(data)
- }
-
- if logging.logFile != "" {
- // Since we are using a single log file, all of the items in l.file array
- // will point to the same file, so just use one of them to write data.
- if l.file[infoLog] == nil {
- if err := l.createFiles(infoLog); err != nil {
- os.Stderr.Write(data) // Make sure the message appears somewhere.
- l.exit(err)
- }
- }
- l.file[infoLog].Write(data)
- } else {
- if l.file[s] == nil {
- if err := l.createFiles(s); err != nil {
- os.Stderr.Write(data) // Make sure the message appears somewhere.
- l.exit(err)
- }
- }
-
- switch s {
- case fatalLog:
- l.file[fatalLog].Write(data)
- fallthrough
- case errorLog:
- l.file[errorLog].Write(data)
- fallthrough
- case warningLog:
- l.file[warningLog].Write(data)
- fallthrough
- case infoLog:
- l.file[infoLog].Write(data)
- }
- }
- }
- if s == fatalLog {
- // If we got here via Exit rather than Fatal, print no stacks.
- if atomic.LoadUint32(&fatalNoStacks) > 0 {
- l.mu.Unlock()
- timeoutFlush(10 * time.Second)
- os.Exit(1)
- }
- // Dump all goroutine stacks before exiting.
- // First, make sure we see the trace for the current goroutine on standard error.
- // If -logtostderr has been specified, the loop below will do that anyway
- // as the first stack in the full dump.
- if !l.toStderr {
- os.Stderr.Write(stacks(false))
- }
- // Write the stack trace for all goroutines to the files.
- trace := stacks(true)
- logExitFunc = func(error) {} // If we get a write error, we'll still exit below.
- for log := fatalLog; log >= infoLog; log-- {
- if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set.
- f.Write(trace)
- }
- }
- l.mu.Unlock()
- timeoutFlush(10 * time.Second)
- os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway.
- }
- l.putBuffer(buf)
- l.mu.Unlock()
- if stats := severityStats[s]; stats != nil {
- atomic.AddInt64(&stats.lines, 1)
- atomic.AddInt64(&stats.bytes, int64(len(data)))
- }
-}
-
-// timeoutFlush calls Flush and returns when it completes or after timeout
-// elapses, whichever happens first. This is needed because the hooks invoked
-// by Flush may deadlock when klog.Fatal is called from a hook that holds
-// a lock.
-func timeoutFlush(timeout time.Duration) {
- done := make(chan bool, 1)
- go func() {
- Flush() // calls logging.lockAndFlushAll()
- done <- true
- }()
- select {
- case <-done:
- case <-time.After(timeout):
- fmt.Fprintln(os.Stderr, "klog: Flush took longer than", timeout)
- }
-}
-
-// stacks is a wrapper for runtime.Stack that attempts to recover the data for all goroutines.
-func stacks(all bool) []byte {
- // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though.
- n := 10000
- if all {
- n = 100000
- }
- var trace []byte
- for i := 0; i < 5; i++ {
- trace = make([]byte, n)
- nbytes := runtime.Stack(trace, all)
- if nbytes < len(trace) {
- return trace[:nbytes]
- }
- n *= 2
- }
- return trace
-}
-
-// logExitFunc provides a simple mechanism to override the default behavior
-// of exiting on error. Used in testing and to guarantee we reach a required exit
-// for fatal logs. Instead, exit could be a function rather than a method but that
-// would make its use clumsier.
-var logExitFunc func(error)
-
-// exit is called if there is trouble creating or writing log files.
-// It flushes the logs and exits the program; there's no point in hanging around.
-// l.mu is held.
-func (l *loggingT) exit(err error) {
- fmt.Fprintf(os.Stderr, "log: exiting because of error: %s\n", err)
- // If logExitFunc is set, we do that instead of exiting.
- if logExitFunc != nil {
- logExitFunc(err)
- return
- }
- l.flushAll()
- os.Exit(2)
-}
-
-// syncBuffer joins a bufio.Writer to its underlying file, providing access to the
-// file's Sync method and providing a wrapper for the Write method that provides log
-// file rotation. There are conflicting methods, so the file cannot be embedded.
-// l.mu is held for all its methods.
-type syncBuffer struct {
- logger *loggingT
- *bufio.Writer
- file *os.File
- sev severity
- nbytes uint64 // The number of bytes written to this file
- maxbytes uint64 // The max number of bytes this syncBuffer.file can hold before cleaning up.
-}
-
-func (sb *syncBuffer) Sync() error {
- return sb.file.Sync()
-}
-
-// CalculateMaxSize returns the real max size in bytes after considering the default max size and the flag options.
-func CalculateMaxSize() uint64 {
- if logging.logFile != "" {
- if logging.logFileMaxSizeMB == 0 {
- // If logFileMaxSizeMB is zero, we don't have limitations on the log size.
- return math.MaxUint64
- }
- // Flag logFileMaxSizeMB is in MB for user convenience.
- return logging.logFileMaxSizeMB * 1024 * 1024
- }
- // If "log_file" flag is not specified, the target file (sb.file) will be cleaned up when reaches a fixed size.
- return MaxSize
-}
-
-func (sb *syncBuffer) Write(p []byte) (n int, err error) {
- if sb.nbytes+uint64(len(p)) >= sb.maxbytes {
- if err := sb.rotateFile(time.Now(), false); err != nil {
- sb.logger.exit(err)
- }
- }
- n, err = sb.Writer.Write(p)
- sb.nbytes += uint64(n)
- if err != nil {
- sb.logger.exit(err)
- }
- return
-}
-
-// rotateFile closes the syncBuffer's file and starts a new one.
-// The startup argument indicates whether this is the initial startup of klog.
-// If startup is true, existing files are opened for appending instead of truncated.
-func (sb *syncBuffer) rotateFile(now time.Time, startup bool) error {
- if sb.file != nil {
- sb.Flush()
- sb.file.Close()
- }
- var err error
- sb.file, _, err = create(severityName[sb.sev], now, startup)
- sb.nbytes = 0
- if err != nil {
- return err
- }
-
- sb.Writer = bufio.NewWriterSize(sb.file, bufferSize)
-
- if sb.logger.skipLogHeaders {
- return nil
- }
-
- // Write header.
- var buf bytes.Buffer
- fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05"))
- fmt.Fprintf(&buf, "Running on machine: %s\n", host)
- fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH)
- fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n")
- n, err := sb.file.Write(buf.Bytes())
- sb.nbytes += uint64(n)
- return err
-}
-
-// bufferSize sizes the buffer associated with each log file. It's large
-// so that log records can accumulate without the logging thread blocking
-// on disk I/O. The flushDaemon will block instead.
-const bufferSize = 256 * 1024
-
-// createFiles creates all the log files for severity from sev down to infoLog.
-// l.mu is held.
-func (l *loggingT) createFiles(sev severity) error {
- now := time.Now()
- // Files are created in decreasing severity order, so as soon as we find one
- // has already been created, we can stop.
- for s := sev; s >= infoLog && l.file[s] == nil; s-- {
- sb := &syncBuffer{
- logger: l,
- sev: s,
- maxbytes: CalculateMaxSize(),
- }
- if err := sb.rotateFile(now, true); err != nil {
- return err
- }
- l.file[s] = sb
- }
- return nil
-}
-
-const flushInterval = 5 * time.Second
-
-// flushDaemon periodically flushes the log file buffers.
-func (l *loggingT) flushDaemon() {
- for range time.NewTicker(flushInterval).C {
- l.lockAndFlushAll()
- }
-}
-
-// lockAndFlushAll is like flushAll but locks l.mu first.
-func (l *loggingT) lockAndFlushAll() {
- l.mu.Lock()
- l.flushAll()
- l.mu.Unlock()
-}
-
-// flushAll flushes all the logs and attempts to "sync" their data to disk.
-// l.mu is held.
-func (l *loggingT) flushAll() {
- // Flush from fatal down, in case there's trouble flushing.
- for s := fatalLog; s >= infoLog; s-- {
- file := l.file[s]
- if file != nil {
- file.Flush() // ignore error
- file.Sync() // ignore error
- }
- }
-}
-
-// CopyStandardLogTo arranges for messages written to the Go "log" package's
-// default logs to also appear in the Google logs for the named and lower
-// severities. Subsequent changes to the standard log's default output location
-// or format may break this behavior.
-//
-// Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not
-// recognized, CopyStandardLogTo panics.
-func CopyStandardLogTo(name string) {
- sev, ok := severityByName(name)
- if !ok {
- panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name))
- }
- // Set a log format that captures the user's file and line:
- // d.go:23: message
- stdLog.SetFlags(stdLog.Lshortfile)
- stdLog.SetOutput(logBridge(sev))
-}
-
-// logBridge provides the Write method that enables CopyStandardLogTo to connect
-// Go's standard logs to the logs provided by this package.
-type logBridge severity
-
-// Write parses the standard logging line and passes its components to the
-// logger for severity(lb).
-func (lb logBridge) Write(b []byte) (n int, err error) {
- var (
- file = "???"
- line = 1
- text string
- )
- // Split "d.go:23: message" into "d.go", "23", and "message".
- if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 {
- text = fmt.Sprintf("bad log format: %s", b)
- } else {
- file = string(parts[0])
- text = string(parts[2][1:]) // skip leading space
- line, err = strconv.Atoi(string(parts[1]))
- if err != nil {
- text = fmt.Sprintf("bad line number: %s", b)
- line = 1
- }
- }
- // printWithFileLine with alsoToStderr=true, so standard log messages
- // always appear on standard error.
- logging.printWithFileLine(severity(lb), file, line, true, text)
- return len(b), nil
-}
-
-// setV computes and remembers the V level for a given PC
-// when vmodule is enabled.
-// File pattern matching takes the basename of the file, stripped
-// of its .go suffix, and uses filepath.Match, which is a little more
-// general than the *? matching used in C++.
-// l.mu is held.
-func (l *loggingT) setV(pc uintptr) Level {
- fn := runtime.FuncForPC(pc)
- file, _ := fn.FileLine(pc)
- // The file is something like /a/b/c/d.go. We want just the d.
- if strings.HasSuffix(file, ".go") {
- file = file[:len(file)-3]
- }
- if slash := strings.LastIndex(file, "/"); slash >= 0 {
- file = file[slash+1:]
- }
- for _, filter := range l.vmodule.filter {
- if filter.match(file) {
- l.vmap[pc] = filter.level
- return filter.level
- }
- }
- l.vmap[pc] = 0
- return 0
-}
-
-// Verbose is a boolean type that implements Infof (like Printf) etc.
-// See the documentation of V for more information.
-type Verbose bool
-
-// V reports whether verbosity at the call site is at least the requested level.
-// The returned value is a boolean of type Verbose, which implements Info, Infoln
-// and Infof. These methods will write to the Info log if called.
-// Thus, one may write either
-// if klog.V(2) { klog.Info("log this") }
-// or
-// klog.V(2).Info("log this")
-// The second form is shorter but the first is cheaper if logging is off because it does
-// not evaluate its arguments.
-//
-// Whether an individual call to V generates a log record depends on the setting of
-// the -v and --vmodule flags; both are off by default. If the level in the call to
-// V is at least the value of -v, or of -vmodule for the source file containing the
-// call, the V call will log.
-func V(level Level) Verbose {
- // This function tries hard to be cheap unless there's work to do.
- // The fast path is two atomic loads and compares.
-
- // Here is a cheap but safe test to see if V logging is enabled globally.
- if logging.verbosity.get() >= level {
- return Verbose(true)
- }
-
- // It's off globally but it vmodule may still be set.
- // Here is another cheap but safe test to see if vmodule is enabled.
- if atomic.LoadInt32(&logging.filterLength) > 0 {
- // Now we need a proper lock to use the logging structure. The pcs field
- // is shared so we must lock before accessing it. This is fairly expensive,
- // but if V logging is enabled we're slow anyway.
- logging.mu.Lock()
- defer logging.mu.Unlock()
- if runtime.Callers(2, logging.pcs[:]) == 0 {
- return Verbose(false)
- }
- v, ok := logging.vmap[logging.pcs[0]]
- if !ok {
- v = logging.setV(logging.pcs[0])
- }
- return Verbose(v >= level)
- }
- return Verbose(false)
-}
-
-// Info is equivalent to the global Info function, guarded by the value of v.
-// See the documentation of V for usage.
-func (v Verbose) Info(args ...interface{}) {
- if v {
- logging.print(infoLog, args...)
- }
-}
-
-// Infoln is equivalent to the global Infoln function, guarded by the value of v.
-// See the documentation of V for usage.
-func (v Verbose) Infoln(args ...interface{}) {
- if v {
- logging.println(infoLog, args...)
- }
-}
-
-// Infof is equivalent to the global Infof function, guarded by the value of v.
-// See the documentation of V for usage.
-func (v Verbose) Infof(format string, args ...interface{}) {
- if v {
- logging.printf(infoLog, format, args...)
- }
-}
-
-// Info logs to the INFO log.
-// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
-func Info(args ...interface{}) {
- logging.print(infoLog, args...)
-}
-
-// InfoDepth acts as Info but uses depth to determine which call frame to log.
-// InfoDepth(0, "msg") is the same as Info("msg").
-func InfoDepth(depth int, args ...interface{}) {
- logging.printDepth(infoLog, depth, args...)
-}
-
-// Infoln logs to the INFO log.
-// Arguments are handled in the manner of fmt.Println; a newline is always appended.
-func Infoln(args ...interface{}) {
- logging.println(infoLog, args...)
-}
-
-// Infof logs to the INFO log.
-// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
-func Infof(format string, args ...interface{}) {
- logging.printf(infoLog, format, args...)
-}
-
-// Warning logs to the WARNING and INFO logs.
-// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
-func Warning(args ...interface{}) {
- logging.print(warningLog, args...)
-}
-
-// WarningDepth acts as Warning but uses depth to determine which call frame to log.
-// WarningDepth(0, "msg") is the same as Warning("msg").
-func WarningDepth(depth int, args ...interface{}) {
- logging.printDepth(warningLog, depth, args...)
-}
-
-// Warningln logs to the WARNING and INFO logs.
-// Arguments are handled in the manner of fmt.Println; a newline is always appended.
-func Warningln(args ...interface{}) {
- logging.println(warningLog, args...)
-}
-
-// Warningf logs to the WARNING and INFO logs.
-// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
-func Warningf(format string, args ...interface{}) {
- logging.printf(warningLog, format, args...)
-}
-
-// Error logs to the ERROR, WARNING, and INFO logs.
-// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
-func Error(args ...interface{}) {
- logging.print(errorLog, args...)
-}
-
-// ErrorDepth acts as Error but uses depth to determine which call frame to log.
-// ErrorDepth(0, "msg") is the same as Error("msg").
-func ErrorDepth(depth int, args ...interface{}) {
- logging.printDepth(errorLog, depth, args...)
-}
-
-// Errorln logs to the ERROR, WARNING, and INFO logs.
-// Arguments are handled in the manner of fmt.Println; a newline is always appended.
-func Errorln(args ...interface{}) {
- logging.println(errorLog, args...)
-}
-
-// Errorf logs to the ERROR, WARNING, and INFO logs.
-// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
-func Errorf(format string, args ...interface{}) {
- logging.printf(errorLog, format, args...)
-}
-
-// Fatal logs to the FATAL, ERROR, WARNING, and INFO logs,
-// including a stack trace of all running goroutines, then calls os.Exit(255).
-// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
-func Fatal(args ...interface{}) {
- logging.print(fatalLog, args...)
-}
-
-// FatalDepth acts as Fatal but uses depth to determine which call frame to log.
-// FatalDepth(0, "msg") is the same as Fatal("msg").
-func FatalDepth(depth int, args ...interface{}) {
- logging.printDepth(fatalLog, depth, args...)
-}
-
-// Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs,
-// including a stack trace of all running goroutines, then calls os.Exit(255).
-// Arguments are handled in the manner of fmt.Println; a newline is always appended.
-func Fatalln(args ...interface{}) {
- logging.println(fatalLog, args...)
-}
-
-// Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs,
-// including a stack trace of all running goroutines, then calls os.Exit(255).
-// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
-func Fatalf(format string, args ...interface{}) {
- logging.printf(fatalLog, format, args...)
-}
-
-// fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks.
-// It allows Exit and relatives to use the Fatal logs.
-var fatalNoStacks uint32
-
-// Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
-// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
-func Exit(args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.print(fatalLog, args...)
-}
-
-// ExitDepth acts as Exit but uses depth to determine which call frame to log.
-// ExitDepth(0, "msg") is the same as Exit("msg").
-func ExitDepth(depth int, args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.printDepth(fatalLog, depth, args...)
-}
-
-// Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
-func Exitln(args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.println(fatalLog, args...)
-}
-
-// Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
-// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
-func Exitf(format string, args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.printf(fatalLog, format, args...)
-}
diff --git a/vendor/k8s.io/klog/klog_file.go b/vendor/k8s.io/klog/klog_file.go
deleted file mode 100644
index e4010ad4d..000000000
--- a/vendor/k8s.io/klog/klog_file.go
+++ /dev/null
@@ -1,139 +0,0 @@
-// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/
-//
-// Copyright 2013 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.
-
-// File I/O for logs.
-
-package klog
-
-import (
- "errors"
- "fmt"
- "os"
- "os/user"
- "path/filepath"
- "strings"
- "sync"
- "time"
-)
-
-// MaxSize is the maximum size of a log file in bytes.
-var MaxSize uint64 = 1024 * 1024 * 1800
-
-// logDirs lists the candidate directories for new log files.
-var logDirs []string
-
-func createLogDirs() {
- if logging.logDir != "" {
- logDirs = append(logDirs, logging.logDir)
- }
- logDirs = append(logDirs, os.TempDir())
-}
-
-var (
- pid = os.Getpid()
- program = filepath.Base(os.Args[0])
- host = "unknownhost"
- userName = "unknownuser"
-)
-
-func init() {
- h, err := os.Hostname()
- if err == nil {
- host = shortHostname(h)
- }
-
- current, err := user.Current()
- if err == nil {
- userName = current.Username
- }
-
- // Sanitize userName since it may contain filepath separators on Windows.
- userName = strings.Replace(userName, `\`, "_", -1)
-}
-
-// shortHostname returns its argument, truncating at the first period.
-// For instance, given "www.google.com" it returns "www".
-func shortHostname(hostname string) string {
- if i := strings.Index(hostname, "."); i >= 0 {
- return hostname[:i]
- }
- return hostname
-}
-
-// logName returns a new log file name containing tag, with start time t, and
-// the name for the symlink for tag.
-func logName(tag string, t time.Time) (name, link string) {
- name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d",
- program,
- host,
- userName,
- tag,
- t.Year(),
- t.Month(),
- t.Day(),
- t.Hour(),
- t.Minute(),
- t.Second(),
- pid)
- return name, program + "." + tag
-}
-
-var onceLogDirs sync.Once
-
-// create creates a new log file and returns the file and its filename, which
-// contains tag ("INFO", "FATAL", etc.) and t. If the file is created
-// successfully, create also attempts to update the symlink for that tag, ignoring
-// errors.
-// The startup argument indicates whether this is the initial startup of klog.
-// If startup is true, existing files are opened for appending instead of truncated.
-func create(tag string, t time.Time, startup bool) (f *os.File, filename string, err error) {
- if logging.logFile != "" {
- f, err := openOrCreate(logging.logFile, startup)
- if err == nil {
- return f, logging.logFile, nil
- }
- return nil, "", fmt.Errorf("log: unable to create log: %v", err)
- }
- onceLogDirs.Do(createLogDirs)
- if len(logDirs) == 0 {
- return nil, "", errors.New("log: no log dirs")
- }
- name, link := logName(tag, t)
- var lastErr error
- for _, dir := range logDirs {
- fname := filepath.Join(dir, name)
- f, err := openOrCreate(fname, startup)
- if err == nil {
- symlink := filepath.Join(dir, link)
- os.Remove(symlink) // ignore err
- os.Symlink(name, symlink) // ignore err
- return f, fname, nil
- }
- lastErr = err
- }
- return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr)
-}
-
-// The startup argument indicates whether this is the initial startup of klog.
-// If startup is true, existing files are opened for appending instead of truncated.
-func openOrCreate(name string, startup bool) (*os.File, error) {
- if startup {
- f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
- return f, err
- }
- f, err := os.Create(name)
- return f, err
-}
diff --git a/vendor/k8s.io/utils/LICENSE b/vendor/k8s.io/utils/LICENSE
deleted file mode 100644
index d64569567..000000000
--- a/vendor/k8s.io/utils/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/k8s.io/utils/integer/integer.go b/vendor/k8s.io/utils/integer/integer.go
deleted file mode 100644
index e4e740cad..000000000
--- a/vendor/k8s.io/utils/integer/integer.go
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
-Copyright 2016 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package integer
-
-// IntMax returns the maximum of the params
-func IntMax(a, b int) int {
- if b > a {
- return b
- }
- return a
-}
-
-// IntMin returns the minimum of the params
-func IntMin(a, b int) int {
- if b < a {
- return b
- }
- return a
-}
-
-// Int32Max returns the maximum of the params
-func Int32Max(a, b int32) int32 {
- if b > a {
- return b
- }
- return a
-}
-
-// Int32Min returns the minimum of the params
-func Int32Min(a, b int32) int32 {
- if b < a {
- return b
- }
- return a
-}
-
-// Int64Max returns the maximum of the params
-func Int64Max(a, b int64) int64 {
- if b > a {
- return b
- }
- return a
-}
-
-// Int64Min returns the minimum of the params
-func Int64Min(a, b int64) int64 {
- if b < a {
- return b
- }
- return a
-}
-
-// RoundToInt32 rounds floats into integer numbers.
-func RoundToInt32(a float64) int32 {
- if a < 0 {
- return int32(a - 0.5)
- }
- return int32(a + 0.5)
-}