add prune and remove unused packages

This commit is contained in:
Michelle Au
2019-03-08 14:54:43 -08:00
parent f59b58d164
commit 8c0accad66
17240 changed files with 27 additions and 4750030 deletions

View File

@@ -1,3 +0,0 @@
Sorry, we do not accept changes directly against this repository, unless the
change is to the `README.md` itself. Please see
`CONTRIBUTING.md` for information on where and how to contribute instead.

10
vendor/k8s.io/client-go/.travis.yml generated vendored
View File

@@ -1,10 +0,0 @@
language: go
go_import_path: k8s.io/client-go
go:
- 1.11.1
script:
- if [ "$TRAVIS_BRANCH" != "master" ]; then godep restore; fi
- go build ./...

771
vendor/k8s.io/client-go/CHANGELOG.md generated vendored
View File

@@ -1,771 +0,0 @@
TODO: This document was manually maintained so might be incomplete. The
automation effort is tracked in
https://github.com/kubernetes/test-infra/issues/5843.
Changes in `k8s.io/api` and `k8s.io/apimachinery` are mentioned here
because `k8s.io/client-go` depends on them.
# v9.0.0
**Breaking Changes:**
* client-go now supports additional non-alpha-numeric characters in UserInfo
"extra" data keys. It should be updated in order to properly support extra
data containing "/" characters or other characters disallowed in HTTP headers.
Old clients sending keys which were `%`-escaped by the user will have their
values unescaped by new API servers.
([#65799](https://github.com/kubernetes/kubernetes/pull/65799))
* `apimachinery/pkg/watch.Until` has been moved to
`client-go/tools/watch.UntilWithoutRetry`. While switching please consider
using the new `client-go/tools/watch.UntilWithSync` or `client-go/tools/watch.Until`.
([#66906](https://github.com/kubernetes/kubernetes/pull/66906))
* [k8s.io/apimachinery] `Unstructured` metadata accessors now respect omitempty semantics
i.e. a field having zero value will now be removed from the unstructured metadata map.
([#67635](https://github.com/kubernetes/kubernetes/pull/67635))
* [k8s.io/apimachinery] The `ObjectConvertor` interface is now changed such that
`ConvertFieldLabel` func takes GroupVersionKind as an argument instead of just
version and kind. ([#65780](https://github.com/kubernetes/kubernetes/pull/65780))
* [k8s.io/apimachinery] componentconfig `ClientConnectionConfiguration` is
moved to `k8s.io/apimachinery/pkg/apis/config`.
([#66058](https://github.com/kubernetes/kubernetes/pull/66058))
* [k8s.io/apimachinery] Renamed ` KubeConfigFile` to `Kubeconfig` in
`ClientConnectionConfiguration`.
([#67149](https://github.com/kubernetes/kubernetes/pull/67149))
* [k8s.io/apimachinery] JSON patch no longer supports `int`.
([#63522](https://github.com/kubernetes/kubernetes/pull/63522))
**New Features:**
* Add ability to cancel leader election.
This also proves useful in integration tests where the whole app is started and
stopped in each test. ([#57932](https://github.com/kubernetes/kubernetes/pull/57932))
* An example showing how to use fake clients in tests is added.
([#65291](https://github.com/kubernetes/kubernetes/pull/65291))
* [k8s.io/apimachinery] Create and Update now support `CreateOptions` and `UpdateOptions`.
([#65105](https://github.com/kubernetes/kubernetes/pull/65105))
**Bug fixes and Improvements:**
* Decrease the amount of time it takes to modify kubeconfig
files with large amounts of contexts.
([#67093](https://github.com/kubernetes/kubernetes/pull/67093))
* The leader election client now renews timeout.
([#65094](https://github.com/kubernetes/kubernetes/pull/65094))
* Switched certificate data replacement from `REDACTED` to `DATA+OMITTED`.
([#66023](https://github.com/kubernetes/kubernetes/pull/66023))
* Fix listing in the fake dynamic client.
([#66078](https://github.com/kubernetes/kubernetes/pull/66078))
* Fix discovery so that plural names are no longer ignored if a singular name is not specified.
([#66249](https://github.com/kubernetes/kubernetes/pull/66249))
* Fix kubelet startup failure when using `ExecPlugin` in kubeconfig.
([#66395](https://github.com/kubernetes/kubernetes/pull/66395))
* Fix panic in the fake `SubjectAccessReview` client when object is nil.
([#66837](https://github.com/kubernetes/kubernetes/pull/66837))
* Periodically reload `InClusterConfig` token.
([#67359](https://github.com/kubernetes/kubernetes/pull/67359))
* [k8s.io/apimachinery] Report parsing error in json serializer.
([#63668](https://github.com/kubernetes/kubernetes/pull/63668))
* [k8s.io/apimachinery] The `metav1.ObjectMeta` accessor does not deepcopy
owner references anymore. In general, the accessor interface does not enforce
deepcopy nor does it forbid it (e.g. for `unstructured.Unstructured`).
([#64915](https://github.com/kubernetes/kubernetes/pull/64915))
* [k8s.io/apimachinery] Utility functions `SetTransportDefaults` and `DialerFor`
once again respect custom Dial functions set on transports.
([#65547](https://github.com/kubernetes/kubernetes/pull/65547))
* [k8s.io/apimachinery] Speed-up conversion function invocation by avoiding
`reflect.Call`. Action required: regenerated conversion with conversion-gen.
([#65771](https://github.com/kubernetes/kubernetes/pull/65771))
* [k8s.io/apimachinery] Establish "406 Not Acceptable" response for
unmarshable protobuf serialization error.
([#67041](https://github.com/kubernetes/kubernetes/pull/67041))
* [k8s.io/apimachinery] Immediately close the other side of the connection by
exiting once one side closes when proxying.
([#67288](https://github.com/kubernetes/kubernetes/pull/67288))
## API changes
**Breaking Changes:**
* Volume dynamic provisioning scheduling has been promoted to beta.
ACTION REQUIRED: The DynamicProvisioningScheduling alpha feature gate has been removed.
The VolumeScheduling beta feature gate is still required for this feature.
([#67432](https://github.com/kubernetes/kubernetes/pull/67432))
* The CSI file system type is no longer defaulted to ext4.
All the production drivers listed under https://kubernetes-csi.github.io/docs/Drivers.html
were inspected and should not be impacted after this change.
If you are using a driver not in that list,
please test the drivers on an updated test cluster first.
([#65499](https://github.com/kubernetes/kubernetes/pull/65499))
**New Features:**
* Support annotations for remote admission webhooks.
([#58679](https://github.com/kubernetes/kubernetes/pull/58679))
* Support both directory and block device for local volume
plugin `FileSystem` `VolumeMode`.
([#63011](https://github.com/kubernetes/kubernetes/pull/63011))
* Introduce `autoscaling/v2beta2` and `custom_metrics/v1beta2`,
which implement metric selectors for Object and Pods metrics,
as well as allowing AverageValue targets on Objects, similar to External metrics.
([#64097](https://github.com/kubernetes/kubernetes/pull/64097))
* Add `Lease` API in the `coordination.k8s.io` API group.
([#64246](https://github.com/kubernetes/kubernetes/pull/64246))
* `ProcMount` added to `SecurityContext` and `AllowedProcMounts` added to `PodSecurityPolicy`
to allow paths in the container's `/proc` to not be masked.
([#64283](https://github.com/kubernetes/kubernetes/pull/64283))
* Add the `AuditAnnotations` field to `ImageReviewStatus` to allow the
`ImageReview` backend to return annotations to be added to the created pod.
([#64597](https://github.com/kubernetes/kubernetes/pull/64597))
* SCTP is now supported as additional protocol (alpha) alongside TCP and UDP in
Pod, Service, Endpoint, and NetworkPolicy.
([#64973](https://github.com/kubernetes/kubernetes/pull/64973))
* The `PodShareProcessNamespace` feature to configure PID namespace sharing
within a pod has been promoted to beta.
([#66507](https://github.com/kubernetes/kubernetes/pull/66507))
* Add `TTLSecondsAfterFinished` to `JobSpec` for cleaning up Jobs after they finish.
([#66840](https://github.com/kubernetes/kubernetes/pull/66840))
* Add `DataSource` and `TypedLocalObjectReference` fields to support
restoring a volume from a volume snapshot data source.
([#67087](https://github.com/kubernetes/kubernetes/pull/67087))
* `RuntimeClass` is a new API resource for defining different classes of runtimes
that may be used to run containers in the cluster.
Pods can select a `RunitmeClass` to use via the `RuntimeClassName` field.
This feature is in alpha, and the `RuntimeClass` feature gate must be enabled
in order to use it. ([#67737](https://github.com/kubernetes/kubernetes/pull/67737))
* To address the possibility dry-run requests overwhelming admission webhooks
that rely on side effects and a reconciliation mechanism, a new field is being
added to `admissionregistration.k8s.io/v1beta1.ValidatingWebhookConfiguration`
and `admissionregistration.k8s.io/v1beta1.MutatingWebhookConfiguration` so that
webhooks can explicitly register as having dry-run support.
If a dry-run request is made on a resource that triggers a non dry-run supporting
webhook, the request will be completely rejected, with "400: Bad Request".
Additionally, a new field is being added to the
`admission.k8s.io/v1beta1.AdmissionReview` API object, exposing to webhooks
whether or not the request being reviewed is a dry-run.
([#66936](https://github.com/kubernetes/kubernetes/pull/66936))
**Bug fixes and Improvements:**
* The `DisruptedPods` field in `PodDisruptionBudgetStatus` is now optional.
([#63757](https://github.com/kubernetes/kubernetes/pull/63757))
* `extensions/v1beta1` Deployment's `ProgressDeadlineSeconds` now defaults to `MaxInt32`.
([#66581](https://github.com/kubernetes/kubernetes/pull/66581))
# v8.0.0
**Breaking Changes:**
* `KUBE_API_VERSIONS` has been removed.
* [https://github.com/kubernetes/kubernetes/pull/63165](https://github.com/kubernetes/kubernetes/pull/63165)
* The client-go/discovery `RESTMapper` has been moved to client-go/restmapper.
* [https://github.com/kubernetes/kubernetes/pull/63507](https://github.com/kubernetes/kubernetes/pull/63507)
* `CachedDiscoveryClient` has been moved from kubectl to client-go.
* [https://github.com/kubernetes/kubernetes/pull/63550](https://github.com/kubernetes/kubernetes/pull/63550)
* The `EventRecorder` interface is changed to include an `AnnotatedEventf` method, which can add annotations to an event.
* [https://github.com/kubernetes/kubernetes/pull/64213](https://github.com/kubernetes/kubernetes/pull/64213)
* [k8s.io/apimachinery] The deprecated `RepairMalformedUpdates` flag has been removed.
* [https://github.com/kubernetes/kubernetes/pull/61455](https://github.com/kubernetes/kubernetes/pull/61455)
**New Features:**
* A new easy-to-use dynamic client is added and the old dynamic client is now deprecated.
* [https://github.com/kubernetes/kubernetes/pull/62913](https://github.com/kubernetes/kubernetes/pull/62913)
* client-go and kubectl now detect and report an error on duplicated name for user, cluster and context, while loading the kubeconfig.
* [https://github.com/kubernetes/kubernetes/pull/60464](https://github.com/kubernetes/kubernetes/pull/60464)
* The informer code-generator now allows specifying a custom resync period for certain informer types and uses the default resync period if none is specified.
* [https://github.com/kubernetes/kubernetes/pull/61400](https://github.com/kubernetes/kubernetes/pull/61400)
* Exec authenticator plugin now supports TLS client certificates.
* [https://github.com/kubernetes/kubernetes/pull/61803](https://github.com/kubernetes/kubernetes/pull/61803)
* The discovery client now has a default request timeout of 32 seconds.
* [https://github.com/kubernetes/kubernetes/pull/62733](https://github.com/kubernetes/kubernetes/pull/62733)
* The OpenStack auth config from is now read from the client config. If the client config is not available, it falls back to reading from the environment variables.
* [https://github.com/kubernetes/kubernetes/pull/60200](https://github.com/kubernetes/kubernetes/pull/60200)
* The in-tree support for openstack credentials is now deprecated. Please use the `client-keystone-auth` from the cloud-provider-openstack repository. Details on how to use this new capability is documented [here](https://github.com/kubernetes/cloud-provider-openstack/blob/master/docs/using-client-keystone-auth.md)
* [https://github.com/kubernetes/kubernetes/pull/64346](https://github.com/kubernetes/kubernetes/pull/64346)
**Bug fixes and Improvements:**
* 406 mime-type errors are now tolerated while attempting to load new openapi schema. This improves compatibility with older servers when creating/updating API objects.
* [https://github.com/kubernetes/kubernetes/pull/61949](https://github.com/kubernetes/kubernetes/pull/61949)
* Removes the generated `DeleteCollection()` method for `Services` since the API does not support it.
* [https://github.com/kubernetes/kubernetes/pull/63861](https://github.com/kubernetes/kubernetes/pull/63861)
* Event object references with apiversion now report an apiversion, instead of just the group.
* [https://github.com/kubernetes/kubernetes/pull/63913](https://github.com/kubernetes/kubernetes/pull/63913)
[https://github.com/kubernetes/kubernetes/pull/62462](https://github.com/kubernetes/kubernetes/pull/62462)
* [k8s.io/apimachinery] `runtime.Unstructured.UnstructuredContent()` no longer mutates the source while returning the contents.
* [https://github.com/kubernetes/kubernetes/pull/62063](https://github.com/kubernetes/kubernetes/pull/62063)
* [k8s.io/apimachinery] Incomplete support for `uint64` is now removed. This fixes a panic encountered while using `DeepCopyJSON` with `uint64`.
* [https://github.com/kubernetes/kubernetes/pull/62981](https://github.com/kubernetes/kubernetes/pull/62981)
* [k8s.io/apimachinery] API server can now parse `propagationPolicy` when it sent as a query parameter sent with a delete request.
* [https://github.com/kubernetes/kubernetes/pull/63414](https://github.com/kubernetes/kubernetes/pull/63414)
* [k8s.io/apimachinery] APIServices with kube-like versions (e.g. v1, v2beta1, etc.) will be sorted appropriately within each group.
* [https://github.com/kubernetes/kubernetes/pull/64004](https://github.com/kubernetes/kubernetes/pull/64004)
* [k8s.io/apimachinery] `int64` is the only allowed integer for printers.
* [https://github.com/kubernetes/kubernetes/pull/64639](https://github.com/kubernetes/kubernetes/pull/64639)
## API changes
**Breaking Changes:**
* Support for `alpha.kubernetes.io/nvidia-gpu` resource which was deprecated in 1.10 is removed. Please use the resource exposed by `DevicePlugins` instead (`nvidia.com/gpu`).
* [https://github.com/kubernetes/kubernetes/pull/61498](https://github.com/kubernetes/kubernetes/pull/61498)
* Alpha annotation for `PersistentVolume` node affinity has been removed. Update your `PersistentVolume`s to use the beta `PersistentVolume.nodeAffinity` field before upgrading.
* [https://github.com/kubernetes/kubernetes/pull/61816](https://github.com/kubernetes/kubernetes/pull/61816)
* `ObjectMeta ` `ListOptions` `DeleteOptions` are removed from the core api group. Please use the ones in `meta/v1` instead.
* [https://github.com/kubernetes/kubernetes/pull/61809](https://github.com/kubernetes/kubernetes/pull/61809)
* `ExternalID` in `NodeSpec` is deprecated. The externalID of the node is no longer set in the Node spec.
* [https://github.com/kubernetes/kubernetes/pull/61877](https://github.com/kubernetes/kubernetes/pull/61877)
* PSP-related types in the `extensions/v1beta1` API group are now deprecated. It is suggested to use the `policy/v1beta1` API group instead.
* [https://github.com/kubernetes/kubernetes/pull/61777](https://github.com/kubernetes/kubernetes/pull/61777)
**New Features:**
* `PodSecurityPolicy` now supports restricting hostPath volume mounts to be readOnly and under specific path prefixes.
* [https://github.com/kubernetes/kubernetes/pull/58647](https://github.com/kubernetes/kubernetes/pull/58647)
* `Node.Spec.ConfigSource.ConfigMap.KubeletConfigKey` must be specified when using dynamic Kubelet config to tell the Kubelet which key of the `ConfigMap` identifies its config file.
* [https://github.com/kubernetes/kubernetes/pull/59847](https://github.com/kubernetes/kubernetes/pull/59847)
* `serverAddressByClientCIDRs` in `meta/v1` APIGroup is now optional.
* [https://github.com/kubernetes/kubernetes/pull/61963](https://github.com/kubernetes/kubernetes/pull/61963)
* A new field `MatchFields` is added to `NodeSelectorTerm`. Currently, it only supports `metadata.name`.
* [https://github.com/kubernetes/kubernetes/pull/62002](https://github.com/kubernetes/kubernetes/pull/62002)
* The `PriorityClass` API is promoted to `scheduling.k8s.io/v1beta1`.
* [https://github.com/kubernetes/kubernetes/pull/63100](https://github.com/kubernetes/kubernetes/pull/63100)
* The status of dynamic Kubelet config is now reported via `Node.Status.Config`, rather than the `KubeletConfigOk` node condition.
* [https://github.com/kubernetes/kubernetes/pull/63314](https://github.com/kubernetes/kubernetes/pull/63314)
* The `GitRepo` volume type is deprecated. To provision a container with a git repo, mount an `EmptyDir` into an `InitContainer` that clones the repo using git, then mount the `EmptyDir` into the Pod's container.
* [https://github.com/kubernetes/kubernetes/pull/63445](https://github.com/kubernetes/kubernetes/pull/63445)
* The Sysctls experimental feature has been promoted to beta (enabled by default via the `Sysctls` feature flag). `PodSecurityPolicy` and `Pod` objects now have fields for specifying and controlling sysctls. Alpha sysctl annotations will be ignored by 1.11+ kubelets. All alpha sysctl annotations in existing deployments must be converted to API fields to be effective.
* [https://github.com/kubernetes/kubernetes/pull/63717](https://github.com/kubernetes/kubernetes/pull/63717)
* The annotation `service.alpha.kubernetes.io/tolerate-unready-endpoints` is deprecated. Users should use `Service.spec.publishNotReadyAddresses` instead.
* [https://github.com/kubernetes/kubernetes/pull/63742](https://github.com/kubernetes/kubernetes/pull/63742)
* `VerticalPodAutoscaler` has been added to `autoscaling/v1` API group.
* [https://github.com/kubernetes/kubernetes/pull/63797](https://github.com/kubernetes/kubernetes/pull/63797)
* Alpha support is added for dynamic volume limits based on node type.
* [https://github.com/kubernetes/kubernetes/pull/64154](https://github.com/kubernetes/kubernetes/pull/64154)
* `ContainersReady` condition is added to the Pod status.
* [https://github.com/kubernetes/kubernetes/pull/64646](https://github.com/kubernetes/kubernetes/pull/64646)
**Bug fixes and Improvements:**
* Default mount propagation has changed from `HostToContainer` (`rslave` in Linux terminology) to `None` (`private`) to match the behavior in 1.9 and earlier releases. `HostToContainer` as a default caused regressions in some pods.
* [https://github.com/kubernetes/kubernetes/pull/62462](https://github.com/kubernetes/kubernetes/pull/62462)
# v7.0.0
**Breaking Changes:**
* Google Cloud Service Account email addresses can now be used in RBAC Role bindings since the default scopes now include the `userinfo.email` scope. This is a breaking change if the numeric uniqueIDs of the Google service accounts were being used in RBAC role bindings. The behavior can be overridden by explicitly specifying the scope values as comma-separated string in the `users[*].config.scopes` field in the `KUBECONFIG` file.
* [https://github.com/kubernetes/kubernetes/pull/58141](https://github.com/kubernetes/kubernetes/pull/58141)
* [k8s.io/api] The `ConfigOK` node condition has been renamed to `KubeletConfigOk`.
* [https://github.com/kubernetes/kubernetes/pull/59905](https://github.com/kubernetes/kubernetes/pull/59905)
**New Features:**
* Subresource support is added to the dynamic client.
* [https://github.com/kubernetes/kubernetes/pull/56717](https://github.com/kubernetes/kubernetes/pull/56717)
* A watch method is added to the Fake Client.
* [https://github.com/kubernetes/kubernetes/pull/57504](https://github.com/kubernetes/kubernetes/pull/57504)
* `ListOptions` can be modified when creating a `ListWatch`.
* [https://github.com/kubernetes/kubernetes/pull/57508](https://github.com/kubernetes/kubernetes/pull/57508)
* A `/token` subresource for ServiceAccount is added.
* [https://github.com/kubernetes/kubernetes/pull/58111](https://github.com/kubernetes/kubernetes/pull/58111)
* If an informer delivery fails, the particular notification is skipped and continued the next time.
* [https://github.com/kubernetes/kubernetes/pull/58394](https://github.com/kubernetes/kubernetes/pull/58394)
* Certificate manager will no longer wait until the initial rotation succeeds or fails before returning from `Start()`.
* [https://github.com/kubernetes/kubernetes/pull/58930](https://github.com/kubernetes/kubernetes/pull/58930)
* [k8s.io/api] `VolumeScheduling` and `LocalPersistentVolume` features are beta and enabled by default. The PersistentVolume NodeAffinity alpha annotation is deprecated and will be removed in a future release.
* [https://github.com/kubernetes/kubernetes/pull/59391](https://github.com/kubernetes/kubernetes/pull/59391)
* [k8s.io/api] The `PodSecurityPolicy` API has been moved to the `policy/v1beta1` API group. The `PodSecurityPolicy` API in the `extensions/v1beta1` API group is deprecated and will be removed in a future release.
* [https://github.com/kubernetes/kubernetes/pull/54933](https://github.com/kubernetes/kubernetes/pull/54933)
* [k8s.io/api] ConfigMap objects now support binary data via a new `binaryData` field.
* [https://github.com/kubernetes/kubernetes/pull/57938](https://github.com/kubernetes/kubernetes/pull/57938)
* [k8s.io/api] Service account TokenRequest API is added.
* [https://github.com/kubernetes/kubernetes/pull/58027](https://github.com/kubernetes/kubernetes/pull/58027)
* [k8s.io/api] FSType is added in CSI volume source to specify filesystems.
* [https://github.com/kubernetes/kubernetes/pull/58209](https://github.com/kubernetes/kubernetes/pull/58209)
* [k8s.io/api] v1beta1 VolumeAttachment API is added.
* [https://github.com/kubernetes/kubernetes/pull/58462](https://github.com/kubernetes/kubernetes/pull/58462)
* [k8s.io/api] `v1.Pod` now has a field `ShareProcessNamespace` to configure whether a single process namespace should be shared between all containers in a pod. This feature is in alpha preview.
* [https://github.com/kubernetes/kubernetes/pull/58716](https://github.com/kubernetes/kubernetes/pull/58716)
* [k8s.io/api] Add `NominatedNodeName` field to `PodStatus`. This field is set when a pod preempts other pods on the node.
* [https://github.com/kubernetes/kubernetes/pull/58990](https://github.com/kubernetes/kubernetes/pull/58990)
* [k8s.io/api] Promote `CSIPersistentVolumeSourc`e to beta.
* [https://github.com/kubernetes/kubernetes/pull/59157](https://github.com/kubernetes/kubernetes/pull/59157)
* [k8s.io/api] Promote `DNSPolicy` and `DNSConfig` in `PodSpec` to beta.
* [https://github.com/kubernetes/kubernetes/pull/59771](https://github.com/kubernetes/kubernetes/pull/59771)
* [k8s.io/api] External metric types are added to the HPA API.
* [https://github.com/kubernetes/kubernetes/pull/60096](https://github.com/kubernetes/kubernetes/pull/60096)
* [k8s.io/apimachinery] The `meta.k8s.io/v1alpha1` objects for retrieving tabular responses from the server (`Table`) or fetching just the `ObjectMeta` for an object (as `PartialObjectMetadata`) are now beta as part of `meta.k8s.io/v1beta1`. Clients may request alternate representations of normal Kubernetes objects by passing an `Accept` header like `application/json;as=Table;g=meta.k8s.io;v=v1beta1` or `application/json;as=PartialObjectMetadata;g=meta.k8s.io;v1=v1beta1`. Older servers will ignore this representation or return an error if it is not available. Clients may request fallback to the normal object by adding a non-qualified mime-type to their `Accept` header like `application/json` - the server will then respond with either the alternate representation if it is supported or the fallback mime-type which is the normal object response.
* [https://github.com/kubernetes/kubernetes/pull/59059](https://github.com/kubernetes/kubernetes/pull/59059)
**Bug fixes and Improvements:**
* Port-forwarding of TCP6 ports is fixed.
* [https://github.com/kubernetes/kubernetes/pull/57457](https://github.com/kubernetes/kubernetes/pull/57457)
* A race condition in SharedInformer that could violate the sequential delivery guarantee and cause panics on shutdown is fixed.
* [https://github.com/kubernetes/kubernetes/pull/59828](https://github.com/kubernetes/kubernetes/pull/59828)
* [k8s.io/api] PersistentVolume flexVolume sources can now reference secrets in a namespace other than the PersistentVolumeClaim's namespace.
* [https://github.com/kubernetes/kubernetes/pull/56460](https://github.com/kubernetes/kubernetes/pull/56460)
* [k8s.io/apimachinery] YAMLDecoder Read can now return the number of bytes read.
* [https://github.com/kubernetes/kubernetes/pull/57000](https://github.com/kubernetes/kubernetes/pull/57000)
* [k8s.io/apimachinery] YAMLDecoder Read now tracks rest of buffer on `io.ErrShortBuffer`.
* [https://github.com/kubernetes/kubernetes/pull/58817](https://github.com/kubernetes/kubernetes/pull/58817)
* [k8s.io/apimachinery] Prompt required merge key in the error message while applying a strategic merge patch.
* [https://github.com/kubernetes/kubernetes/pull/57854](https://github.com/kubernetes/kubernetes/pull/57854)
# v6.0.0
**Breaking Changes:**
* If you upgrade your client-go libs and use the `AppsV1() or Apps()` interface, please note that the default garbage collection behavior is changed.
* [https://github.com/kubernetes/kubernetes/pull/55148](https://github.com/kubernetes/kubernetes/pull/55148)
* Swagger 1.2 retriever `DiscoveryClient.SwaggerSchema` was removed from the discovery client
* [https://github.com/kubernetes/kubernetes/pull/53441](https://github.com/kubernetes/kubernetes/pull/53441)
* Informers got a NewFilteredSharedInformerFactory to e.g. filter by namespace
* [https://github.com/kubernetes/kubernetes/pull/54660](https://github.com/kubernetes/kubernetes/pull/54660)
* [k8s.io/api] The dynamic admission webhook is split into two kinds, mutating and validating.
The kinds have changed completely and old code must be ported to `admissionregistration.k8s.io/v1beta1` -
`MutatingWebhookConfiguration` and `ValidatingWebhookConfiguration`
* [https://github.com/kubernetes/kubernetes/pull/55282](https://github.com/kubernetes/kubernetes/pull/55282)
* [k8s.io/api] Renamed `core/v1.ScaleIOVolumeSource` to `ScaleIOPersistentVolumeSource`
* [https://github.com/kubernetes/kubernetes/pull/54013](https://github.com/kubernetes/kubernetes/pull/54013)
* [k8s.io/api] Renamed `core/v1.RBDVolumeSource` to `RBDPersistentVolumeSource`
* [https://github.com/kubernetes/kubernetes/pull/54302](https://github.com/kubernetes/kubernetes/pull/54302)
* [k8s.io/api] Removed `core/v1.CreatedByAnnotation`
* [https://github.com/kubernetes/kubernetes/pull/54445](https://github.com/kubernetes/kubernetes/pull/54445)
* [k8s.io/api] Renamed `core/v1.StorageMediumHugepages` to `StorageMediumHugePages`
* [https://github.com/kubernetes/kubernetes/pull/54748](https://github.com/kubernetes/kubernetes/pull/54748)
* [k8s.io/api] `core/v1.Taint.TimeAdded` became a pointer
* [https://github.com/kubernetes/kubernetes/pull/43016](https://github.com/kubernetes/kubernetes/pull/43016)
* [k8s.io/api] `core/v1.DefaultHardPodAffinitySymmetricWeight` type changed from int to int32
* [https://github.com/kubernetes/kubernetes/pull/53850](https://github.com/kubernetes/kubernetes/pull/53850)
* [k8s.io/apimachinery] `ObjectCopier` interface was removed (requires switch to new generators with DeepCopy methods)
* [https://github.com/kubernetes/kubernetes/pull/53525](https://github.com/kubernetes/kubernetes/pull/53525)
**New Features:**
* Certificate manager was moved from kubelet to `k8s.io/client-go/util/certificates`
* [https://github.com/kubernetes/kubernetes/pull/49654](https://github.com/kubernetes/kubernetes/pull/49654)
* [k8s.io/api] Workloads api types are promoted to `apps/v1` version
* [https://github.com/kubernetes/kubernetes/pull/53679](https://github.com/kubernetes/kubernetes/pull/53679)
* [k8s.io/api] Added `storage.k8s.io/v1alpha1` API group
* [https://github.com/kubernetes/kubernetes/pull/54463](https://github.com/kubernetes/kubernetes/pull/54463)
* [k8s.io/api] Added support for conditions in StatefulSet status
* [https://github.com/kubernetes/kubernetes/pull/55268](https://github.com/kubernetes/kubernetes/pull/55268)
* [k8s.io/api] Added support for conditions in DaemonSet status
* [https://github.com/kubernetes/kubernetes/pull/55272](https://github.com/kubernetes/kubernetes/pull/55272)
* [k8s.io/apimachinery] Added polymorphic scale client in `k8s.io/client-go/scale`, which supports scaling of resources in arbitrary API groups
* [https://github.com/kubernetes/kubernetes/pull/53743](https://github.com/kubernetes/kubernetes/pull/53743)
* [k8s.io/apimachinery] `meta.MetadataAccessor` got API chunking support
* [https://github.com/kubernetes/kubernetes/pull/53768](https://github.com/kubernetes/kubernetes/pull/53768)
* [k8s.io/apimachinery] `unstructured.Unstructured` got getters and setters
* [https://github.com/kubernetes/kubernetes/pull/51940](https://github.com/kubernetes/kubernetes/pull/51940)
**Bug fixes and Improvements:**
* The body in glog output is not truncated with log level 10
* [https://github.com/kubernetes/kubernetes/pull/54801](https://github.com/kubernetes/kubernetes/pull/54801)
* [k8s.io/api] Unset `creationTimestamp` field is output as null if encoded from an unstructured object
* [https://github.com/kubernetes/kubernetes/pull/53464](https://github.com/kubernetes/kubernetes/pull/53464)
* [k8s.io/apimachinery] Redirect behavior is restored for proxy subresources
* [https://github.com/kubernetes/kubernetes/pull/52933](https://github.com/kubernetes/kubernetes/pull/52933)
* [k8s.io/apimachinery] Random string generation functions are optimized
* [https://github.com/kubernetes/kubernetes/pull/53720](https://github.com/kubernetes/kubernetes/pull/53720)
# v5.0.1
Bug fix: picked up a security fix [kubernetes/kubernetes#53443](https://github.com/kubernetes/kubernetes/pull/53443) for `PodSecurityPolicy`.
# v5.0.0
**New features:**
* Added paging support
* [https://github.com/kubernetes/kubernetes/pull/51876](https://github.com/kubernetes/kubernetes/pull/51876)
* Added support for client-side spam filtering of events
* [https://github.com/kubernetes/kubernetes/pull/47367](https://github.com/kubernetes/kubernetes/pull/47367)
* Added support for http etag and caching
* [https://github.com/kubernetes/kubernetes/pull/50404](https://github.com/kubernetes/kubernetes/pull/50404)
* Added priority queue support to informer cache
* [https://github.com/kubernetes/kubernetes/pull/49752](https://github.com/kubernetes/kubernetes/pull/49752)
* Added openstack auth provider
* [https://github.com/kubernetes/kubernetes/pull/39587](https://github.com/kubernetes/kubernetes/pull/39587)
* Added metrics for checking reflector health
* [https://github.com/kubernetes/kubernetes/pull/48224](https://github.com/kubernetes/kubernetes/pull/48224)
* Client-go now includes the leaderelection package
* [https://github.com/kubernetes/kubernetes/pull/39173](https://github.com/kubernetes/kubernetes/pull/39173)
**API changes:**
* Promoted Autoscaling v2alpha1 to v2beta1
* [https://github.com/kubernetes/kubernetes/pull/50708](https://github.com/kubernetes/kubernetes/pull/50708)
* Promoted CronJobs to batch/v1beta1
* [https://github.com/kubernetes/kubernetes/pull/41901](https://github.com/kubernetes/kubernetes/pull/41901)
* Promoted rbac.authorization.k8s.io/v1beta1 to rbac.authorization.k8s.io/v1
* [https://github.com/kubernetes/kubernetes/pull/49642](https://github.com/kubernetes/kubernetes/pull/49642)
* Added a new API version apps/v1beta2
* [https://github.com/kubernetes/kubernetes/pull/48746](https://github.com/kubernetes/kubernetes/pull/48746)
* Added a new API version scheduling/v1alpha1
* [https://github.com/kubernetes/kubernetes/pull/48377](https://github.com/kubernetes/kubernetes/pull/48377)
**Breaking changes:**
* Moved pkg/api and pkg/apis to [k8s.io/api](https://github.com/kubernetes/api). Other kubernetes repositories also import types from there, so they are composable with client-go.
* Removed helper functions in pkg/api and pkg/apis. They are planned to be exported in other repos. The issue is tracked [here](https://github.com/kubernetes/kubernetes/issues/48209#issuecomment-314537745). During the transition, you'll have to copy the helper functions to your projects.
* The discovery client now fetches the protobuf encoded OpenAPI schema and returns `openapi_v2.Document`
* [https://github.com/kubernetes/kubernetes/pull/46803](https://github.com/kubernetes/kubernetes/pull/46803)
* Enforced explicit references to API group client interfaces in clientsets to avoid ambiguity.
* [https://github.com/kubernetes/kubernetes/pull/49370](https://github.com/kubernetes/kubernetes/pull/49370)
* The generic RESTClient type (`k8s.io/client-go/rest`) no longer exposes `LabelSelectorParam` or `FieldSelectorParam` methods - use `VersionedParams` with `metav1.ListOptions` instead. The `UintParam` method has been removed. The `timeout` parameter will no longer cause an error when using `Param()`.
* [https://github.com/kubernetes/kubernetes/pull/48991](https://github.com/kubernetes/kubernetes/pull/48991)
# v4.0.0
No significant changes since v4.0.0-beta.0.
# v4.0.0-beta.0
**New features:**
* Added OpenAPISchema support in the discovery client
* [https://github.com/kubernetes/kubernetes/pull/44531](https://github.com/kubernetes/kubernetes/pull/44531)
* Added mutation cache filter: MutationCache is able to take the result of update operations and stores them in an LRU that can be used to provide a more current view of a requested object.
* [https://github.com/kubernetes/kubernetes/pull/45838](https://github.com/kubernetes/kubernetes/pull/45838/commits/f88c7725b4f9446c652d160bdcfab7c6201bddea)
* Moved the remotecommand package (used by `kubectl exec/attach`) to client-go
* [https://github.com/kubernetes/kubernetes/pull/41331](https://github.com/kubernetes/kubernetes/pull/41331)
* Added support for following redirects to the SpdyRoundTripper
* [https://github.com/kubernetes/kubernetes/pull/44451](https://github.com/kubernetes/kubernetes/pull/44451)
* Added Azure Active Directory plugin
* [https://github.com/kubernetes/kubernetes/pull/43987](https://github.com/kubernetes/kubernetes/pull/43987)
**Usability improvements:**
* Added several new examples and reorganized client-go/examples
* [Related PRs](https://github.com/kubernetes/kubernetes/commits/release-1.7/staging/src/k8s.io/client-go/examples)
**API changes:**
* Added networking.k8s.io/v1 API
* [https://github.com/kubernetes/kubernetes/pull/39164](https://github.com/kubernetes/kubernetes/pull/39164)
* ControllerRevision type added for StatefulSet and DaemonSet history.
* [https://github.com/kubernetes/kubernetes/pull/45867](https://github.com/kubernetes/kubernetes/pull/45867)
* Added support for initializers
* [https://github.com/kubernetes/kubernetes/pull/38058](https://github.com/kubernetes/kubernetes/pull/38058)
* Added admissionregistration.k8s.io/v1alpha1 API
* [https://github.com/kubernetes/kubernetes/pull/46294](https://github.com/kubernetes/kubernetes/pull/46294)
**Breaking changes:**
* Moved client-go/util/clock to apimachinery/pkg/util/clock
* [https://github.com/kubernetes/kubernetes/pull/45933](https://github.com/kubernetes/kubernetes/pull/45933/commits/8013212db54e95050c622675c6706cce5de42b45)
* Some [API helpers](https://github.com/kubernetes/client-go/blob/release-3.0/pkg/api/helpers.go) were removed.
* Dynamic client takes GetOptions as an input parameter
* [https://github.com/kubernetes/kubernetes/pull/47251](https://github.com/kubernetes/kubernetes/pull/47251)
**Bug fixes:**
* PortForwarder: don't log an error if net.Listen fails. [https://github.com/kubernetes/kubernetes/pull/44636](https://github.com/kubernetes/kubernetes/pull/44636)
* oidc auth plugin not to override the Auth header if it's already exits. [https://github.com/kubernetes/kubernetes/pull/45529](https://github.com/kubernetes/kubernetes/pull/45529)
* The --namespace flag is now honored for in-cluster clients that have an empty configuration. [https://github.com/kubernetes/kubernetes/pull/46299](https://github.com/kubernetes/kubernetes/pull/46299)
* GCP auth plugin no longer overwrites existing Authorization headers. [https://github.com/kubernetes/kubernetes/pull/45575](https://github.com/kubernetes/kubernetes/pull/45575)
# v3.0.0
Bug fixes:
* Use OS-specific libs when computing client User-Agent in kubectl, etc. (https://github.com/kubernetes/kubernetes/pull/44423)
* kubectl commands run inside a pod using a kubeconfig file now use the namespace specified in the kubeconfig file, instead of using the pod namespace. If no kubeconfig file is used, or the kubeconfig does not specify a namespace, the pod namespace is still used as a fallback. (https://github.com/kubernetes/kubernetes/pull/44570)
* Restored the ability of kubectl running inside a pod to consume resource files specifying a different namespace than the one the pod is running in. (https://github.com/kubernetes/kubernetes/pull/44862)
# v3.0.0-beta.0
* Added dependency on k8s.io/apimachinery. The impacts include changing import path of API objects like `ListOptions` from `k8s.io/client-go/pkg/api/v1` to `k8s.io/apimachinery/pkg/apis/meta/v1`.
* Added generated listers (listers/) and informers (informers/)
* Kubernetes API changes:
* Added client support for:
* authentication/v1
* authorization/v1
* autoscaling/v2alpha1
* rbac/v1beta1
* settings/v1alpha1
* storage/v1
* Changed client support for:
* certificates from v1alpha1 to v1beta1
* policy from v1alpha1 to v1beta1
* Deleted client support for:
* extensions/v1beta1#Job
* CHANGED: pass typed options to dynamic client (https://github.com/kubernetes/kubernetes/pull/41887)
# v2.0.0
* Included bug fixes in k8s.io/kuberentes release-1.5 branch, up to commit
bde8578d9675129b7a2aa08f1b825ec6cc0f3420
# v2.0.0-alpha.1
* Removed top-level version folder (e.g., 1.4 and 1.5), switching to maintaining separate versions
in separate branches.
* Clientset supported multiple versions per API group
* Added ThirdPartyResources example
* Kubernetes API changes
* Apps API group graduated to v1beta1
* Policy API group graduated to v1beta1
* Added support for batch/v2alpha1/cronjob
* Renamed PetSet to StatefulSet
# v1.5.0
* Included the auth plugin (https://github.com/kubernetes/kubernetes/pull/33334)
* Added timeout field to RESTClient config (https://github.com/kubernetes/kubernetes/pull/33958)

View File

@@ -1,9 +0,0 @@
# Contributing guidelines
Do not open pull requests directly against this repository. They will be ignored. Instead, please open pull requests against [kubernetes/kubernetes](https://git.k8s.io/kubernetes/).
The exception is changes to the `README.md` itself.
Please follow the same [contributing guide](https://git.k8s.io/kubernetes/CONTRIBUTING.md) you would follow for any other pull request made to kubernetes/kubernetes.
This repository is published from [kubernetes/kubernetes/staging/src/k8s.io/client-go](https://git.k8s.io/kubernetes/staging/src/k8s.io/client-go) by the [kubernetes publishing-bot](https://git.k8s.io/publishing-bot).
Please see [Staging Directory and Publishing](https://git.k8s.io/community/contributors/devel/staging.md) for more information

View File

@@ -1,622 +0,0 @@
{
"ImportPath": "k8s.io/client-go",
"GoVersion": "go1.11",
"GodepVersion": "v80",
"Packages": [
"./..."
],
"Deps": [
{
"ImportPath": "cloud.google.com/go/compute/metadata",
"Rev": "3b1ae45394a234c385be014e9a488f2bb6eef821"
},
{
"ImportPath": "cloud.google.com/go/internal",
"Rev": "3b1ae45394a234c385be014e9a488f2bb6eef821"
},
{
"ImportPath": "github.com/Azure/go-autorest/autorest",
"Rev": "ea233b6412b0421a65dc6160e16c893364664a95"
},
{
"ImportPath": "github.com/Azure/go-autorest/autorest/adal",
"Rev": "ea233b6412b0421a65dc6160e16c893364664a95"
},
{
"ImportPath": "github.com/Azure/go-autorest/autorest/azure",
"Rev": "ea233b6412b0421a65dc6160e16c893364664a95"
},
{
"ImportPath": "github.com/Azure/go-autorest/autorest/date",
"Rev": "ea233b6412b0421a65dc6160e16c893364664a95"
},
{
"ImportPath": "github.com/Azure/go-autorest/logger",
"Rev": "ea233b6412b0421a65dc6160e16c893364664a95"
},
{
"ImportPath": "github.com/Azure/go-autorest/version",
"Rev": "ea233b6412b0421a65dc6160e16c893364664a95"
},
{
"ImportPath": "github.com/davecgh/go-spew/spew",
"Rev": "782f4967f2dc4564575ca782fe2d04090b5faca8"
},
{
"ImportPath": "github.com/dgrijalva/jwt-go",
"Rev": "01aeca54ebda6e0fbfafd0a524d234159c05ec20"
},
{
"ImportPath": "github.com/docker/spdystream",
"Rev": "449fdfce4d962303d702fec724ef0ad181c92528"
},
{
"ImportPath": "github.com/docker/spdystream/spdy",
"Rev": "449fdfce4d962303d702fec724ef0ad181c92528"
},
{
"ImportPath": "github.com/evanphx/json-patch",
"Rev": "36442dbdb585210f8d5a1b45e67aa323c197d5c4"
},
{
"ImportPath": "github.com/gogo/protobuf/proto",
"Rev": "342cbe0a04158f6dcb03ca0079991a51a4248c02"
},
{
"ImportPath": "github.com/gogo/protobuf/sortkeys",
"Rev": "342cbe0a04158f6dcb03ca0079991a51a4248c02"
},
{
"ImportPath": "github.com/golang/groupcache/lru",
"Rev": "02826c3e79038b59d737d3b1c0a1d937f71a4433"
},
{
"ImportPath": "github.com/golang/protobuf/proto",
"Rev": "b4deda0973fb4c70b50d226b1af49f3da59f5265"
},
{
"ImportPath": "github.com/golang/protobuf/ptypes",
"Rev": "b4deda0973fb4c70b50d226b1af49f3da59f5265"
},
{
"ImportPath": "github.com/golang/protobuf/ptypes/any",
"Rev": "b4deda0973fb4c70b50d226b1af49f3da59f5265"
},
{
"ImportPath": "github.com/golang/protobuf/ptypes/duration",
"Rev": "b4deda0973fb4c70b50d226b1af49f3da59f5265"
},
{
"ImportPath": "github.com/golang/protobuf/ptypes/timestamp",
"Rev": "b4deda0973fb4c70b50d226b1af49f3da59f5265"
},
{
"ImportPath": "github.com/google/btree",
"Rev": "7d79101e329e5a3adf994758c578dab82b90c017"
},
{
"ImportPath": "github.com/google/gofuzz",
"Rev": "44d81051d367757e1c7c6a5a86423ece9afcf63c"
},
{
"ImportPath": "github.com/googleapis/gnostic/OpenAPIv2",
"Rev": "0c5108395e2debce0d731cf0287ddf7242066aba"
},
{
"ImportPath": "github.com/googleapis/gnostic/compiler",
"Rev": "0c5108395e2debce0d731cf0287ddf7242066aba"
},
{
"ImportPath": "github.com/googleapis/gnostic/extensions",
"Rev": "0c5108395e2debce0d731cf0287ddf7242066aba"
},
{
"ImportPath": "github.com/gophercloud/gophercloud",
"Rev": "781450b3c4fcb4f5182bcc5133adb4b2e4a09d1d"
},
{
"ImportPath": "github.com/gophercloud/gophercloud/openstack",
"Rev": "781450b3c4fcb4f5182bcc5133adb4b2e4a09d1d"
},
{
"ImportPath": "github.com/gophercloud/gophercloud/openstack/identity/v2/tenants",
"Rev": "781450b3c4fcb4f5182bcc5133adb4b2e4a09d1d"
},
{
"ImportPath": "github.com/gophercloud/gophercloud/openstack/identity/v2/tokens",
"Rev": "781450b3c4fcb4f5182bcc5133adb4b2e4a09d1d"
},
{
"ImportPath": "github.com/gophercloud/gophercloud/openstack/identity/v3/tokens",
"Rev": "781450b3c4fcb4f5182bcc5133adb4b2e4a09d1d"
},
{
"ImportPath": "github.com/gophercloud/gophercloud/openstack/utils",
"Rev": "781450b3c4fcb4f5182bcc5133adb4b2e4a09d1d"
},
{
"ImportPath": "github.com/gophercloud/gophercloud/pagination",
"Rev": "781450b3c4fcb4f5182bcc5133adb4b2e4a09d1d"
},
{
"ImportPath": "github.com/gregjones/httpcache",
"Rev": "787624de3eb7bd915c329cba748687a3b22666a6"
},
{
"ImportPath": "github.com/gregjones/httpcache/diskcache",
"Rev": "787624de3eb7bd915c329cba748687a3b22666a6"
},
{
"ImportPath": "github.com/hashicorp/golang-lru",
"Rev": "a0d98a5f288019575c6d1f4bb1573fef2d1fcdc4"
},
{
"ImportPath": "github.com/hashicorp/golang-lru/simplelru",
"Rev": "a0d98a5f288019575c6d1f4bb1573fef2d1fcdc4"
},
{
"ImportPath": "github.com/imdario/mergo",
"Rev": "9316a62528ac99aaecb4e47eadd6dc8aa6533d58"
},
{
"ImportPath": "github.com/json-iterator/go",
"Rev": "f2b4162afba35581b6d4a50d3b8f34e33c144682"
},
{
"ImportPath": "github.com/modern-go/concurrent",
"Rev": "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94"
},
{
"ImportPath": "github.com/modern-go/reflect2",
"Rev": "94122c33edd36123c84d5368cfb2b69df93a0ec8"
},
{
"ImportPath": "github.com/peterbourgon/diskv",
"Rev": "5f041e8faa004a95c88a202771f4cc3e991971e6"
},
{
"ImportPath": "github.com/pmezard/go-difflib/difflib",
"Rev": "d8ed2627bdf02c080bf22230dbb337003b7aba2d"
},
{
"ImportPath": "github.com/spf13/pflag",
"Rev": "583c0c0531f06d5278b7d917446061adc344b5cd"
},
{
"ImportPath": "github.com/stretchr/testify/assert",
"Rev": "c679ae2cc0cb27ec3293fea7e254e47386f05d69"
},
{
"ImportPath": "golang.org/x/crypto/ssh/terminal",
"Rev": "de0752318171da717af4ce24d0a2e8626afaeb11"
},
{
"ImportPath": "golang.org/x/net/context",
"Rev": "0ed95abb35c445290478a5348a7b38bb154135fd"
},
{
"ImportPath": "golang.org/x/net/context/ctxhttp",
"Rev": "0ed95abb35c445290478a5348a7b38bb154135fd"
},
{
"ImportPath": "golang.org/x/net/http2",
"Rev": "0ed95abb35c445290478a5348a7b38bb154135fd"
},
{
"ImportPath": "golang.org/x/net/http2/hpack",
"Rev": "0ed95abb35c445290478a5348a7b38bb154135fd"
},
{
"ImportPath": "golang.org/x/net/idna",
"Rev": "0ed95abb35c445290478a5348a7b38bb154135fd"
},
{
"ImportPath": "golang.org/x/net/lex/httplex",
"Rev": "0ed95abb35c445290478a5348a7b38bb154135fd"
},
{
"ImportPath": "golang.org/x/oauth2",
"Rev": "a6bd8cefa1811bd24b86f8902872e4e8225f74c4"
},
{
"ImportPath": "golang.org/x/oauth2/google",
"Rev": "a6bd8cefa1811bd24b86f8902872e4e8225f74c4"
},
{
"ImportPath": "golang.org/x/oauth2/internal",
"Rev": "a6bd8cefa1811bd24b86f8902872e4e8225f74c4"
},
{
"ImportPath": "golang.org/x/oauth2/jws",
"Rev": "a6bd8cefa1811bd24b86f8902872e4e8225f74c4"
},
{
"ImportPath": "golang.org/x/oauth2/jwt",
"Rev": "a6bd8cefa1811bd24b86f8902872e4e8225f74c4"
},
{
"ImportPath": "golang.org/x/sys/unix",
"Rev": "95c6576299259db960f6c5b9b69ea52422860fce"
},
{
"ImportPath": "golang.org/x/sys/windows",
"Rev": "95c6576299259db960f6c5b9b69ea52422860fce"
},
{
"ImportPath": "golang.org/x/text/secure/bidirule",
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
},
{
"ImportPath": "golang.org/x/text/transform",
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
},
{
"ImportPath": "golang.org/x/text/unicode/bidi",
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
},
{
"ImportPath": "golang.org/x/text/unicode/norm",
"Rev": "b19bf474d317b857955b12035d2c5acb57ce8b01"
},
{
"ImportPath": "golang.org/x/time/rate",
"Rev": "f51c12702a4d776e4c1fa9b0fabab841babae631"
},
{
"ImportPath": "gopkg.in/inf.v0",
"Rev": "3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4"
},
{
"ImportPath": "gopkg.in/yaml.v2",
"Rev": "5420a8b6744d3b0345ab293f6fcba19c978f1183"
},
{
"ImportPath": "k8s.io/api/admissionregistration/v1alpha1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/admissionregistration/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/apps/v1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/apps/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/apps/v1beta2",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/auditregistration/v1alpha1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/authentication/v1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/authentication/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/authorization/v1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/authorization/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/autoscaling/v1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/autoscaling/v2beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/autoscaling/v2beta2",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/batch/v1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/batch/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/batch/v2alpha1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/certificates/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/coordination/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/core/v1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/events/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/extensions/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/imagepolicy/v1alpha1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/networking/v1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/policy/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/rbac/v1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/rbac/v1alpha1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/rbac/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/scheduling/v1alpha1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/scheduling/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/settings/v1alpha1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/storage/v1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/storage/v1alpha1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/api/storage/v1beta1",
"Rev": "d01564359763a39d310efc27866b63d4f5c92f1d"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/api/apitesting",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/api/apitesting/fuzzer",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/api/apitesting/roundtrip",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/api/equality",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/api/errors",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/api/meta",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/api/resource",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/apis/meta/fuzzer",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/apis/meta/internalversion",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/apis/meta/v1",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/apis/meta/v1beta1",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/conversion",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/conversion/queryparams",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/fields",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/labels",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/runtime",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/runtime/schema",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/runtime/serializer",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/runtime/serializer/json",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/runtime/serializer/protobuf",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/runtime/serializer/recognizer",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/runtime/serializer/streaming",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/runtime/serializer/versioning",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/selection",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/types",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/cache",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/clock",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/diff",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/errors",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/framer",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/httpstream",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/httpstream/spdy",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/intstr",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/json",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/mergepatch",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/naming",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/net",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/remotecommand",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/runtime",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/sets",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/strategicpatch",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/validation",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/validation/field",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/wait",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/util/yaml",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/version",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/pkg/watch",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/third_party/forked/golang/json",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/third_party/forked/golang/netutil",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/apimachinery/third_party/forked/golang/reflect",
"Rev": "0028e7a3cc82b29fea214c5793c77c24a23bb3ef"
},
{
"ImportPath": "k8s.io/klog",
"Rev": "8139d8cb77af419532b33dfa7dd09fbc5f1d344f"
},
{
"ImportPath": "k8s.io/kube-openapi/pkg/util/proto",
"Rev": "c59034cc13d587f5ef4e85ca0ade0c1866ae8e1d"
},
{
"ImportPath": "sigs.k8s.io/yaml",
"Rev": "fd68e9863619f6ec2fdd8625fe1f02e7c877e480"
}
]
}

View File

@@ -1,2 +0,0 @@
approvers:
- dep-approvers

View File

@@ -1,5 +0,0 @@
This directory tree is generated automatically by godep.
Please do not edit.
See https://github.com/tools/godep for more information.

162
vendor/k8s.io/client-go/INSTALL.md generated vendored
View File

@@ -1,162 +0,0 @@
# Installing client-go
## For the casual user
If you want to write a simple script, don't care about a reproducible client
library install, don't mind getting head (which may be less stable than a
particular release), then simply:
```sh
$ go get k8s.io/client-go/...
```
This will install `k8s.io/client-go` in your `$GOPATH`. `k8s.io/client-go`
includes most of its own dependencies in its `k8s.io/client-go/vendor` path,
except for `k8s.io/apimachinery` and `glog`. `go get` will recursively download
these excluded repos to your `$GOPATH`, if they don't already exist. If
`k8s.io/apimachinery` preexisted in `$GOPATH`, you also need to:
```sh
$ go get -u k8s.io/apimachinery/...
```
because the head of client-go is only guaranteed to work with the head of
apimachinery.
We excluded `k8s.io/apimachinery` and `glog` from `k8s.io/client-go/vendor` to
prevent `go get` users from hitting issues like
[#19](https://github.com/kubernetes/client-go/issues/19) and
[#83](https://github.com/kubernetes/client-go/issues/83). If your project share
other dependencies with client-go, and you hit issues similar to #19 or #83,
then you'll need to look down at the next section.
Note: the official go policy is that libraries should not vendor their
dependencies. This is unworkable for us, since our dependencies change and HEAD
on every dependency has not necessarily been tested with client-go. In fact,
HEAD from all dependencies may not even compile with client-go!
## Dependency management for the serious (or reluctant) user
Reasons why you might need to use a dependency management system:
* You use a dependency that client-go also uses, and don't want two copies of
the dependency compiled into your application. For some dependencies with
singletons or global inits (e.g. `glog`) this wouldn't even compile...
* You want to lock in a particular version (so you don't have to change your
code every time we change a public interface).
* You want your install to be reproducible. For example, for your CI system or
for new team members.
There are three tools you could in theory use for this. Instructions
for each follows.
### Godep
[godep](https://github.com/tools/godep) is an older dependency management tool, which is
used by the main Kubernetes repo and `client-go` to manage dependencies.
Before proceeding with the below instructions, you should ensure that your
$GOPATH is empty except for containing your own package and its dependencies,
and you have a copy of godep somewhere in your $PATH.
To install `client-go` and place its dependencies in your `$GOPATH`:
```sh
go get k8s.io/client-go/...
cd $GOPATH/src/k8s.io/client-go
git checkout v9.0.0 # replace v9.0.0 with the required version
# cd 1.5 # only necessary with 1.5 and 1.4 clients.
godep restore ./...
```
At this point, `client-go`'s dependencies have been placed in your $GOPATH, but
if you were to build, `client-go` would still see its own copy of its
dependencies in its `vendor` directory. You have two options at this point.
If you would like to keep dependencies in your own project's vendor directory,
then you can continue like this:
```sh
cd $GOPATH/src/<my-pkg>
godep save ./...
```
Alternatively, if you want to build using the dependencies in your `$GOPATH`,
then `rm -rf vendor/` to remove `client-go`'s copy of its dependencies.
### Glide
[Glide](https://github.com/Masterminds/glide) is another popular dependency
management tool for Go. Glide will manage your /vendor directory, but unlike
godep, will not use or modify your $GOPATH (there's no equivalent of
`godep restore` or `godep save`).
Generally, it's best to avoid Glide's many subcommands, favoring modifying
Glide's manifest file (`glide.yaml`) directly, then running
`glide update --strip-vendor`. First create a `glide.yaml` file at the root of
your project:
```yaml
package: ( your project's import path ) # e.g. github.com/foo/bar
import:
- package: k8s.io/client-go
version: v9.0.0 # replace v9.0.0 with the required version
```
Second, add a Go file that imports `client-go` somewhere in your project,
otherwise `client-go`'s dependencies will not be added to your project's
vendor/. Then run the following command in the same directory as `glide.yaml`:
```sh
glide update --strip-vendor
```
This can also be abbreviated as:
```sh
glide up -v
```
At this point, `k8s.io/client-go` should be added to your project's vendor/.
`client-go`'s dependencies should be flattened and be added to your project's
vendor/ as well.
Glide will detect the versions of dependencies `client-go` specified in
`client-go`'s Godep.json file, and automatically set the versions of these
imports in your /vendor directory. It will also record the detected version of
all dependencies in the `glide.lock` file.
Projects that require a different version of a dependency than `client-go`
requests can override the version manually in `glide.yaml`. For example:
```yaml
package: ( your project's import path ) # e.g. github.com/foo/bar
import:
- package: k8s.io/client-go
version: v9.0.0 # replace v9.0.0 with the required version
# Use a newer version of go-spew even though client-go wants an old one.
- package: github.com/davecgh/go-spew
version: v1.1.0
```
After modifying, run `glide up -v` again to re-populate your /vendor directory.
Optionally, Glide users can also use [`glide-vc`](https://github.com/sgotti/glide-vc)
after running `glide up -v` to remove unused files from /vendor.
### Dep (Not supported yet!)
[dep](https://github.com/golang/dep) is an up-and-coming dependency management
tool, which has the goal of being accepted as part of the standard go toolchain.
However, client-go does **NOT** work well with `dep` yet. To support `dep`, we
need to fix at least two issues:
1. publish native `Gopkg.toml` in client-go and other k8s.io repos, like `k8s.io/apimachinery`;
2. find a way to express transitive constraints (see https://github.com/golang/dep/issues/1124).
As a workaround, which may or may not be worthwhile, you can specify all
client-go dependencies manually as
[override](https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md#override)
in Gopkg.toml with the versions listed in [Godeps.json](./Godeps/Godeps.json),
and manually update them when you upgrade client-go version.
We are actively working on the two issues blocking using `dep`. For the
meantime, we recommend using `glide` or `godeps`.

17
vendor/k8s.io/client-go/OWNERS generated vendored
View File

@@ -1,17 +0,0 @@
approvers:
- caesarxuchao
- deads2k
- lavalamp
- liggitt
- smarterclayton
- sttts
reviewers:
- caesarxuchao
- deads2k
- lavalamp
- liggitt
- soltysh
- sttts
- yliaog
labels:
- sig/api-machinery

193
vendor/k8s.io/client-go/README.md generated vendored
View File

@@ -1,193 +0,0 @@
# client-go
Go clients for talking to a [kubernetes](http://kubernetes.io/) cluster.
We currently recommend using the v9.0.0 tag. See [INSTALL.md](/INSTALL.md) for
detailed installation instructions. `go get k8s.io/client-go/...` works, but
will build `master`, which doesn't handle the dependencies well.
[![BuildStatus Widget]][BuildStatus Result]
[![GoReport Widget]][GoReport Status]
[![GoDocWidget]][GoDocReference]
[BuildStatus Result]: https://travis-ci.org/kubernetes/client-go
[BuildStatus Widget]: https://travis-ci.org/kubernetes/client-go.svg?branch=master
[GoReport Status]: https://goreportcard.com/report/github.com/kubernetes/client-go
[GoReport Widget]: https://goreportcard.com/badge/github.com/kubernetes/client-go
[GoDocWidget]: https://godoc.org/k8s.io/client-go?status.svg
[GoDocReference]:https://godoc.org/k8s.io/client-go
## Table of Contents
- [What's included](#whats-included)
- [Versioning](#versioning)
- [Compatibility: your code <-> client-go](#compatibility-your-code---client-go)
- [Compatibility: client-go <-> Kubernetes clusters](#compatibility-client-go---kubernetes-clusters)
- [Compatibility matrix](#compatibility-matrix)
- [Why do the 1.4 and 1.5 branch contain top-level folder named after the version?](#why-do-the-14-and-15-branch-contain-top-level-folder-named-after-the-version)
- [Kubernetes tags](#kubernetes-tags)
- [How to get it](#how-to-get-it)
- [How to use it](#how-to-use-it)
- [Dependency management](#dependency-management)
- [Contributing code](#contributing-code)
### What's included
* The `kubernetes` package contains the clientset to access Kubernetes API.
* The `discovery` package is used to discover APIs supported by a Kubernetes API server.
* The `dynamic` package contains a dynamic client that can perform generic operations on arbitrary Kubernetes API objects.
* The `transport` package is used to set up auth and start a connection.
* The `tools/cache` package is useful for writing controllers.
### Versioning
`client-go` follows [semver](http://semver.org/). We will not make
backwards-incompatible changes without incrementing the major version number. A
change is backwards-incompatible either if it *i)* changes the public interfaces
of `client-go`, or *ii)* makes `client-go` incompatible with otherwise supported
versions of Kubernetes clusters.
Changes that add features in a backwards-compatible way will result in bumping
the minor version (second digit) number.
Bugfixes will result in the patch version (third digit) changing. PRs that are
cherry-picked into an older Kubernetes release branch will result in an update
to the corresponding branch in `client-go`, with a corresponding new tag
changing the patch version.
A consequence of this is that `client-go` version numbers will be unrelated to
Kubernetes version numbers.
#### Branches and tags.
We will create a new branch and tag for each increment in the major version number or
minor version number. We will create only a new tag for each increment in the patch
version number. See [semver](http://semver.org/) for definitions of major,
minor, and patch.
The master branch will track HEAD in the main Kubernetes repo and
accumulate changes. Consider HEAD to have the version `x.(y+1).0-alpha` or
`(x+1).0.0-alpha` (depending on whether it has accumulated a breaking change or
not), where `x` and `y` are the current major and minor versions.
#### Compatibility: your code <-> client-go
`client-go` follows [semver](http://semver.org/), so until the major version of
client-go gets increased, your code will compile and will continue to work with
explicitly supported versions of Kubernetes clusters. You must use a dependency
management system and pin a specific major version of `client-go` to get this
benefit, as HEAD follows the upstream Kubernetes repo.
#### Compatibility: client-go <-> Kubernetes clusters
Since Kubernetes is backwards compatible with clients, older `client-go`
versions will work with many different Kubernetes cluster versions.
We will backport bugfixes--but not new features--into older versions of
`client-go`.
#### Compatibility matrix
| | Kubernetes 1.6 | Kubernetes 1.7 | Kubernetes 1.8 | Kubernetes 1.9 | Kubernetes 1.10 | Kubernetes 1.11 | Kubernetes 1.12 |
|---------------------|----------------|----------------|----------------|----------------|-----------------|-----------------|-----------------|
| client-go 3.0 | ✓ | - | +- | +- | +- | +- | +- |
| client-go 4.0 | +- | ✓ | +- | +- | +- | +- | +- |
| client-go 5.0 | +- | +- | ✓ | +- | +- | +- | +- |
| client-go 6.0 | +- | +- | +- | ✓ | +- | +- | +- |
| client-go 7.0 | +- | +- | +- | +- | ✓ | +- | +- |
| client-go 8.0 | +- | +- | +- | +- | +- | ✓ | +- |
| client-go 9.0 | +- | +- | +- | +- | +- | +- | ✓ |
| client-go HEAD | +- | +- | +- | +- | +- | +- | +- |
Key:
* `✓` Exactly the same features / API objects in both client-go and the Kubernetes
version.
* `+` client-go has features or API objects that may not be present in the
Kubernetes cluster, either due to that client-go has additional new API, or
that the server has removed old API. However, everything they have in
common (i.e., most APIs) will work. Please note that alpha APIs may vanish or
change significantly in a single release.
* `-` The Kubernetes cluster has features the client-go library can't use,
either due to the server has additional new API, or that client-go has
removed old API. However, everything they share in common (i.e., most APIs)
will work.
See the [CHANGELOG](./CHANGELOG.md) for a detailed description of changes
between client-go versions.
| Branch | Canonical source code location | Maintenance status |
|----------------|--------------------------------------|-------------------------------|
| client-go 1.4 | Kubernetes main repo, 1.4 branch | = - |
| client-go 1.5 | Kubernetes main repo, 1.5 branch | = - |
| client-go 2.0 | Kubernetes main repo, 1.5 branch | = - |
| client-go 3.0 | Kubernetes main repo, 1.6 branch | = - |
| client-go 4.0 | Kubernetes main repo, 1.7 branch | = - |
| client-go 5.0 | Kubernetes main repo, 1.8 branch | = - |
| client-go 6.0 | Kubernetes main repo, 1.9 branch | = - |
| client-go 7.0 | Kubernetes main repo, 1.10 branch | ✓ |
| client-go 8.0 | Kubernetes main repo, 1.11 branch | ✓ |
| client-go 9.0 | Kubernetes main repo, 1.12 branch | ✓ |
| client-go HEAD | Kubernetes main repo, master branch | ✓ |
Key:
* `✓` Changes in main Kubernetes repo are actively published to client-go by a bot
* `=` Maintenance is manual, only severe security bugs will be patched.
* `-` Deprecated; please upgrade.
#### Deprecation policy
We will maintain branches for at least six months after their first stable tag
is cut. (E.g., the clock for the release-2.0 branch started ticking when we
tagged v2.0.0, not when we made the first alpha.) This policy applies to
every version greater than or equal to 2.0.
#### Why do the 1.4 and 1.5 branch contain top-level folder named after the version?
For the initial release of client-go, we thought it would be easiest to keep
separate directories for each minor version. That soon proved to be a mistake.
We are keeping the top-level folders in the 1.4 and 1.5 branches so that
existing users won't be broken.
### Kubernetes tags
This repository is still a mirror of
[k8s.io/kubernetes/staging/src/client-go](https://github.com/kubernetes/kubernetes/tree/master/staging/src/k8s.io/client-go),
the code development is still done in the staging area. Since Kubernetes 1.8
release, when syncing the code from the staging area, we also sync the Kubernetes
version tags to client-go, prefixed with "kubernetes-". For example, if you check
out the `kubernetes-v1.8.0` tag in client-go, the code you get is exactly the
same as if you check out the `v1.8.0` tag in kubernetes, and change directory to
`staging/src/k8s.io/client-go`. The purpose is to let users quickly find matching
commits among published repos, like
[sample-apiserver](https://github.com/kubernetes/sample-apiserver),
[apiextension-apiserver](https://github.com/kubernetes/apiextensions-apiserver),
etc. The Kubernetes version tag does NOT claim any backwards compatibility
guarantees for client-go. Please check the [semantic versions](#versioning) if
you care about backwards compatibility.
### How to get it
You can use `go get k8s.io/client-go/...` to get client-go, but **you will get
the unstable master branch** and `client-go`'s vendored dependencies will not be
added to your `$GOPATH`. So we think most users will want to use a dependency
management system. See [INSTALL.md](/INSTALL.md) for detailed instructions.
### How to use it
If your application runs in a Pod in the cluster, please refer to the
in-cluster [example](examples/in-cluster-client-configuration), otherwise please
refer to the out-of-cluster [example](examples/out-of-cluster-client-configuration).
### Dependency management
If your application depends on a package that client-go depends on, and you let the Go compiler find the dependency in `GOPATH`, you will end up with duplicated dependencies: one copy from the `GOPATH`, and one from the vendor folder of client-go. This will cause unexpected runtime error like flag redefinition, since the go compiler ends up importing both packages separately, even if they are exactly the same thing. If this happens, you can either
* run `godep restore` ([godep](https://github.com/tools/godep)) in the client-go/ folder, then remove the vendor folder of client-go. Then the packages in your GOPATH will be the only copy
* or run `godep save` in your application folder to flatten all dependencies.
### Contributing code
Please send pull requests against the client packages in the Kubernetes main [repository](https://github.com/kubernetes/kubernetes). Changes in the staging area will be published to this repository every day.

View File

@@ -1,17 +0,0 @@
# Defined below are the security contacts for this repo.
#
# They are the contact point for the Product Security Team to reach out
# to for triaging and handling of incoming issues.
#
# The below names agree to abide by the
# [Embargo Policy](https://github.com/kubernetes/sig-release/blob/master/security-release-process-documentation/security-release-process.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/
cjcullen
jessfraz
liggitt
philips
tallclair

View File

@@ -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)

View File

@@ -1,79 +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 deprecated_dynamic
import (
"encoding/json"
"io"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
)
// dynamicCodec is a codec that wraps the standard unstructured codec
// with special handling for Status objects.
// Deprecated only used by test code and its wrong
type dynamicCodec struct{}
func (dynamicCodec) Decode(data []byte, gvk *schema.GroupVersionKind, obj runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
obj, gvk, err := unstructured.UnstructuredJSONScheme.Decode(data, gvk, obj)
if err != nil {
return nil, nil, err
}
if _, ok := obj.(*metav1.Status); !ok && strings.ToLower(gvk.Kind) == "status" {
obj = &metav1.Status{}
err := json.Unmarshal(data, obj)
if err != nil {
return nil, nil, err
}
}
return obj, gvk, nil
}
func (dynamicCodec) Encode(obj runtime.Object, w io.Writer) error {
return unstructured.UnstructuredJSONScheme.Encode(obj, w)
}
// ContentConfig returns a rest.ContentConfig for dynamic types.
// Deprecated only used by test code and its wrong
func ContentConfig() rest.ContentConfig {
var jsonInfo runtime.SerializerInfo
// TODO: scheme.Codecs here should become "pkg/apis/server/scheme" which is the minimal core you need
// to talk to a kubernetes server
for _, info := range scheme.Codecs.SupportedMediaTypes() {
if info.MediaType == runtime.ContentTypeJSON {
jsonInfo = info
break
}
}
jsonInfo.Serializer = dynamicCodec{}
jsonInfo.PrettySerializer = nil
return rest.ContentConfig{
AcceptContentTypes: runtime.ContentTypeJSON,
ContentType: runtime.ContentTypeJSON,
NegotiatedSerializer: serializer.NegotiatedSerializerWrapper(jsonInfo),
}
}

View File

@@ -1,131 +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 dynamic provides a client interface to arbitrary Kubernetes
// APIs that exposes common high level operations and exposes common
// metadata.
package deprecated_dynamic
import (
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
restclient "k8s.io/client-go/rest"
)
// Interface is a Kubernetes client that allows you to access metadata
// and manipulate metadata of a Kubernetes API group.
type Interface interface {
// Resource returns an API interface to the specified resource for this client's
// group and version. If resource is not a namespaced resource, then namespace
// is ignored. The ResourceInterface inherits the parameter codec of this client.
Resource(resource *metav1.APIResource, namespace string) ResourceInterface
}
// ResourceInterface is an API interface to a specific resource under a
// dynamic client.
type ResourceInterface interface {
// List returns a list of objects for this resource.
List(opts metav1.ListOptions) (runtime.Object, error)
// Get gets the resource with the specified name.
Get(name string, opts metav1.GetOptions) (*unstructured.Unstructured, error)
// Delete deletes the resource with the specified name.
Delete(name string, opts *metav1.DeleteOptions) error
// DeleteCollection deletes a collection of objects.
DeleteCollection(deleteOptions *metav1.DeleteOptions, listOptions metav1.ListOptions) error
// Create creates the provided resource.
Create(obj *unstructured.Unstructured) (*unstructured.Unstructured, error)
// Update updates the provided resource.
Update(obj *unstructured.Unstructured) (*unstructured.Unstructured, error)
// Watch returns a watch.Interface that watches the resource.
Watch(opts metav1.ListOptions) (watch.Interface, error)
// Patch patches the provided resource.
Patch(name string, pt types.PatchType, data []byte) (*unstructured.Unstructured, error)
}
// Client is a Kubernetes client that allows you to access metadata
// and manipulate metadata of a Kubernetes API group, and implements Interface.
type Client struct {
version schema.GroupVersion
delegate dynamic.Interface
}
// NewClient returns a new client based on the passed in config. The
// codec is ignored, as the dynamic client uses it's own codec.
func NewClient(conf *restclient.Config, version schema.GroupVersion) (*Client, error) {
delegate, err := dynamic.NewForConfig(conf)
if err != nil {
return nil, err
}
return &Client{version: version, delegate: delegate}, nil
}
// Resource returns an API interface to the specified resource for this client's
// group and version. If resource is not a namespaced resource, then namespace
// is ignored. The ResourceInterface inherits the parameter codec of c.
func (c *Client) Resource(resource *metav1.APIResource, namespace string) ResourceInterface {
resourceTokens := strings.SplitN(resource.Name, "/", 2)
subresources := []string{}
if len(resourceTokens) > 1 {
subresources = strings.Split(resourceTokens[1], "/")
}
if len(namespace) == 0 {
return oldResourceShim(c.delegate.Resource(c.version.WithResource(resourceTokens[0])), subresources)
}
return oldResourceShim(c.delegate.Resource(c.version.WithResource(resourceTokens[0])).Namespace(namespace), subresources)
}
// the old interfaces used the wrong type for lists. this fixes that
func oldResourceShim(in dynamic.ResourceInterface, subresources []string) ResourceInterface {
return oldResourceShimType{ResourceInterface: in, subresources: subresources}
}
type oldResourceShimType struct {
dynamic.ResourceInterface
subresources []string
}
func (s oldResourceShimType) Create(obj *unstructured.Unstructured) (*unstructured.Unstructured, error) {
return s.ResourceInterface.Create(obj, metav1.CreateOptions{}, s.subresources...)
}
func (s oldResourceShimType) Update(obj *unstructured.Unstructured) (*unstructured.Unstructured, error) {
return s.ResourceInterface.Update(obj, metav1.UpdateOptions{}, s.subresources...)
}
func (s oldResourceShimType) Delete(name string, opts *metav1.DeleteOptions) error {
return s.ResourceInterface.Delete(name, opts, s.subresources...)
}
func (s oldResourceShimType) Get(name string, opts metav1.GetOptions) (*unstructured.Unstructured, error) {
return s.ResourceInterface.Get(name, opts, s.subresources...)
}
func (s oldResourceShimType) List(opts metav1.ListOptions) (runtime.Object, error) {
return s.ResourceInterface.List(opts)
}
func (s oldResourceShimType) Patch(name string, pt types.PatchType, data []byte) (*unstructured.Unstructured, error) {
return s.ResourceInterface.Patch(name, pt, data, metav1.UpdateOptions{}, s.subresources...)
}

View File

@@ -1,122 +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 deprecated_dynamic
import (
"sync"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema"
restclient "k8s.io/client-go/rest"
)
// ClientPool manages a pool of dynamic clients.
type ClientPool interface {
// ClientForGroupVersionResource returns a client configured for the specified groupVersionResource.
// Resource may be empty.
ClientForGroupVersionResource(resource schema.GroupVersionResource) (Interface, error)
// ClientForGroupVersionKind returns a client configured for the specified groupVersionKind.
// Kind may be empty.
ClientForGroupVersionKind(kind schema.GroupVersionKind) (Interface, error)
}
// APIPathResolverFunc knows how to convert a groupVersion to its API path. The Kind field is
// optional.
type APIPathResolverFunc func(kind schema.GroupVersionKind) string
// LegacyAPIPathResolverFunc can resolve paths properly with the legacy API.
func LegacyAPIPathResolverFunc(kind schema.GroupVersionKind) string {
if len(kind.Group) == 0 {
return "/api"
}
return "/apis"
}
// clientPoolImpl implements ClientPool and caches clients for the resource group versions
// is asked to retrieve. This type is thread safe.
type clientPoolImpl struct {
lock sync.RWMutex
config *restclient.Config
clients map[schema.GroupVersion]*Client
apiPathResolverFunc APIPathResolverFunc
mapper meta.RESTMapper
}
// NewClientPool returns a ClientPool from the specified config. It reuses clients for the same
// group version. It is expected this type may be wrapped by specific logic that special cases certain
// resources or groups.
func NewClientPool(config *restclient.Config, mapper meta.RESTMapper, apiPathResolverFunc APIPathResolverFunc) ClientPool {
confCopy := *config
return &clientPoolImpl{
config: &confCopy,
clients: map[schema.GroupVersion]*Client{},
apiPathResolverFunc: apiPathResolverFunc,
mapper: mapper,
}
}
// Instantiates a new dynamic client pool with the given config.
func NewDynamicClientPool(cfg *restclient.Config) ClientPool {
// restMapper is not needed when using LegacyAPIPathResolverFunc
emptyMapper := meta.MultiRESTMapper{}
return NewClientPool(cfg, emptyMapper, LegacyAPIPathResolverFunc)
}
// ClientForGroupVersionResource uses the provided RESTMapper to identify the appropriate resource. Resource may
// be empty. If no matching kind is found the underlying client for that group is still returned.
func (c *clientPoolImpl) ClientForGroupVersionResource(resource schema.GroupVersionResource) (Interface, error) {
kinds, err := c.mapper.KindsFor(resource)
if err != nil {
if meta.IsNoMatchError(err) {
return c.ClientForGroupVersionKind(schema.GroupVersionKind{Group: resource.Group, Version: resource.Version})
}
return nil, err
}
return c.ClientForGroupVersionKind(kinds[0])
}
// ClientForGroupVersion returns a client for the specified groupVersion, creates one if none exists. Kind
// in the GroupVersionKind may be empty.
func (c *clientPoolImpl) ClientForGroupVersionKind(kind schema.GroupVersionKind) (Interface, error) {
c.lock.Lock()
defer c.lock.Unlock()
gv := kind.GroupVersion()
// do we have a client already configured?
if existingClient, found := c.clients[gv]; found {
return existingClient, nil
}
// avoid changing the original config
confCopy := *c.config
conf := &confCopy
// we need to set the api path based on group version, if no group, default to legacy path
conf.APIPath = c.apiPathResolverFunc(kind)
// we need to make a client
conf.GroupVersion = &gv
dynamicClient, err := NewClient(conf, gv)
if err != nil {
return nil, err
}
c.clients[gv] = dynamicClient
return dynamicClient, nil
}

View File

@@ -1,623 +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 deprecated_dynamic
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer/streaming"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
restclient "k8s.io/client-go/rest"
restclientwatch "k8s.io/client-go/rest/watch"
)
func getJSON(version, kind, name string) []byte {
return []byte(fmt.Sprintf(`{"apiVersion": %q, "kind": %q, "metadata": {"name": %q}}`, version, kind, name))
}
func getListJSON(version, kind string, items ...[]byte) []byte {
json := fmt.Sprintf(`{"apiVersion": %q, "kind": %q, "items": [%s]}`,
version, kind, bytes.Join(items, []byte(",")))
return []byte(json)
}
func getObject(version, kind, name string) *unstructured.Unstructured {
return &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": version,
"kind": kind,
"metadata": map[string]interface{}{
"name": name,
},
},
}
}
func getClientServer(gv *schema.GroupVersion, h func(http.ResponseWriter, *http.Request)) (Interface, *httptest.Server, error) {
srv := httptest.NewServer(http.HandlerFunc(h))
cl, err := NewClient(&restclient.Config{
Host: srv.URL,
ContentConfig: restclient.ContentConfig{GroupVersion: gv},
}, *gv)
if err != nil {
srv.Close()
return nil, nil, err
}
return cl, srv, nil
}
func TestList(t *testing.T) {
tcs := []struct {
name string
namespace string
path string
resp []byte
want *unstructured.UnstructuredList
}{
{
name: "normal_list",
path: "/apis/gtest/vtest/rtest",
resp: getListJSON("vTest", "rTestList",
getJSON("vTest", "rTest", "item1"),
getJSON("vTest", "rTest", "item2")),
want: &unstructured.UnstructuredList{
Object: map[string]interface{}{
"apiVersion": "vTest",
"kind": "rTestList",
},
Items: []unstructured.Unstructured{
*getObject("vTest", "rTest", "item1"),
*getObject("vTest", "rTest", "item2"),
},
},
},
{
name: "namespaced_list",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest",
resp: getListJSON("vTest", "rTestList",
getJSON("vTest", "rTest", "item1"),
getJSON("vTest", "rTest", "item2")),
want: &unstructured.UnstructuredList{
Object: map[string]interface{}{
"apiVersion": "vTest",
"kind": "rTestList",
},
Items: []unstructured.Unstructured{
*getObject("vTest", "rTest", "item1"),
*getObject("vTest", "rTest", "item2"),
},
},
},
}
for _, tc := range tcs {
gv := &schema.GroupVersion{Group: "gtest", Version: "vtest"}
resource := &metav1.APIResource{Name: "rtest", Namespaced: len(tc.namespace) != 0}
cl, srv, err := getClientServer(gv, func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Errorf("List(%q) got HTTP method %s. wanted GET", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("List(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
w.Write(tc.resp)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
got, err := cl.Resource(resource, tc.namespace).List(metav1.ListOptions{})
if err != nil {
t.Errorf("unexpected error when listing %q: %v", tc.name, err)
continue
}
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("List(%q) want: %v\ngot: %v", tc.name, tc.want, got)
}
}
}
func TestGet(t *testing.T) {
tcs := []struct {
resource string
namespace string
name string
path string
resp []byte
want *unstructured.Unstructured
}{
{
resource: "rtest",
name: "normal_get",
path: "/apis/gtest/vtest/rtest/normal_get",
resp: getJSON("vTest", "rTest", "normal_get"),
want: getObject("vTest", "rTest", "normal_get"),
},
{
resource: "rtest",
namespace: "nstest",
name: "namespaced_get",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_get",
resp: getJSON("vTest", "rTest", "namespaced_get"),
want: getObject("vTest", "rTest", "namespaced_get"),
},
{
resource: "rtest/srtest",
name: "normal_subresource_get",
path: "/apis/gtest/vtest/rtest/normal_subresource_get/srtest",
resp: getJSON("vTest", "srTest", "normal_subresource_get"),
want: getObject("vTest", "srTest", "normal_subresource_get"),
},
{
resource: "rtest/srtest",
namespace: "nstest",
name: "namespaced_subresource_get",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_subresource_get/srtest",
resp: getJSON("vTest", "srTest", "namespaced_subresource_get"),
want: getObject("vTest", "srTest", "namespaced_subresource_get"),
},
}
for _, tc := range tcs {
gv := &schema.GroupVersion{Group: "gtest", Version: "vtest"}
resource := &metav1.APIResource{Name: tc.resource, Namespaced: len(tc.namespace) != 0}
cl, srv, err := getClientServer(gv, func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Errorf("Get(%q) got HTTP method %s. wanted GET", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Get(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
w.Write(tc.resp)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
got, err := cl.Resource(resource, tc.namespace).Get(tc.name, metav1.GetOptions{})
if err != nil {
t.Errorf("unexpected error when getting %q: %v", tc.name, err)
continue
}
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("Get(%q) want: %v\ngot: %v", tc.name, tc.want, got)
}
}
}
func TestDelete(t *testing.T) {
background := metav1.DeletePropagationBackground
uid := types.UID("uid")
statusOK := &metav1.Status{
TypeMeta: metav1.TypeMeta{Kind: "Status"},
Status: metav1.StatusSuccess,
}
tcs := []struct {
namespace string
name string
path string
deleteOptions *metav1.DeleteOptions
}{
{
name: "normal_delete",
path: "/apis/gtest/vtest/rtest/normal_delete",
},
{
namespace: "nstest",
name: "namespaced_delete",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_delete",
},
{
namespace: "nstest",
name: "namespaced_delete_with_options",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_delete_with_options",
deleteOptions: &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &uid}, PropagationPolicy: &background},
},
}
for _, tc := range tcs {
gv := &schema.GroupVersion{Group: "gtest", Version: "vtest"}
resource := &metav1.APIResource{Name: "rtest", Namespaced: len(tc.namespace) != 0}
cl, srv, err := getClientServer(gv, func(w http.ResponseWriter, r *http.Request) {
if r.Method != "DELETE" {
t.Errorf("Delete(%q) got HTTP method %s. wanted DELETE", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Delete(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
unstructured.UnstructuredJSONScheme.Encode(statusOK, w)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
err = cl.Resource(resource, tc.namespace).Delete(tc.name, tc.deleteOptions)
if err != nil {
t.Errorf("unexpected error when deleting %q: %v", tc.name, err)
continue
}
}
}
func TestDeleteCollection(t *testing.T) {
statusOK := &metav1.Status{
TypeMeta: metav1.TypeMeta{Kind: "Status"},
Status: metav1.StatusSuccess,
}
tcs := []struct {
namespace string
name string
path string
}{
{
name: "normal_delete_collection",
path: "/apis/gtest/vtest/rtest",
},
{
namespace: "nstest",
name: "namespaced_delete_collection",
path: "/apis/gtest/vtest/namespaces/nstest/rtest",
},
}
for _, tc := range tcs {
gv := &schema.GroupVersion{Group: "gtest", Version: "vtest"}
resource := &metav1.APIResource{Name: "rtest", Namespaced: len(tc.namespace) != 0}
cl, srv, err := getClientServer(gv, func(w http.ResponseWriter, r *http.Request) {
if r.Method != "DELETE" {
t.Errorf("DeleteCollection(%q) got HTTP method %s. wanted DELETE", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("DeleteCollection(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
unstructured.UnstructuredJSONScheme.Encode(statusOK, w)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
err = cl.Resource(resource, tc.namespace).DeleteCollection(nil, metav1.ListOptions{})
if err != nil {
t.Errorf("unexpected error when deleting collection %q: %v", tc.name, err)
continue
}
}
}
func TestCreate(t *testing.T) {
tcs := []struct {
resource string
name string
namespace string
obj *unstructured.Unstructured
path string
}{
{
resource: "rtest",
name: "normal_create",
path: "/apis/gtest/vtest/rtest",
obj: getObject("gtest/vTest", "rTest", "normal_create"),
},
{
resource: "rtest",
name: "namespaced_create",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest",
obj: getObject("gtest/vTest", "rTest", "namespaced_create"),
},
}
for _, tc := range tcs {
gv := &schema.GroupVersion{Group: "gtest", Version: "vtest"}
resource := &metav1.APIResource{Name: tc.resource, Namespaced: len(tc.namespace) != 0}
cl, srv, err := getClientServer(gv, func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
t.Errorf("Create(%q) got HTTP method %s. wanted POST", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Create(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
data, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Errorf("Create(%q) unexpected error reading body: %v", tc.name, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(data)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
got, err := cl.Resource(resource, tc.namespace).Create(tc.obj)
if err != nil {
t.Errorf("unexpected error when creating %q: %v", tc.name, err)
continue
}
if !reflect.DeepEqual(got, tc.obj) {
t.Errorf("Create(%q) want: %v\ngot: %v", tc.name, tc.obj, got)
}
}
}
func TestUpdate(t *testing.T) {
tcs := []struct {
resource string
name string
namespace string
obj *unstructured.Unstructured
path string
}{
{
resource: "rtest",
name: "normal_update",
path: "/apis/gtest/vtest/rtest/normal_update",
obj: getObject("gtest/vTest", "rTest", "normal_update"),
},
{
resource: "rtest",
name: "namespaced_update",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_update",
obj: getObject("gtest/vTest", "rTest", "namespaced_update"),
},
{
resource: "rtest/srtest",
name: "normal_subresource_update",
path: "/apis/gtest/vtest/rtest/normal_update/srtest",
obj: getObject("gtest/vTest", "srTest", "normal_update"),
},
{
resource: "rtest/srtest",
name: "namespaced_subresource_update",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_update/srtest",
obj: getObject("gtest/vTest", "srTest", "namespaced_update"),
},
}
for _, tc := range tcs {
gv := &schema.GroupVersion{Group: "gtest", Version: "vtest"}
resource := &metav1.APIResource{Name: tc.resource, Namespaced: len(tc.namespace) != 0}
cl, srv, err := getClientServer(gv, func(w http.ResponseWriter, r *http.Request) {
if r.Method != "PUT" {
t.Errorf("Update(%q) got HTTP method %s. wanted PUT", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Update(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
data, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Errorf("Update(%q) unexpected error reading body: %v", tc.name, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(data)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
got, err := cl.Resource(resource, tc.namespace).Update(tc.obj)
if err != nil {
t.Errorf("unexpected error when updating %q: %v", tc.name, err)
continue
}
if !reflect.DeepEqual(got, tc.obj) {
t.Errorf("Update(%q) want: %v\ngot: %v", tc.name, tc.obj, got)
}
}
}
func TestWatch(t *testing.T) {
tcs := []struct {
name string
namespace string
events []watch.Event
path string
query string
}{
{
name: "normal_watch",
path: "/apis/gtest/vtest/rtest",
query: "watch=true",
events: []watch.Event{
{Type: watch.Added, Object: getObject("gtest/vTest", "rTest", "normal_watch")},
{Type: watch.Modified, Object: getObject("gtest/vTest", "rTest", "normal_watch")},
{Type: watch.Deleted, Object: getObject("gtest/vTest", "rTest", "normal_watch")},
},
},
{
name: "namespaced_watch",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest",
query: "watch=true",
events: []watch.Event{
{Type: watch.Added, Object: getObject("gtest/vTest", "rTest", "namespaced_watch")},
{Type: watch.Modified, Object: getObject("gtest/vTest", "rTest", "namespaced_watch")},
{Type: watch.Deleted, Object: getObject("gtest/vTest", "rTest", "namespaced_watch")},
},
},
}
for _, tc := range tcs {
gv := &schema.GroupVersion{Group: "gtest", Version: "vtest"}
resource := &metav1.APIResource{Name: "rtest", Namespaced: len(tc.namespace) != 0}
cl, srv, err := getClientServer(gv, func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Errorf("Watch(%q) got HTTP method %s. wanted GET", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Watch(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
if r.URL.RawQuery != tc.query {
t.Errorf("Watch(%q) got query %s. wanted %s", tc.name, r.URL.RawQuery, tc.query)
}
enc := restclientwatch.NewEncoder(streaming.NewEncoder(w, dynamicCodec{}), dynamicCodec{})
for _, e := range tc.events {
enc.Encode(&e)
}
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
watcher, err := cl.Resource(resource, tc.namespace).Watch(metav1.ListOptions{})
if err != nil {
t.Errorf("unexpected error when watching %q: %v", tc.name, err)
continue
}
for _, want := range tc.events {
got := <-watcher.ResultChan()
if !reflect.DeepEqual(got, want) {
t.Errorf("Watch(%q) want: %v\ngot: %v", tc.name, want, got)
}
}
}
}
func TestPatch(t *testing.T) {
tcs := []struct {
resource string
name string
namespace string
patch []byte
want *unstructured.Unstructured
path string
}{
{
resource: "rtest",
name: "normal_patch",
path: "/apis/gtest/vtest/rtest/normal_patch",
patch: getJSON("gtest/vTest", "rTest", "normal_patch"),
want: getObject("gtest/vTest", "rTest", "normal_patch"),
},
{
resource: "rtest",
name: "namespaced_patch",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_patch",
patch: getJSON("gtest/vTest", "rTest", "namespaced_patch"),
want: getObject("gtest/vTest", "rTest", "namespaced_patch"),
},
{
resource: "rtest/srtest",
name: "normal_subresource_patch",
path: "/apis/gtest/vtest/rtest/normal_subresource_patch/srtest",
patch: getJSON("gtest/vTest", "srTest", "normal_subresource_patch"),
want: getObject("gtest/vTest", "srTest", "normal_subresource_patch"),
},
{
resource: "rtest/srtest",
name: "namespaced_subresource_patch",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_subresource_patch/srtest",
patch: getJSON("gtest/vTest", "srTest", "namespaced_subresource_patch"),
want: getObject("gtest/vTest", "srTest", "namespaced_subresource_patch"),
},
}
for _, tc := range tcs {
gv := &schema.GroupVersion{Group: "gtest", Version: "vtest"}
resource := &metav1.APIResource{Name: tc.resource, Namespaced: len(tc.namespace) != 0}
cl, srv, err := getClientServer(gv, func(w http.ResponseWriter, r *http.Request) {
if r.Method != "PATCH" {
t.Errorf("Patch(%q) got HTTP method %s. wanted PATCH", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Patch(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
content := r.Header.Get("Content-Type")
if content != string(types.StrategicMergePatchType) {
t.Errorf("Patch(%q) got Content-Type %s. wanted %s", tc.name, content, types.StrategicMergePatchType)
}
data, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Errorf("Patch(%q) unexpected error reading body: %v", tc.name, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
got, err := cl.Resource(resource, tc.namespace).Patch(tc.name, types.StrategicMergePatchType, tc.patch)
if err != nil {
t.Errorf("unexpected error when patching %q: %v", tc.name, err)
continue
}
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("Patch(%q) want: %v\ngot: %v", tc.name, tc.want, got)
}
}
}

View File

@@ -1,161 +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 cached
import (
"errors"
"fmt"
"sync"
"github.com/googleapis/gnostic/OpenAPIv2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/version"
"k8s.io/client-go/discovery"
restclient "k8s.io/client-go/rest"
)
// memCacheClient can Invalidate() to stay up-to-date with discovery
// information.
//
// TODO: Switch to a watch interface. Right now it will poll anytime
// Invalidate() is called.
type memCacheClient struct {
delegate discovery.DiscoveryInterface
lock sync.RWMutex
groupToServerResources map[string]*metav1.APIResourceList
groupList *metav1.APIGroupList
cacheValid bool
}
// Error Constants
var (
ErrCacheEmpty = errors.New("the cache has not been filled yet")
ErrCacheNotFound = errors.New("not found")
)
var _ discovery.CachedDiscoveryInterface = &memCacheClient{}
// ServerResourcesForGroupVersion returns the supported resources for a group and version.
func (d *memCacheClient) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) {
d.lock.RLock()
defer d.lock.RUnlock()
if !d.cacheValid {
return nil, ErrCacheEmpty
}
cachedVal, ok := d.groupToServerResources[groupVersion]
if !ok {
return nil, ErrCacheNotFound
}
return cachedVal, nil
}
// ServerResources returns the supported resources for all groups and versions.
func (d *memCacheClient) ServerResources() ([]*metav1.APIResourceList, error) {
return discovery.ServerResources(d)
}
func (d *memCacheClient) ServerGroups() (*metav1.APIGroupList, error) {
d.lock.RLock()
defer d.lock.RUnlock()
if d.groupList == nil {
return nil, ErrCacheEmpty
}
return d.groupList, nil
}
func (d *memCacheClient) RESTClient() restclient.Interface {
return d.delegate.RESTClient()
}
func (d *memCacheClient) ServerPreferredResources() ([]*metav1.APIResourceList, error) {
return discovery.ServerPreferredResources(d)
}
func (d *memCacheClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) {
return discovery.ServerPreferredNamespacedResources(d)
}
func (d *memCacheClient) ServerVersion() (*version.Info, error) {
return d.delegate.ServerVersion()
}
func (d *memCacheClient) OpenAPISchema() (*openapi_v2.Document, error) {
return d.delegate.OpenAPISchema()
}
func (d *memCacheClient) Fresh() bool {
d.lock.RLock()
defer d.lock.RUnlock()
// Fresh is supposed to tell the caller whether or not to retry if the cache
// fails to find something. The idea here is that Invalidate will be called
// periodically and therefore we'll always be returning the latest data. (And
// in the future we can watch and stay even more up-to-date.) So we only
// return false if the cache has never been filled.
return d.cacheValid
}
// Invalidate refreshes the cache, blocking calls until the cache has been
// refreshed. It would be trivial to make a version that does this in the
// background while continuing to respond to requests if needed.
func (d *memCacheClient) Invalidate() {
d.lock.Lock()
defer d.lock.Unlock()
// TODO: Could this multiplicative set of calls be replaced by a single call
// to ServerResources? If it's possible for more than one resulting
// APIResourceList to have the same GroupVersion, the lists would need merged.
gl, err := d.delegate.ServerGroups()
if err != nil || len(gl.Groups) == 0 {
utilruntime.HandleError(fmt.Errorf("couldn't get current server API group list; will keep using cached value. (%v)", err))
return
}
rl := map[string]*metav1.APIResourceList{}
for _, g := range gl.Groups {
for _, v := range g.Versions {
r, err := d.delegate.ServerResourcesForGroupVersion(v.GroupVersion)
if err != nil || len(r.APIResources) == 0 {
utilruntime.HandleError(fmt.Errorf("couldn't get resource list for %v: %v", v.GroupVersion, err))
if cur, ok := d.groupToServerResources[v.GroupVersion]; ok {
// retain the existing list, if we had it.
r = cur
} else {
continue
}
}
rl[v.GroupVersion] = r
}
}
d.groupToServerResources, d.groupList = rl, gl
d.cacheValid = true
}
// NewMemCacheClient creates a new CachedDiscoveryInterface which caches
// discovery information in memory and will stay up-to-date if Invalidate is
// called with regularity.
//
// NOTE: The client will NOT resort to live lookups on cache misses.
func NewMemCacheClient(delegate discovery.DiscoveryInterface) discovery.CachedDiscoveryInterface {
return &memCacheClient{
delegate: delegate,
groupToServerResources: map[string]*metav1.APIResourceList{},
}
}

View File

@@ -1,132 +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 cached
import (
"errors"
"reflect"
"sync"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/discovery/fake"
)
type fakeDiscovery struct {
*fake.FakeDiscovery
lock sync.Mutex
groupList *metav1.APIGroupList
resourceMap map[string]*metav1.APIResourceList
}
func (c *fakeDiscovery) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) {
c.lock.Lock()
defer c.lock.Unlock()
if rl, ok := c.resourceMap[groupVersion]; ok {
return rl, nil
}
return nil, errors.New("doesn't exist")
}
func (c *fakeDiscovery) ServerGroups() (*metav1.APIGroupList, error) {
c.lock.Lock()
defer c.lock.Unlock()
if c.groupList == nil {
return nil, errors.New("doesn't exist")
}
return c.groupList, nil
}
func TestClient(t *testing.T) {
fake := &fakeDiscovery{
groupList: &metav1.APIGroupList{
Groups: []metav1.APIGroup{{
Name: "astronomy",
Versions: []metav1.GroupVersionForDiscovery{{
GroupVersion: "astronomy/v8beta1",
Version: "v8beta1",
}},
}},
},
resourceMap: map[string]*metav1.APIResourceList{
"astronomy/v8beta1": {
GroupVersion: "astronomy/v8beta1",
APIResources: []metav1.APIResource{{
Name: "dwarfplanets",
SingularName: "dwarfplanet",
Namespaced: true,
Kind: "DwarfPlanet",
ShortNames: []string{"dp"},
}},
},
},
}
c := NewMemCacheClient(fake)
g, err := c.ServerGroups()
if err == nil {
t.Errorf("Unexpected non-error.")
}
if c.Fresh() {
t.Errorf("Expected not fresh.")
}
c.Invalidate()
if !c.Fresh() {
t.Errorf("Expected fresh.")
}
g, err = c.ServerGroups()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if e, a := fake.groupList, g; !reflect.DeepEqual(e, a) {
t.Errorf("Expected %#v, got %#v", e, a)
}
r, err := c.ServerResourcesForGroupVersion("astronomy/v8beta1")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if e, a := fake.resourceMap["astronomy/v8beta1"], r; !reflect.DeepEqual(e, a) {
t.Errorf("Expected %#v, got %#v", e, a)
}
fake.lock.Lock()
fake.resourceMap = map[string]*metav1.APIResourceList{
"astronomy/v8beta1": {
GroupVersion: "astronomy/v8beta1",
APIResources: []metav1.APIResource{{
Name: "stars",
SingularName: "star",
Namespaced: true,
Kind: "Star",
ShortNames: []string{"s"},
}},
},
}
fake.lock.Unlock()
c.Invalidate()
r, err = c.ServerResourcesForGroupVersion("astronomy/v8beta1")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if e, a := fake.resourceMap["astronomy/v8beta1"], r; !reflect.DeepEqual(e, a) {
t.Errorf("Expected %#v, got %#v", e, a)
}
}

View File

@@ -1,169 +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 discovery
import (
"io/ioutil"
"os"
"testing"
"time"
"github.com/googleapis/gnostic/OpenAPIv2"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/version"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/rest/fake"
)
func TestCachedDiscoveryClient_Fresh(t *testing.T) {
assert := assert.New(t)
d, err := ioutil.TempDir("", "")
assert.NoError(err)
defer os.RemoveAll(d)
c := fakeDiscoveryClient{}
cdc := newCachedDiscoveryClient(&c, d, 60*time.Second)
assert.True(cdc.Fresh(), "should be fresh after creation")
cdc.ServerGroups()
assert.True(cdc.Fresh(), "should be fresh after groups call without cache")
assert.Equal(c.groupCalls, 1)
cdc.ServerGroups()
assert.True(cdc.Fresh(), "should be fresh after another groups call")
assert.Equal(c.groupCalls, 1)
cdc.ServerResources()
assert.True(cdc.Fresh(), "should be fresh after resources call")
assert.Equal(c.resourceCalls, 1)
cdc.ServerResources()
assert.True(cdc.Fresh(), "should be fresh after another resources call")
assert.Equal(c.resourceCalls, 1)
cdc = newCachedDiscoveryClient(&c, d, 60*time.Second)
cdc.ServerGroups()
assert.False(cdc.Fresh(), "should NOT be fresh after recreation with existing groups cache")
assert.Equal(c.groupCalls, 1)
cdc.ServerResources()
assert.False(cdc.Fresh(), "should NOT be fresh after recreation with existing resources cache")
assert.Equal(c.resourceCalls, 1)
cdc.Invalidate()
assert.True(cdc.Fresh(), "should be fresh after cache invalidation")
cdc.ServerResources()
assert.True(cdc.Fresh(), "should ignore existing resources cache after invalidation")
assert.Equal(c.resourceCalls, 2)
}
func TestNewCachedDiscoveryClient_TTL(t *testing.T) {
assert := assert.New(t)
d, err := ioutil.TempDir("", "")
assert.NoError(err)
defer os.RemoveAll(d)
c := fakeDiscoveryClient{}
cdc := newCachedDiscoveryClient(&c, d, 1*time.Nanosecond)
cdc.ServerGroups()
assert.Equal(c.groupCalls, 1)
time.Sleep(1 * time.Second)
cdc.ServerGroups()
assert.Equal(c.groupCalls, 2)
}
type fakeDiscoveryClient struct {
groupCalls int
resourceCalls int
versionCalls int
openAPICalls int
serverResourcesHandler func() ([]*metav1.APIResourceList, error)
}
var _ DiscoveryInterface = &fakeDiscoveryClient{}
func (c *fakeDiscoveryClient) RESTClient() restclient.Interface {
return &fake.RESTClient{}
}
func (c *fakeDiscoveryClient) ServerGroups() (*metav1.APIGroupList, error) {
c.groupCalls = c.groupCalls + 1
return &metav1.APIGroupList{
Groups: []metav1.APIGroup{
{
Name: "a",
Versions: []metav1.GroupVersionForDiscovery{
{
GroupVersion: "a/v1",
Version: "v1",
},
},
PreferredVersion: metav1.GroupVersionForDiscovery{
GroupVersion: "a/v1",
Version: "v1",
},
},
},
}, nil
}
func (c *fakeDiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) {
c.resourceCalls = c.resourceCalls + 1
if groupVersion == "a/v1" {
return &metav1.APIResourceList{APIResources: []metav1.APIResource{{Name: "widgets", Kind: "Widget"}}}, nil
}
return nil, errors.NewNotFound(schema.GroupResource{}, "")
}
func (c *fakeDiscoveryClient) ServerResources() ([]*metav1.APIResourceList, error) {
c.resourceCalls = c.resourceCalls + 1
if c.serverResourcesHandler != nil {
return c.serverResourcesHandler()
}
return []*metav1.APIResourceList{}, nil
}
func (c *fakeDiscoveryClient) ServerPreferredResources() ([]*metav1.APIResourceList, error) {
c.resourceCalls = c.resourceCalls + 1
return nil, nil
}
func (c *fakeDiscoveryClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) {
c.resourceCalls = c.resourceCalls + 1
return nil, nil
}
func (c *fakeDiscoveryClient) ServerVersion() (*version.Info, error) {
c.versionCalls = c.versionCalls + 1
return &version.Info{}, nil
}
func (c *fakeDiscoveryClient) OpenAPISchema() (*openapi_v2.Document, error) {
c.openAPICalls = c.openAPICalls + 1
return &openapi_v2.Document{}, nil
}

View File

@@ -1,882 +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 discovery
import (
"encoding/json"
"fmt"
"mime"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/gogo/protobuf/proto"
"github.com/googleapis/gnostic/OpenAPIv2"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/diff"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/version"
restclient "k8s.io/client-go/rest"
)
func TestGetServerVersion(t *testing.T) {
expect := version.Info{
Major: "foo",
Minor: "bar",
GitCommit: "baz",
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
output, err := json.Marshal(expect)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(output)
}))
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
got, err := client.ServerVersion()
if err != nil {
t.Fatalf("unexpected encoding error: %v", err)
}
if e, a := expect, *got; !reflect.DeepEqual(e, a) {
t.Errorf("expected %v, got %v", e, a)
}
}
func TestGetServerGroupsWithV1Server(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
var obj interface{}
switch req.URL.Path {
case "/api":
obj = &metav1.APIVersions{
Versions: []string{
"v1",
},
}
case "/apis":
obj = &metav1.APIGroupList{
Groups: []metav1.APIGroup{
{
Name: "extensions",
Versions: []metav1.GroupVersionForDiscovery{
{GroupVersion: "extensions/v1beta1"},
},
},
},
}
default:
w.WriteHeader(http.StatusNotFound)
return
}
output, err := json.Marshal(obj)
if err != nil {
t.Fatalf("unexpected encoding error: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(output)
}))
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
// ServerGroups should not return an error even if server returns error at /api and /apis
apiGroupList, err := client.ServerGroups()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
groupVersions := metav1.ExtractGroupVersions(apiGroupList)
if !reflect.DeepEqual(groupVersions, []string{"v1", "extensions/v1beta1"}) {
t.Errorf("expected: %q, got: %q", []string{"v1", "extensions/v1beta1"}, groupVersions)
}
}
func TestGetServerGroupsWithBrokenServer(t *testing.T) {
for _, statusCode := range []int{http.StatusNotFound, http.StatusForbidden} {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(statusCode)
}))
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
// ServerGroups should not return an error even if server returns Not Found or Forbidden error at all end points
apiGroupList, err := client.ServerGroups()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
groupVersions := metav1.ExtractGroupVersions(apiGroupList)
if len(groupVersions) != 0 {
t.Errorf("expected empty list, got: %q", groupVersions)
}
}
}
func TestTimeoutIsSet(t *testing.T) {
cfg := &restclient.Config{}
setDiscoveryDefaults(cfg)
assert.Equal(t, defaultTimeout, cfg.Timeout)
}
func TestGetServerResourcesWithV1Server(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
var obj interface{}
switch req.URL.Path {
case "/api":
obj = &metav1.APIVersions{
Versions: []string{
"v1",
},
}
default:
w.WriteHeader(http.StatusNotFound)
return
}
output, err := json.Marshal(obj)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(output)
}))
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
// ServerResources should not return an error even if server returns error at /api/v1.
serverResources, err := client.ServerResources()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
gvs := groupVersions(serverResources)
if !sets.NewString(gvs...).Has("v1") {
t.Errorf("missing v1 in resource list: %v", serverResources)
}
}
func TestGetServerResources(t *testing.T) {
stable := metav1.APIResourceList{
GroupVersion: "v1",
APIResources: []metav1.APIResource{
{Name: "pods", Namespaced: true, Kind: "Pod"},
{Name: "services", Namespaced: true, Kind: "Service"},
{Name: "namespaces", Namespaced: false, Kind: "Namespace"},
},
}
beta := metav1.APIResourceList{
GroupVersion: "extensions/v1beta1",
APIResources: []metav1.APIResource{
{Name: "deployments", Namespaced: true, Kind: "Deployment"},
{Name: "ingresses", Namespaced: true, Kind: "Ingress"},
{Name: "jobs", Namespaced: true, Kind: "Job"},
},
}
beta2 := metav1.APIResourceList{
GroupVersion: "extensions/v1beta2",
APIResources: []metav1.APIResource{
{Name: "deployments", Namespaced: true, Kind: "Deployment"},
{Name: "ingresses", Namespaced: true, Kind: "Ingress"},
{Name: "jobs", Namespaced: true, Kind: "Job"},
},
}
tests := []struct {
resourcesList *metav1.APIResourceList
path string
request string
expectErr bool
}{
{
resourcesList: &stable,
path: "/api/v1",
request: "v1",
expectErr: false,
},
{
resourcesList: &beta,
path: "/apis/extensions/v1beta1",
request: "extensions/v1beta1",
expectErr: false,
},
{
resourcesList: &stable,
path: "/api/v1",
request: "foobar",
expectErr: true,
},
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
var list interface{}
switch req.URL.Path {
case "/api/v1":
list = &stable
case "/apis/extensions/v1beta1":
list = &beta
case "/apis/extensions/v1beta2":
list = &beta2
case "/api":
list = &metav1.APIVersions{
Versions: []string{
"v1",
},
}
case "/apis":
list = &metav1.APIGroupList{
Groups: []metav1.APIGroup{
{
Name: "extensions",
Versions: []metav1.GroupVersionForDiscovery{
{GroupVersion: "extensions/v1beta1", Version: "v1beta1"},
{GroupVersion: "extensions/v1beta2", Version: "v1beta2"},
},
},
},
}
default:
t.Logf("unexpected request: %s", req.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
output, err := json.Marshal(list)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(output)
}))
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
for _, test := range tests {
got, err := client.ServerResourcesForGroupVersion(test.request)
if test.expectErr {
if err == nil {
t.Error("unexpected non-error")
}
continue
}
if err != nil {
t.Errorf("unexpected error: %v", err)
continue
}
if !reflect.DeepEqual(got, test.resourcesList) {
t.Errorf("expected:\n%v\ngot:\n%v\n", test.resourcesList, got)
}
}
serverResources, err := client.ServerResources()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
serverGroupVersions := groupVersions(serverResources)
expectedGroupVersions := []string{"v1", "extensions/v1beta1", "extensions/v1beta2"}
if !reflect.DeepEqual(expectedGroupVersions, serverGroupVersions) {
t.Errorf("unexpected group versions: %v", diff.ObjectReflectDiff(expectedGroupVersions, serverGroupVersions))
}
}
var returnedOpenAPI = openapi_v2.Document{
Definitions: &openapi_v2.Definitions{
AdditionalProperties: []*openapi_v2.NamedSchema{
{
Name: "fake.type.1",
Value: &openapi_v2.Schema{
Properties: &openapi_v2.Properties{
AdditionalProperties: []*openapi_v2.NamedSchema{
{
Name: "count",
Value: &openapi_v2.Schema{
Type: &openapi_v2.TypeItem{
Value: []string{"integer"},
},
},
},
},
},
},
},
{
Name: "fake.type.2",
Value: &openapi_v2.Schema{
Properties: &openapi_v2.Properties{
AdditionalProperties: []*openapi_v2.NamedSchema{
{
Name: "count",
Value: &openapi_v2.Schema{
Type: &openapi_v2.TypeItem{
Value: []string{"array"},
},
Items: &openapi_v2.ItemsItem{
Schema: []*openapi_v2.Schema{
{
Type: &openapi_v2.TypeItem{
Value: []string{"string"},
},
},
},
},
},
},
},
},
},
},
},
},
}
func openapiSchemaDeprecatedFakeServer(status int) (*httptest.Server, error) {
var sErr error
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/openapi/v2" {
// write the error status for the new endpoint request
w.WriteHeader(status)
return
}
if req.URL.Path != "/swagger-2.0.0.pb-v1" {
sErr = fmt.Errorf("Unexpected url %v", req.URL)
}
if req.Method != "GET" {
sErr = fmt.Errorf("Unexpected method %v", req.Method)
}
mime.AddExtensionType(".pb-v1", "application/com.github.googleapis.gnostic.OpenAPIv2@68f4ded+protobuf")
output, err := proto.Marshal(&returnedOpenAPI)
if err != nil {
sErr = err
return
}
w.WriteHeader(http.StatusOK)
w.Write(output)
}))
return server, sErr
}
func openapiSchemaFakeServer() (*httptest.Server, error) {
var sErr error
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/openapi/v2" {
sErr = fmt.Errorf("Unexpected url %v", req.URL)
}
if req.Method != "GET" {
sErr = fmt.Errorf("Unexpected method %v", req.Method)
}
decipherableFormat := req.Header.Get("Accept")
if decipherableFormat != "application/com.github.proto-openapi.spec.v2@v1.0+protobuf" {
sErr = fmt.Errorf("Unexpected accept mime type %v", decipherableFormat)
}
mime.AddExtensionType(".pb-v1", "application/com.github.googleapis.gnostic.OpenAPIv2@68f4ded+protobuf")
output, err := proto.Marshal(&returnedOpenAPI)
if err != nil {
sErr = err
return
}
w.WriteHeader(http.StatusOK)
w.Write(output)
}))
return server, sErr
}
func TestGetOpenAPISchema(t *testing.T) {
server, err := openapiSchemaFakeServer()
if err != nil {
t.Errorf("unexpected error starting fake server: %v", err)
}
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
got, err := client.OpenAPISchema()
if err != nil {
t.Fatalf("unexpected error getting openapi: %v", err)
}
if e, a := returnedOpenAPI, *got; !reflect.DeepEqual(e, a) {
t.Errorf("expected %v, got %v", e, a)
}
}
func TestGetOpenAPISchemaForbiddenFallback(t *testing.T) {
server, err := openapiSchemaDeprecatedFakeServer(http.StatusForbidden)
if err != nil {
t.Errorf("unexpected error starting fake server: %v", err)
}
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
got, err := client.OpenAPISchema()
if err != nil {
t.Fatalf("unexpected error getting openapi: %v", err)
}
if e, a := returnedOpenAPI, *got; !reflect.DeepEqual(e, a) {
t.Errorf("expected %v, got %v", e, a)
}
}
func TestGetOpenAPISchemaNotFoundFallback(t *testing.T) {
server, err := openapiSchemaDeprecatedFakeServer(http.StatusNotFound)
if err != nil {
t.Errorf("unexpected error starting fake server: %v", err)
}
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
got, err := client.OpenAPISchema()
if err != nil {
t.Fatalf("unexpected error getting openapi: %v", err)
}
if e, a := returnedOpenAPI, *got; !reflect.DeepEqual(e, a) {
t.Errorf("expected %v, got %v", e, a)
}
}
func TestGetOpenAPISchemaNotAcceptableFallback(t *testing.T) {
server, err := openapiSchemaDeprecatedFakeServer(http.StatusNotAcceptable)
if err != nil {
t.Errorf("unexpected error starting fake server: %v", err)
}
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
got, err := client.OpenAPISchema()
if err != nil {
t.Fatalf("unexpected error getting openapi: %v", err)
}
if e, a := returnedOpenAPI, *got; !reflect.DeepEqual(e, a) {
t.Errorf("expected %v, got %v", e, a)
}
}
func TestServerPreferredResources(t *testing.T) {
stable := metav1.APIResourceList{
GroupVersion: "v1",
APIResources: []metav1.APIResource{
{Name: "pods", Namespaced: true, Kind: "Pod"},
{Name: "services", Namespaced: true, Kind: "Service"},
{Name: "namespaces", Namespaced: false, Kind: "Namespace"},
},
}
tests := []struct {
resourcesList []*metav1.APIResourceList
response func(w http.ResponseWriter, req *http.Request)
expectErr func(err error) bool
}{
{
resourcesList: []*metav1.APIResourceList{&stable},
expectErr: IsGroupDiscoveryFailedError,
response: func(w http.ResponseWriter, req *http.Request) {
var list interface{}
switch req.URL.Path {
case "/apis/extensions/v1beta1":
w.WriteHeader(http.StatusInternalServerError)
return
case "/api/v1":
list = &stable
case "/api":
list = &metav1.APIVersions{
Versions: []string{
"v1",
},
}
case "/apis":
list = &metav1.APIGroupList{
Groups: []metav1.APIGroup{
{
Versions: []metav1.GroupVersionForDiscovery{
{GroupVersion: "extensions/v1beta1"},
},
},
},
}
default:
t.Logf("unexpected request: %s", req.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
output, err := json.Marshal(list)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(output)
},
},
{
resourcesList: nil,
expectErr: IsGroupDiscoveryFailedError,
response: func(w http.ResponseWriter, req *http.Request) {
var list interface{}
switch req.URL.Path {
case "/apis/extensions/v1beta1":
w.WriteHeader(http.StatusInternalServerError)
return
case "/api/v1":
w.WriteHeader(http.StatusInternalServerError)
case "/api":
list = &metav1.APIVersions{
Versions: []string{
"v1",
},
}
case "/apis":
list = &metav1.APIGroupList{
Groups: []metav1.APIGroup{
{
Versions: []metav1.GroupVersionForDiscovery{
{GroupVersion: "extensions/v1beta1"},
},
},
},
}
default:
t.Logf("unexpected request: %s", req.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
output, err := json.Marshal(list)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(output)
},
},
}
for _, test := range tests {
server := httptest.NewServer(http.HandlerFunc(test.response))
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
resources, err := client.ServerPreferredResources()
if test.expectErr != nil {
if err == nil {
t.Error("unexpected non-error")
}
continue
}
if err != nil {
t.Errorf("unexpected error: %v", err)
continue
}
got, err := GroupVersionResources(resources)
if err != nil {
t.Errorf("unexpected error: %v", err)
continue
}
expected, _ := GroupVersionResources(test.resourcesList)
if !reflect.DeepEqual(got, expected) {
t.Errorf("expected:\n%v\ngot:\n%v\n", test.resourcesList, got)
}
server.Close()
}
}
func TestServerPreferredResourcesRetries(t *testing.T) {
stable := metav1.APIResourceList{
GroupVersion: "v1",
APIResources: []metav1.APIResource{
{Name: "pods", Namespaced: true, Kind: "Pod"},
},
}
beta := metav1.APIResourceList{
GroupVersion: "extensions/v1",
APIResources: []metav1.APIResource{
{Name: "deployments", Namespaced: true, Kind: "Deployment"},
},
}
response := func(numErrors int) http.HandlerFunc {
var i = 0
return func(w http.ResponseWriter, req *http.Request) {
var list interface{}
switch req.URL.Path {
case "/apis/extensions/v1beta1":
if i < numErrors {
i++
w.WriteHeader(http.StatusInternalServerError)
return
}
list = &beta
case "/api/v1":
list = &stable
case "/api":
list = &metav1.APIVersions{
Versions: []string{
"v1",
},
}
case "/apis":
list = &metav1.APIGroupList{
Groups: []metav1.APIGroup{
{
Name: "extensions",
Versions: []metav1.GroupVersionForDiscovery{
{GroupVersion: "extensions/v1beta1", Version: "v1beta1"},
},
PreferredVersion: metav1.GroupVersionForDiscovery{
GroupVersion: "extensions/v1beta1",
Version: "v1beta1",
},
},
},
}
default:
t.Logf("unexpected request: %s", req.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
output, err := json.Marshal(list)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(output)
}
}
tests := []struct {
responseErrors int
expectResources int
expectedError func(err error) bool
}{
{
responseErrors: 1,
expectResources: 2,
expectedError: func(err error) bool {
return err == nil
},
},
{
responseErrors: 2,
expectResources: 1,
expectedError: IsGroupDiscoveryFailedError,
},
}
for i, tc := range tests {
server := httptest.NewServer(http.HandlerFunc(response(tc.responseErrors)))
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
resources, err := client.ServerPreferredResources()
if !tc.expectedError(err) {
t.Errorf("case %d: unexpected error: %v", i, err)
}
got, err := GroupVersionResources(resources)
if err != nil {
t.Errorf("case %d: unexpected error: %v", i, err)
}
if len(got) != tc.expectResources {
t.Errorf("case %d: expect %d resources, got %#v", i, tc.expectResources, got)
}
server.Close()
}
}
func TestServerPreferredNamespacedResources(t *testing.T) {
stable := metav1.APIResourceList{
GroupVersion: "v1",
APIResources: []metav1.APIResource{
{Name: "pods", Namespaced: true, Kind: "Pod"},
{Name: "services", Namespaced: true, Kind: "Service"},
{Name: "namespaces", Namespaced: false, Kind: "Namespace"},
},
}
batchv1 := metav1.APIResourceList{
GroupVersion: "batch/v1",
APIResources: []metav1.APIResource{
{Name: "jobs", Namespaced: true, Kind: "Job"},
},
}
batchv2alpha1 := metav1.APIResourceList{
GroupVersion: "batch/v2alpha1",
APIResources: []metav1.APIResource{
{Name: "jobs", Namespaced: true, Kind: "Job"},
{Name: "cronjobs", Namespaced: true, Kind: "CronJob"},
},
}
batchv3alpha1 := metav1.APIResourceList{
GroupVersion: "batch/v3alpha1",
APIResources: []metav1.APIResource{
{Name: "jobs", Namespaced: true, Kind: "Job"},
{Name: "cronjobs", Namespaced: true, Kind: "CronJob"},
},
}
tests := []struct {
response func(w http.ResponseWriter, req *http.Request)
expected map[schema.GroupVersionResource]struct{}
}{
{
response: func(w http.ResponseWriter, req *http.Request) {
var list interface{}
switch req.URL.Path {
case "/api/v1":
list = &stable
case "/api":
list = &metav1.APIVersions{
Versions: []string{
"v1",
},
}
default:
t.Logf("unexpected request: %s", req.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
output, err := json.Marshal(list)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(output)
},
expected: map[schema.GroupVersionResource]struct{}{
{Group: "", Version: "v1", Resource: "pods"}: {},
{Group: "", Version: "v1", Resource: "services"}: {},
},
},
{
response: func(w http.ResponseWriter, req *http.Request) {
var list interface{}
switch req.URL.Path {
case "/apis":
list = &metav1.APIGroupList{
Groups: []metav1.APIGroup{
{
Name: "batch",
Versions: []metav1.GroupVersionForDiscovery{
{GroupVersion: "batch/v1", Version: "v1"},
{GroupVersion: "batch/v2alpha1", Version: "v2alpha1"},
{GroupVersion: "batch/v3alpha1", Version: "v3alpha1"},
},
PreferredVersion: metav1.GroupVersionForDiscovery{GroupVersion: "batch/v1", Version: "v1"},
},
},
}
case "/apis/batch/v1":
list = &batchv1
case "/apis/batch/v2alpha1":
list = &batchv2alpha1
case "/apis/batch/v3alpha1":
list = &batchv3alpha1
default:
t.Logf("unexpected request: %s", req.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
output, err := json.Marshal(list)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(output)
},
expected: map[schema.GroupVersionResource]struct{}{
{Group: "batch", Version: "v1", Resource: "jobs"}: {},
{Group: "batch", Version: "v2alpha1", Resource: "cronjobs"}: {},
},
},
{
response: func(w http.ResponseWriter, req *http.Request) {
var list interface{}
switch req.URL.Path {
case "/apis":
list = &metav1.APIGroupList{
Groups: []metav1.APIGroup{
{
Name: "batch",
Versions: []metav1.GroupVersionForDiscovery{
{GroupVersion: "batch/v1", Version: "v1"},
{GroupVersion: "batch/v2alpha1", Version: "v2alpha1"},
{GroupVersion: "batch/v3alpha1", Version: "v3alpha1"},
},
PreferredVersion: metav1.GroupVersionForDiscovery{GroupVersion: "batch/v2alpha", Version: "v2alpha1"},
},
},
}
case "/apis/batch/v1":
list = &batchv1
case "/apis/batch/v2alpha1":
list = &batchv2alpha1
case "/apis/batch/v3alpha1":
list = &batchv3alpha1
default:
t.Logf("unexpected request: %s", req.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
output, err := json.Marshal(list)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(output)
},
expected: map[schema.GroupVersionResource]struct{}{
{Group: "batch", Version: "v2alpha1", Resource: "jobs"}: {},
{Group: "batch", Version: "v2alpha1", Resource: "cronjobs"}: {},
},
},
}
for i, test := range tests {
server := httptest.NewServer(http.HandlerFunc(test.response))
defer server.Close()
client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
resources, err := client.ServerPreferredNamespacedResources()
if err != nil {
t.Errorf("[%d] unexpected error: %v", i, err)
continue
}
got, err := GroupVersionResources(resources)
if err != nil {
t.Errorf("[%d] unexpected error: %v", i, err)
continue
}
if !reflect.DeepEqual(got, test.expected) {
t.Errorf("[%d] expected:\n%v\ngot:\n%v\n", i, test.expected, got)
}
server.Close()
}
}
func groupVersions(resources []*metav1.APIResourceList) []string {
result := []string{}
for _, resourceList := range resources {
result = append(result, resourceList.GroupVersion)
}
return result
}

View File

@@ -1,46 +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 fake_test
import (
"testing"
"k8s.io/apimachinery/pkg/version"
fakediscovery "k8s.io/client-go/discovery/fake"
fakeclientset "k8s.io/client-go/kubernetes/fake"
)
func TestFakingServerVersion(t *testing.T) {
client := fakeclientset.NewSimpleClientset()
fakeDiscovery, ok := client.Discovery().(*fakediscovery.FakeDiscovery)
if !ok {
t.Fatalf("couldn't convert Discovery() to *FakeDiscovery")
}
testGitCommit := "v1.0.0"
fakeDiscovery.FakedServerVersion = &version.Info{
GitCommit: testGitCommit,
}
sv, err := client.Discovery().ServerVersion()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if sv.GitCommit != testGitCommit {
t.Fatalf("unexpected faked discovery return value: %q", sv.GitCommit)
}
}

View File

@@ -1,184 +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 discovery_test
import (
"bytes"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"strings"
"testing"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/discovery"
"k8s.io/client-go/kubernetes/scheme"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/rest/fake"
)
func objBody(object interface{}) io.ReadCloser {
output, err := json.MarshalIndent(object, "", "")
if err != nil {
panic(err)
}
return ioutil.NopCloser(bytes.NewReader([]byte(output)))
}
func TestServerSupportsVersion(t *testing.T) {
tests := []struct {
name string
requiredVersion schema.GroupVersion
serverVersions []string
expectErr func(err error) bool
sendErr error
statusCode int
}{
{
name: "explicit version supported",
requiredVersion: schema.GroupVersion{Version: "v1"},
serverVersions: []string{"/version1", v1.SchemeGroupVersion.String()},
statusCode: http.StatusOK,
},
{
name: "explicit version not supported on server",
requiredVersion: schema.GroupVersion{Version: "v1"},
serverVersions: []string{"version1"},
expectErr: func(err error) bool { return strings.Contains(err.Error(), `server does not support API version "v1"`) },
statusCode: http.StatusOK,
},
{
name: "connection refused error",
serverVersions: []string{"version1"},
sendErr: errors.New("connection refused"),
expectErr: func(err error) bool { return strings.Contains(err.Error(), "connection refused") },
statusCode: http.StatusOK,
},
{
name: "discovery fails due to 404 Not Found errors and thus serverVersions is empty, use requested GroupVersion",
requiredVersion: schema.GroupVersion{Version: "version1"},
statusCode: http.StatusNotFound,
},
}
for _, test := range tests {
fakeClient := &fake.RESTClient{
NegotiatedSerializer: scheme.Codecs,
Resp: &http.Response{
StatusCode: test.statusCode,
Body: objBody(&metav1.APIVersions{Versions: test.serverVersions}),
},
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
if test.sendErr != nil {
return nil, test.sendErr
}
header := http.Header{}
header.Set("Content-Type", runtime.ContentTypeJSON)
return &http.Response{StatusCode: test.statusCode, Header: header, Body: objBody(&metav1.APIVersions{Versions: test.serverVersions})}, nil
}),
}
c := discovery.NewDiscoveryClientForConfigOrDie(&restclient.Config{})
c.RESTClient().(*restclient.RESTClient).Client = fakeClient.Client
err := discovery.ServerSupportsVersion(c, test.requiredVersion)
if err == nil && test.expectErr != nil {
t.Errorf("expected error, got nil for [%s].", test.name)
}
if err != nil {
if test.expectErr == nil || !test.expectErr(err) {
t.Errorf("unexpected error for [%s]: %v.", test.name, err)
}
continue
}
}
}
func TestFilteredBy(t *testing.T) {
all := discovery.ResourcePredicateFunc(func(gv string, r *metav1.APIResource) bool {
return true
})
none := discovery.ResourcePredicateFunc(func(gv string, r *metav1.APIResource) bool {
return false
})
onlyV2 := discovery.ResourcePredicateFunc(func(gv string, r *metav1.APIResource) bool {
return strings.HasSuffix(gv, "/v2") || gv == "v2"
})
onlyBar := discovery.ResourcePredicateFunc(func(gv string, r *metav1.APIResource) bool {
return r.Kind == "Bar"
})
foo := []*metav1.APIResourceList{
{
GroupVersion: "foo/v1",
APIResources: []metav1.APIResource{
{Name: "bar", Kind: "Bar"},
{Name: "test", Kind: "Test"},
},
},
{
GroupVersion: "foo/v2",
APIResources: []metav1.APIResource{
{Name: "bar", Kind: "Bar"},
{Name: "test", Kind: "Test"},
},
},
{
GroupVersion: "foo/v3",
APIResources: []metav1.APIResource{},
},
}
tests := []struct {
input []*metav1.APIResourceList
pred discovery.ResourcePredicate
expectedResources []string
}{
{nil, all, []string{}},
{[]*metav1.APIResourceList{
{GroupVersion: "foo/v1"},
}, all, []string{}},
{foo, all, []string{"foo/v1.bar", "foo/v1.test", "foo/v2.bar", "foo/v2.test"}},
{foo, onlyV2, []string{"foo/v2.bar", "foo/v2.test"}},
{foo, onlyBar, []string{"foo/v1.bar", "foo/v2.bar"}},
{foo, none, []string{}},
}
for i, test := range tests {
filtered := discovery.FilteredBy(test.pred, test.input)
if expected, got := sets.NewString(test.expectedResources...), sets.NewString(stringify(filtered)...); !expected.Equal(got) {
t.Errorf("[%d] unexpected group versions: expected=%v, got=%v", i, test.expectedResources, stringify(filtered))
}
}
}
func stringify(rls []*metav1.APIResourceList) []string {
result := []string{}
for _, rl := range rls {
for _, r := range rl.APIResources {
result = append(result, rl.GroupVersion+"."+r.Name)
}
if len(rl.APIResources) == 0 {
result = append(result, rl.GroupVersion)
}
}
return result
}

View File

@@ -1,95 +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 discovery
import (
"bytes"
"io/ioutil"
"net/http"
"net/url"
"os"
"testing"
)
// copied from k8s.io/client-go/transport/round_trippers_test.go
type testRoundTripper struct {
Request *http.Request
Response *http.Response
Err error
}
func (rt *testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
rt.Request = req
return rt.Response, rt.Err
}
func TestCacheRoundTripper(t *testing.T) {
rt := &testRoundTripper{}
cacheDir, err := ioutil.TempDir("", "cache-rt")
defer os.RemoveAll(cacheDir)
if err != nil {
t.Fatal(err)
}
cache := newCacheRoundTripper(cacheDir, rt)
// First call, caches the response
req := &http.Request{
Method: http.MethodGet,
URL: &url.URL{Host: "localhost"},
}
rt.Response = &http.Response{
Header: http.Header{"ETag": []string{`"123456"`}},
Body: ioutil.NopCloser(bytes.NewReader([]byte("Content"))),
StatusCode: http.StatusOK,
}
resp, err := cache.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if string(content) != "Content" {
t.Errorf(`Expected Body to be "Content", got %q`, string(content))
}
// Second call, returns cached response
req = &http.Request{
Method: http.MethodGet,
URL: &url.URL{Host: "localhost"},
}
rt.Response = &http.Response{
StatusCode: http.StatusNotModified,
Body: ioutil.NopCloser(bytes.NewReader([]byte("Other Content"))),
}
resp, err = cache.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
// Read body and make sure we have the initial content
content, err = ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
t.Fatal(err)
}
if string(content) != "Content" {
t.Errorf("Invalid content read from cache %q", string(content))
}
}

View File

@@ -1,651 +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 dynamic
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer/streaming"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
restclient "k8s.io/client-go/rest"
restclientwatch "k8s.io/client-go/rest/watch"
)
func getJSON(version, kind, name string) []byte {
return []byte(fmt.Sprintf(`{"apiVersion": %q, "kind": %q, "metadata": {"name": %q}}`, version, kind, name))
}
func getListJSON(version, kind string, items ...[]byte) []byte {
json := fmt.Sprintf(`{"apiVersion": %q, "kind": %q, "items": [%s]}`,
version, kind, bytes.Join(items, []byte(",")))
return []byte(json)
}
func getObject(version, kind, name string) *unstructured.Unstructured {
return &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": version,
"kind": kind,
"metadata": map[string]interface{}{
"name": name,
},
},
}
}
func getClientServer(h func(http.ResponseWriter, *http.Request)) (Interface, *httptest.Server, error) {
srv := httptest.NewServer(http.HandlerFunc(h))
cl, err := NewForConfig(&restclient.Config{
Host: srv.URL,
})
if err != nil {
srv.Close()
return nil, nil, err
}
return cl, srv, nil
}
func TestList(t *testing.T) {
tcs := []struct {
name string
namespace string
path string
resp []byte
want *unstructured.UnstructuredList
}{
{
name: "normal_list",
path: "/apis/gtest/vtest/rtest",
resp: getListJSON("vTest", "rTestList",
getJSON("vTest", "rTest", "item1"),
getJSON("vTest", "rTest", "item2")),
want: &unstructured.UnstructuredList{
Object: map[string]interface{}{
"apiVersion": "vTest",
"kind": "rTestList",
},
Items: []unstructured.Unstructured{
*getObject("vTest", "rTest", "item1"),
*getObject("vTest", "rTest", "item2"),
},
},
},
{
name: "namespaced_list",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest",
resp: getListJSON("vTest", "rTestList",
getJSON("vTest", "rTest", "item1"),
getJSON("vTest", "rTest", "item2")),
want: &unstructured.UnstructuredList{
Object: map[string]interface{}{
"apiVersion": "vTest",
"kind": "rTestList",
},
Items: []unstructured.Unstructured{
*getObject("vTest", "rTest", "item1"),
*getObject("vTest", "rTest", "item2"),
},
},
},
}
for _, tc := range tcs {
resource := schema.GroupVersionResource{Group: "gtest", Version: "vtest", Resource: "rtest"}
cl, srv, err := getClientServer(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Errorf("List(%q) got HTTP method %s. wanted GET", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("List(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
w.Write(tc.resp)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
got, err := cl.Resource(resource).Namespace(tc.namespace).List(metav1.ListOptions{})
if err != nil {
t.Errorf("unexpected error when listing %q: %v", tc.name, err)
continue
}
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("List(%q) want: %v\ngot: %v", tc.name, tc.want, got)
}
}
}
func TestGet(t *testing.T) {
tcs := []struct {
resource string
subresource []string
namespace string
name string
path string
resp []byte
want *unstructured.Unstructured
}{
{
resource: "rtest",
name: "normal_get",
path: "/apis/gtest/vtest/rtest/normal_get",
resp: getJSON("vTest", "rTest", "normal_get"),
want: getObject("vTest", "rTest", "normal_get"),
},
{
resource: "rtest",
namespace: "nstest",
name: "namespaced_get",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_get",
resp: getJSON("vTest", "rTest", "namespaced_get"),
want: getObject("vTest", "rTest", "namespaced_get"),
},
{
resource: "rtest",
subresource: []string{"srtest"},
name: "normal_subresource_get",
path: "/apis/gtest/vtest/rtest/normal_subresource_get/srtest",
resp: getJSON("vTest", "srTest", "normal_subresource_get"),
want: getObject("vTest", "srTest", "normal_subresource_get"),
},
{
resource: "rtest",
subresource: []string{"srtest"},
namespace: "nstest",
name: "namespaced_subresource_get",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_subresource_get/srtest",
resp: getJSON("vTest", "srTest", "namespaced_subresource_get"),
want: getObject("vTest", "srTest", "namespaced_subresource_get"),
},
}
for _, tc := range tcs {
resource := schema.GroupVersionResource{Group: "gtest", Version: "vtest", Resource: tc.resource}
cl, srv, err := getClientServer(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Errorf("Get(%q) got HTTP method %s. wanted GET", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Get(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
w.Write(tc.resp)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
got, err := cl.Resource(resource).Namespace(tc.namespace).Get(tc.name, metav1.GetOptions{}, tc.subresource...)
if err != nil {
t.Errorf("unexpected error when getting %q: %v", tc.name, err)
continue
}
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("Get(%q) want: %v\ngot: %v", tc.name, tc.want, got)
}
}
}
func TestDelete(t *testing.T) {
background := metav1.DeletePropagationBackground
uid := types.UID("uid")
statusOK := &metav1.Status{
TypeMeta: metav1.TypeMeta{Kind: "Status"},
Status: metav1.StatusSuccess,
}
tcs := []struct {
subresource []string
namespace string
name string
path string
deleteOptions *metav1.DeleteOptions
}{
{
name: "normal_delete",
path: "/apis/gtest/vtest/rtest/normal_delete",
},
{
namespace: "nstest",
name: "namespaced_delete",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_delete",
},
{
subresource: []string{"srtest"},
name: "normal_delete",
path: "/apis/gtest/vtest/rtest/normal_delete/srtest",
},
{
subresource: []string{"srtest"},
namespace: "nstest",
name: "namespaced_delete",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_delete/srtest",
},
{
namespace: "nstest",
name: "namespaced_delete_with_options",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_delete_with_options",
deleteOptions: &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &uid}, PropagationPolicy: &background},
},
}
for _, tc := range tcs {
resource := schema.GroupVersionResource{Group: "gtest", Version: "vtest", Resource: "rtest"}
cl, srv, err := getClientServer(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "DELETE" {
t.Errorf("Delete(%q) got HTTP method %s. wanted DELETE", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Delete(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
unstructured.UnstructuredJSONScheme.Encode(statusOK, w)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
err = cl.Resource(resource).Namespace(tc.namespace).Delete(tc.name, tc.deleteOptions, tc.subresource...)
if err != nil {
t.Errorf("unexpected error when deleting %q: %v", tc.name, err)
continue
}
}
}
func TestDeleteCollection(t *testing.T) {
statusOK := &metav1.Status{
TypeMeta: metav1.TypeMeta{Kind: "Status"},
Status: metav1.StatusSuccess,
}
tcs := []struct {
namespace string
name string
path string
}{
{
name: "normal_delete_collection",
path: "/apis/gtest/vtest/rtest",
},
{
namespace: "nstest",
name: "namespaced_delete_collection",
path: "/apis/gtest/vtest/namespaces/nstest/rtest",
},
}
for _, tc := range tcs {
resource := schema.GroupVersionResource{Group: "gtest", Version: "vtest", Resource: "rtest"}
cl, srv, err := getClientServer(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "DELETE" {
t.Errorf("DeleteCollection(%q) got HTTP method %s. wanted DELETE", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("DeleteCollection(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
unstructured.UnstructuredJSONScheme.Encode(statusOK, w)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
err = cl.Resource(resource).Namespace(tc.namespace).DeleteCollection(nil, metav1.ListOptions{})
if err != nil {
t.Errorf("unexpected error when deleting collection %q: %v", tc.name, err)
continue
}
}
}
func TestCreate(t *testing.T) {
tcs := []struct {
resource string
subresource []string
name string
namespace string
obj *unstructured.Unstructured
path string
}{
{
resource: "rtest",
name: "normal_create",
path: "/apis/gtest/vtest/rtest",
obj: getObject("gtest/vTest", "rTest", "normal_create"),
},
{
resource: "rtest",
name: "namespaced_create",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest",
obj: getObject("gtest/vTest", "rTest", "namespaced_create"),
},
{
resource: "rtest",
subresource: []string{"srtest"},
name: "normal_subresource_create",
path: "/apis/gtest/vtest/rtest/normal_subresource_create/srtest",
obj: getObject("vTest", "srTest", "normal_subresource_create"),
},
{
resource: "rtest/",
subresource: []string{"srtest"},
name: "namespaced_subresource_create",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_subresource_create/srtest",
obj: getObject("vTest", "srTest", "namespaced_subresource_create"),
},
}
for _, tc := range tcs {
resource := schema.GroupVersionResource{Group: "gtest", Version: "vtest", Resource: tc.resource}
cl, srv, err := getClientServer(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
t.Errorf("Create(%q) got HTTP method %s. wanted POST", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Create(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
data, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Errorf("Create(%q) unexpected error reading body: %v", tc.name, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(data)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
got, err := cl.Resource(resource).Namespace(tc.namespace).Create(tc.obj, metav1.CreateOptions{}, tc.subresource...)
if err != nil {
t.Errorf("unexpected error when creating %q: %v", tc.name, err)
continue
}
if !reflect.DeepEqual(got, tc.obj) {
t.Errorf("Create(%q) want: %v\ngot: %v", tc.name, tc.obj, got)
}
}
}
func TestUpdate(t *testing.T) {
tcs := []struct {
resource string
subresource []string
name string
namespace string
obj *unstructured.Unstructured
path string
}{
{
resource: "rtest",
name: "normal_update",
path: "/apis/gtest/vtest/rtest/normal_update",
obj: getObject("gtest/vTest", "rTest", "normal_update"),
},
{
resource: "rtest",
name: "namespaced_update",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_update",
obj: getObject("gtest/vTest", "rTest", "namespaced_update"),
},
{
resource: "rtest",
subresource: []string{"srtest"},
name: "normal_subresource_update",
path: "/apis/gtest/vtest/rtest/normal_update/srtest",
obj: getObject("gtest/vTest", "srTest", "normal_update"),
},
{
resource: "rtest",
subresource: []string{"srtest"},
name: "namespaced_subresource_update",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_update/srtest",
obj: getObject("gtest/vTest", "srTest", "namespaced_update"),
},
}
for _, tc := range tcs {
resource := schema.GroupVersionResource{Group: "gtest", Version: "vtest", Resource: tc.resource}
cl, srv, err := getClientServer(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "PUT" {
t.Errorf("Update(%q) got HTTP method %s. wanted PUT", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Update(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
data, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Errorf("Update(%q) unexpected error reading body: %v", tc.name, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(data)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
got, err := cl.Resource(resource).Namespace(tc.namespace).Update(tc.obj, metav1.UpdateOptions{}, tc.subresource...)
if err != nil {
t.Errorf("unexpected error when updating %q: %v", tc.name, err)
continue
}
if !reflect.DeepEqual(got, tc.obj) {
t.Errorf("Update(%q) want: %v\ngot: %v", tc.name, tc.obj, got)
}
}
}
func TestWatch(t *testing.T) {
tcs := []struct {
name string
namespace string
events []watch.Event
path string
query string
}{
{
name: "normal_watch",
path: "/apis/gtest/vtest/rtest",
query: "watch=true",
events: []watch.Event{
{Type: watch.Added, Object: getObject("gtest/vTest", "rTest", "normal_watch")},
{Type: watch.Modified, Object: getObject("gtest/vTest", "rTest", "normal_watch")},
{Type: watch.Deleted, Object: getObject("gtest/vTest", "rTest", "normal_watch")},
},
},
{
name: "namespaced_watch",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest",
query: "watch=true",
events: []watch.Event{
{Type: watch.Added, Object: getObject("gtest/vTest", "rTest", "namespaced_watch")},
{Type: watch.Modified, Object: getObject("gtest/vTest", "rTest", "namespaced_watch")},
{Type: watch.Deleted, Object: getObject("gtest/vTest", "rTest", "namespaced_watch")},
},
},
}
for _, tc := range tcs {
resource := schema.GroupVersionResource{Group: "gtest", Version: "vtest", Resource: "rtest"}
cl, srv, err := getClientServer(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Errorf("Watch(%q) got HTTP method %s. wanted GET", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Watch(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
if r.URL.RawQuery != tc.query {
t.Errorf("Watch(%q) got query %s. wanted %s", tc.name, r.URL.RawQuery, tc.query)
}
enc := restclientwatch.NewEncoder(streaming.NewEncoder(w, unstructured.UnstructuredJSONScheme), unstructured.UnstructuredJSONScheme)
for _, e := range tc.events {
enc.Encode(&e)
}
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
watcher, err := cl.Resource(resource).Namespace(tc.namespace).Watch(metav1.ListOptions{})
if err != nil {
t.Errorf("unexpected error when watching %q: %v", tc.name, err)
continue
}
for _, want := range tc.events {
got := <-watcher.ResultChan()
if !reflect.DeepEqual(got, want) {
t.Errorf("Watch(%q) want: %v\ngot: %v", tc.name, want, got)
}
}
}
}
func TestPatch(t *testing.T) {
tcs := []struct {
resource string
subresource []string
name string
namespace string
patch []byte
want *unstructured.Unstructured
path string
}{
{
resource: "rtest",
name: "normal_patch",
path: "/apis/gtest/vtest/rtest/normal_patch",
patch: getJSON("gtest/vTest", "rTest", "normal_patch"),
want: getObject("gtest/vTest", "rTest", "normal_patch"),
},
{
resource: "rtest",
name: "namespaced_patch",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_patch",
patch: getJSON("gtest/vTest", "rTest", "namespaced_patch"),
want: getObject("gtest/vTest", "rTest", "namespaced_patch"),
},
{
resource: "rtest",
subresource: []string{"srtest"},
name: "normal_subresource_patch",
path: "/apis/gtest/vtest/rtest/normal_subresource_patch/srtest",
patch: getJSON("gtest/vTest", "srTest", "normal_subresource_patch"),
want: getObject("gtest/vTest", "srTest", "normal_subresource_patch"),
},
{
resource: "rtest",
subresource: []string{"srtest"},
name: "namespaced_subresource_patch",
namespace: "nstest",
path: "/apis/gtest/vtest/namespaces/nstest/rtest/namespaced_subresource_patch/srtest",
patch: getJSON("gtest/vTest", "srTest", "namespaced_subresource_patch"),
want: getObject("gtest/vTest", "srTest", "namespaced_subresource_patch"),
},
}
for _, tc := range tcs {
resource := schema.GroupVersionResource{Group: "gtest", Version: "vtest", Resource: tc.resource}
cl, srv, err := getClientServer(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "PATCH" {
t.Errorf("Patch(%q) got HTTP method %s. wanted PATCH", tc.name, r.Method)
}
if r.URL.Path != tc.path {
t.Errorf("Patch(%q) got path %s. wanted %s", tc.name, r.URL.Path, tc.path)
}
content := r.Header.Get("Content-Type")
if content != string(types.StrategicMergePatchType) {
t.Errorf("Patch(%q) got Content-Type %s. wanted %s", tc.name, content, types.StrategicMergePatchType)
}
data, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Errorf("Patch(%q) unexpected error reading body: %v", tc.name, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
})
if err != nil {
t.Errorf("unexpected error when creating client: %v", err)
continue
}
defer srv.Close()
got, err := cl.Resource(resource).Namespace(tc.namespace).Patch(tc.name, types.StrategicMergePatchType, tc.patch, metav1.UpdateOptions{}, tc.subresource...)
if err != nil {
t.Errorf("unexpected error when patching %q: %v", tc.name, err)
continue
}
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("Patch(%q) want: %v\ngot: %v", tc.name, tc.want, got)
}
}
}

View File

@@ -1,155 +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 dynamicinformer
import (
"sync"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/dynamic/dynamiclister"
"k8s.io/client-go/informers"
"k8s.io/client-go/tools/cache"
)
// NewDynamicSharedInformerFactory constructs a new instance of dynamicSharedInformerFactory for all namespaces.
func NewDynamicSharedInformerFactory(client dynamic.Interface, defaultResync time.Duration) DynamicSharedInformerFactory {
return NewFilteredDynamicSharedInformerFactory(client, defaultResync, metav1.NamespaceAll, nil)
}
// NewFilteredDynamicSharedInformerFactory constructs a new instance of dynamicSharedInformerFactory.
// Listers obtained via this factory will be subject to the same filters as specified here.
func NewFilteredDynamicSharedInformerFactory(client dynamic.Interface, defaultResync time.Duration, namespace string, tweakListOptions TweakListOptionsFunc) DynamicSharedInformerFactory {
return &dynamicSharedInformerFactory{
client: client,
defaultResync: defaultResync,
namespace: metav1.NamespaceAll,
informers: map[schema.GroupVersionResource]informers.GenericInformer{},
startedInformers: make(map[schema.GroupVersionResource]bool),
}
}
type dynamicSharedInformerFactory struct {
client dynamic.Interface
defaultResync time.Duration
namespace string
lock sync.Mutex
informers map[schema.GroupVersionResource]informers.GenericInformer
// startedInformers is used for tracking which informers have been started.
// This allows Start() to be called multiple times safely.
startedInformers map[schema.GroupVersionResource]bool
}
var _ DynamicSharedInformerFactory = &dynamicSharedInformerFactory{}
func (f *dynamicSharedInformerFactory) ForResource(gvr schema.GroupVersionResource) informers.GenericInformer {
f.lock.Lock()
defer f.lock.Unlock()
key := gvr
informer, exists := f.informers[key]
if exists {
return informer
}
informer = NewFilteredDynamicInformer(f.client, gvr, f.namespace, f.defaultResync, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, nil)
f.informers[key] = informer
return informer
}
// Start initializes all requested informers.
func (f *dynamicSharedInformerFactory) Start(stopCh <-chan struct{}) {
f.lock.Lock()
defer f.lock.Unlock()
for informerType, informer := range f.informers {
if !f.startedInformers[informerType] {
go informer.Informer().Run(stopCh)
f.startedInformers[informerType] = true
}
}
}
// WaitForCacheSync waits for all started informers' cache were synced.
func (f *dynamicSharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[schema.GroupVersionResource]bool {
informers := func() map[schema.GroupVersionResource]cache.SharedIndexInformer {
f.lock.Lock()
defer f.lock.Unlock()
informers := map[schema.GroupVersionResource]cache.SharedIndexInformer{}
for informerType, informer := range f.informers {
if f.startedInformers[informerType] {
informers[informerType] = informer.Informer()
}
}
return informers
}()
res := map[schema.GroupVersionResource]bool{}
for informType, informer := range informers {
res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced)
}
return res
}
// NewFilteredDynamicInformer constructs a new informer for a dynamic type.
func NewFilteredDynamicInformer(client dynamic.Interface, gvr schema.GroupVersionResource, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions TweakListOptionsFunc) informers.GenericInformer {
return &dynamicInformer{
gvr: gvr,
informer: cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.Resource(gvr).Namespace(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.Resource(gvr).Namespace(namespace).Watch(options)
},
},
&unstructured.Unstructured{},
resyncPeriod,
indexers,
),
}
}
type dynamicInformer struct {
informer cache.SharedIndexInformer
gvr schema.GroupVersionResource
}
var _ informers.GenericInformer = &dynamicInformer{}
func (d *dynamicInformer) Informer() cache.SharedIndexInformer {
return d.informer
}
func (d *dynamicInformer) Lister() cache.GenericLister {
return dynamiclister.NewRuntimeObjectShim(dynamiclister.New(d.informer.GetIndexer(), d.gvr))
}

View File

@@ -1,160 +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 dynamicinformer_test
import (
"context"
"testing"
"time"
"k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/diff"
"k8s.io/client-go/dynamic/dynamicinformer"
"k8s.io/client-go/dynamic/fake"
"k8s.io/client-go/tools/cache"
)
func TestDynamicSharedInformerFactory(t *testing.T) {
scenarios := []struct {
name string
existingObj *unstructured.Unstructured
gvr schema.GroupVersionResource
ns string
trigger func(gvr schema.GroupVersionResource, ns string, fakeClient *fake.FakeDynamicClient, testObject *unstructured.Unstructured) *unstructured.Unstructured
handler func(rcvCh chan<- *unstructured.Unstructured) *cache.ResourceEventHandlerFuncs
}{
// scenario 1
{
name: "scenario 1: test if adding an object triggers AddFunc",
ns: "ns-foo",
gvr: schema.GroupVersionResource{Group: "extensions", Version: "v1beta1", Resource: "deployments"},
trigger: func(gvr schema.GroupVersionResource, ns string, fakeClient *fake.FakeDynamicClient, _ *unstructured.Unstructured) *unstructured.Unstructured {
testObject := newUnstructured("extensions/v1beta1", "Deployment", "ns-foo", "name-foo")
createdObj, err := fakeClient.Resource(gvr).Namespace(ns).Create(testObject, metav1.CreateOptions{})
if err != nil {
t.Error(err)
}
return createdObj
},
handler: func(rcvCh chan<- *unstructured.Unstructured) *cache.ResourceEventHandlerFuncs {
return &cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
rcvCh <- obj.(*unstructured.Unstructured)
},
}
},
},
// scenario 2
{
name: "scenario 2: tests if updating an object triggers UpdateFunc",
ns: "ns-foo",
gvr: schema.GroupVersionResource{Group: "extensions", Version: "v1beta1", Resource: "deployments"},
existingObj: newUnstructured("extensions/v1beta1", "Deployment", "ns-foo", "name-foo"),
trigger: func(gvr schema.GroupVersionResource, ns string, fakeClient *fake.FakeDynamicClient, testObject *unstructured.Unstructured) *unstructured.Unstructured {
testObject.Object["spec"] = "updatedName"
updatedObj, err := fakeClient.Resource(gvr).Namespace(ns).Update(testObject, metav1.UpdateOptions{})
if err != nil {
t.Error(err)
}
return updatedObj
},
handler: func(rcvCh chan<- *unstructured.Unstructured) *cache.ResourceEventHandlerFuncs {
return &cache.ResourceEventHandlerFuncs{
UpdateFunc: func(old, updated interface{}) {
rcvCh <- updated.(*unstructured.Unstructured)
},
}
},
},
// scenario 3
{
name: "scenario 3: test if deleting an object triggers DeleteFunc",
ns: "ns-foo",
gvr: schema.GroupVersionResource{Group: "extensions", Version: "v1beta1", Resource: "deployments"},
existingObj: newUnstructured("extensions/v1beta1", "Deployment", "ns-foo", "name-foo"),
trigger: func(gvr schema.GroupVersionResource, ns string, fakeClient *fake.FakeDynamicClient, testObject *unstructured.Unstructured) *unstructured.Unstructured {
err := fakeClient.Resource(gvr).Namespace(ns).Delete(testObject.GetName(), &metav1.DeleteOptions{})
if err != nil {
t.Error(err)
}
return testObject
},
handler: func(rcvCh chan<- *unstructured.Unstructured) *cache.ResourceEventHandlerFuncs {
return &cache.ResourceEventHandlerFuncs{
DeleteFunc: func(obj interface{}) {
rcvCh <- obj.(*unstructured.Unstructured)
},
}
},
},
}
for _, ts := range scenarios {
t.Run(ts.name, func(t *testing.T) {
// test data
timeout := time.Duration(3 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
scheme := runtime.NewScheme()
informerReciveObjectCh := make(chan *unstructured.Unstructured, 1)
objs := []runtime.Object{}
if ts.existingObj != nil {
objs = append(objs, ts.existingObj)
}
fakeClient := fake.NewSimpleDynamicClient(scheme, objs...)
target := dynamicinformer.NewDynamicSharedInformerFactory(fakeClient, 0)
// act
informerListerForGvr := target.ForResource(ts.gvr)
informerListerForGvr.Informer().AddEventHandler(ts.handler(informerReciveObjectCh))
target.Start(ctx.Done())
if synced := target.WaitForCacheSync(ctx.Done()); !synced[ts.gvr] {
t.Errorf("informer for %s hasn't synced", ts.gvr)
}
testObject := ts.trigger(ts.gvr, ts.ns, fakeClient, ts.existingObj)
select {
case objFromInformer := <-informerReciveObjectCh:
if !equality.Semantic.DeepEqual(testObject, objFromInformer) {
t.Fatalf("%v", diff.ObjectDiff(testObject, objFromInformer))
}
case <-ctx.Done():
t.Errorf("tested informer haven't received an object, waited %v", timeout)
}
})
}
}
func newUnstructured(apiVersion, kind, namespace, name string) *unstructured.Unstructured {
return &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": apiVersion,
"kind": kind,
"metadata": map[string]interface{}{
"namespace": namespace,
"name": name,
},
"spec": name,
},
}
}

View File

@@ -1,34 +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 dynamicinformer
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/informers"
)
// DynamicSharedInformerFactory provides access to a shared informer and lister for dynamic client
type DynamicSharedInformerFactory interface {
Start(stopCh <-chan struct{})
ForResource(gvr schema.GroupVersionResource) informers.GenericInformer
WaitForCacheSync(stopCh <-chan struct{}) map[schema.GroupVersionResource]bool
}
// TweakListOptionsFunc defines the signature of a helper function
// that wants to provide more listing options to API
type TweakListOptionsFunc func(*metav1.ListOptions)

View File

@@ -1,40 +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 dynamiclister
import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
)
// Lister helps list resources.
type Lister interface {
// List lists all resources in the indexer.
List(selector labels.Selector) (ret []*unstructured.Unstructured, err error)
// Get retrieves a resource from the indexer with the given name
Get(name string) (*unstructured.Unstructured, error)
// Namespace returns an object that can list and get resources in a given namespace.
Namespace(namespace string) NamespaceLister
}
// NamespaceLister helps list and get resources.
type NamespaceLister interface {
// List lists all resources in the indexer for a given namespace.
List(selector labels.Selector) (ret []*unstructured.Unstructured, err error)
// Get retrieves a resource from the indexer for a given namespace and name.
Get(name string) (*unstructured.Unstructured, error)
}

View File

@@ -1,91 +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 dynamiclister
import (
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/tools/cache"
)
var _ Lister = &dynamicLister{}
var _ NamespaceLister = &dynamicNamespaceLister{}
// dynamicLister implements the Lister interface.
type dynamicLister struct {
indexer cache.Indexer
gvr schema.GroupVersionResource
}
// New returns a new Lister.
func New(indexer cache.Indexer, gvr schema.GroupVersionResource) Lister {
return &dynamicLister{indexer: indexer, gvr: gvr}
}
// List lists all resources in the indexer.
func (l *dynamicLister) List(selector labels.Selector) (ret []*unstructured.Unstructured, err error) {
err = cache.ListAll(l.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*unstructured.Unstructured))
})
return ret, err
}
// Get retrieves a resource from the indexer with the given name
func (l *dynamicLister) Get(name string) (*unstructured.Unstructured, error) {
obj, exists, err := l.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(l.gvr.GroupResource(), name)
}
return obj.(*unstructured.Unstructured), nil
}
// Namespace returns an object that can list and get resources from a given namespace.
func (l *dynamicLister) Namespace(namespace string) NamespaceLister {
return &dynamicNamespaceLister{indexer: l.indexer, namespace: namespace, gvr: l.gvr}
}
// dynamicNamespaceLister implements the NamespaceLister interface.
type dynamicNamespaceLister struct {
indexer cache.Indexer
namespace string
gvr schema.GroupVersionResource
}
// List lists all resources in the indexer for a given namespace.
func (l *dynamicNamespaceLister) List(selector labels.Selector) (ret []*unstructured.Unstructured, err error) {
err = cache.ListAllByNamespace(l.indexer, l.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*unstructured.Unstructured))
})
return ret, err
}
// Get retrieves a resource from the indexer for a given namespace and name.
func (l *dynamicNamespaceLister) Get(name string) (*unstructured.Unstructured, error) {
obj, exists, err := l.indexer.GetByKey(l.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(l.gvr.GroupResource(), name)
}
return obj.(*unstructured.Unstructured), nil
}

View File

@@ -1,257 +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 dynamiclister_test
import (
"reflect"
"testing"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/diff"
"k8s.io/client-go/dynamic/dynamiclister"
"k8s.io/client-go/tools/cache"
)
func TestNamespaceGetMethod(t *testing.T) {
tests := []struct {
name string
existingObjects []runtime.Object
namespaceToSync string
gvrToSync schema.GroupVersionResource
objectToGet string
expectedObject *unstructured.Unstructured
expectError bool
}{
{
name: "scenario 1: gets name-foo1 resource from the indexer from ns-foo namespace",
existingObjects: []runtime.Object{
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo"),
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo1"),
newUnstructured("group/version", "TheKind", "ns-bar", "name-bar"),
},
namespaceToSync: "ns-foo",
gvrToSync: schema.GroupVersionResource{Group: "group", Version: "version", Resource: "TheKinds"},
objectToGet: "name-foo1",
expectedObject: newUnstructured("group/version", "TheKind", "ns-foo", "name-foo1"),
},
{
name: "scenario 2: gets name-foo-non-existing resource from the indexer from ns-foo namespace",
existingObjects: []runtime.Object{
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo"),
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo1"),
newUnstructured("group/version", "TheKind", "ns-bar", "name-bar"),
},
namespaceToSync: "ns-foo",
gvrToSync: schema.GroupVersionResource{Group: "group", Version: "version", Resource: "TheKinds"},
objectToGet: "name-foo-non-existing",
expectError: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// test data
indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})
for _, obj := range test.existingObjects {
err := indexer.Add(obj)
if err != nil {
t.Fatal(err)
}
}
// act
target := dynamiclister.New(indexer, test.gvrToSync).Namespace(test.namespaceToSync)
actualObject, err := target.Get(test.objectToGet)
// validate
if test.expectError {
if err == nil {
t.Fatal("expected to get an error but non was returned")
}
return
}
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(test.expectedObject, actualObject) {
t.Fatalf("unexpected object has been returned expected = %v actual = %v, diff = %v", test.expectedObject, actualObject, diff.ObjectDiff(test.expectedObject, actualObject))
}
})
}
}
func TestNamespaceListMethod(t *testing.T) {
// test data
objs := []runtime.Object{
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo"),
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo1"),
newUnstructured("group/version", "TheKind", "ns-bar", "name-bar"),
}
indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})
for _, obj := range objs {
err := indexer.Add(obj)
if err != nil {
t.Fatal(err)
}
}
expectedOutput := []*unstructured.Unstructured{
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo"),
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo1"),
}
namespaceToList := "ns-foo"
// act
target := dynamiclister.New(indexer, schema.GroupVersionResource{Group: "group", Version: "version", Resource: "TheKinds"}).Namespace(namespaceToList)
actualOutput, err := target.List(labels.Everything())
// validate
if err != nil {
t.Fatal(err)
}
assertListOrDie(expectedOutput, actualOutput, t)
}
func TestListerGetMethod(t *testing.T) {
tests := []struct {
name string
existingObjects []runtime.Object
namespaceToSync string
gvrToSync schema.GroupVersionResource
objectToGet string
expectedObject *unstructured.Unstructured
expectError bool
}{
{
name: "scenario 1: gets name-foo1 resource from the indexer",
existingObjects: []runtime.Object{
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo"),
newUnstructured("group/version", "TheKind", "", "name-foo1"),
newUnstructured("group/version", "TheKind", "ns-bar", "name-bar"),
},
namespaceToSync: "",
gvrToSync: schema.GroupVersionResource{Group: "group", Version: "version", Resource: "TheKinds"},
objectToGet: "name-foo1",
expectedObject: newUnstructured("group/version", "TheKind", "", "name-foo1"),
},
{
name: "scenario 2: doesn't get name-foo resource from the indexer from ns-foo namespace",
existingObjects: []runtime.Object{
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo"),
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo1"),
newUnstructured("group/version", "TheKind", "ns-bar", "name-bar"),
},
namespaceToSync: "ns-foo",
gvrToSync: schema.GroupVersionResource{Group: "group", Version: "version", Resource: "TheKinds"},
objectToGet: "name-foo",
expectError: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// test data
indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})
for _, obj := range test.existingObjects {
err := indexer.Add(obj)
if err != nil {
t.Fatal(err)
}
}
// act
target := dynamiclister.New(indexer, test.gvrToSync)
actualObject, err := target.Get(test.objectToGet)
// validate
if test.expectError {
if err == nil {
t.Fatal("expected to get an error but non was returned")
}
return
}
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(test.expectedObject, actualObject) {
t.Fatalf("unexpected object has been returned expected = %v actual = %v, diff = %v", test.expectedObject, actualObject, diff.ObjectDiff(test.expectedObject, actualObject))
}
})
}
}
func TestListerListMethod(t *testing.T) {
// test data
objs := []runtime.Object{
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo"),
newUnstructured("group/version", "TheKind", "ns-foo", "name-bar"),
}
indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})
for _, obj := range objs {
err := indexer.Add(obj)
if err != nil {
t.Fatal(err)
}
}
expectedOutput := []*unstructured.Unstructured{
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo"),
newUnstructured("group/version", "TheKind", "ns-foo", "name-bar"),
}
// act
target := dynamiclister.New(indexer, schema.GroupVersionResource{Group: "group", Version: "version", Resource: "TheKinds"})
actualOutput, err := target.List(labels.Everything())
// validate
if err != nil {
t.Fatal(err)
}
assertListOrDie(expectedOutput, actualOutput, t)
}
func newUnstructured(apiVersion, kind, namespace, name string) *unstructured.Unstructured {
return &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": apiVersion,
"kind": kind,
"metadata": map[string]interface{}{
"namespace": namespace,
"name": name,
},
},
}
}
func assertListOrDie(expected, actual []*unstructured.Unstructured, t *testing.T) {
if len(actual) != len(expected) {
t.Fatalf("unexpected number of items returned, expected = %d, actual = %d", len(expected), len(actual))
}
for _, expectedObject := range expected {
found := false
for _, actualObject := range actual {
if actualObject.GetName() == expectedObject.GetName() {
if !reflect.DeepEqual(expectedObject, actualObject) {
t.Fatalf("unexpected object has been returned expected = %v actual = %v, diff = %v", expectedObject, actualObject, diff.ObjectDiff(expectedObject, actualObject))
}
found = true
}
}
if !found {
t.Fatalf("the resource with the name = %s was not found in the returned output", expectedObject.GetName())
}
}
}

View File

@@ -1,87 +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 dynamiclister
import (
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/cache"
)
var _ cache.GenericLister = &dynamicListerShim{}
var _ cache.GenericNamespaceLister = &dynamicNamespaceListerShim{}
// dynamicListerShim implements the cache.GenericLister interface.
type dynamicListerShim struct {
lister Lister
}
// NewRuntimeObjectShim returns a new shim for Lister.
// It wraps Lister so that it implements cache.GenericLister interface
func NewRuntimeObjectShim(lister Lister) cache.GenericLister {
return &dynamicListerShim{lister: lister}
}
// List will return all objects across namespaces
func (s *dynamicListerShim) List(selector labels.Selector) (ret []runtime.Object, err error) {
objs, err := s.lister.List(selector)
if err != nil {
return nil, err
}
ret = make([]runtime.Object, len(objs))
for index, obj := range objs {
ret[index] = obj
}
return ret, err
}
// Get will attempt to retrieve assuming that name==key
func (s *dynamicListerShim) Get(name string) (runtime.Object, error) {
return s.lister.Get(name)
}
func (s *dynamicListerShim) ByNamespace(namespace string) cache.GenericNamespaceLister {
return &dynamicNamespaceListerShim{
namespaceLister: s.lister.Namespace(namespace),
}
}
// dynamicNamespaceListerShim implements the NamespaceLister interface.
// It wraps NamespaceLister so that it implements cache.GenericNamespaceLister interface
type dynamicNamespaceListerShim struct {
namespaceLister NamespaceLister
}
// List will return all objects in this namespace
func (ns *dynamicNamespaceListerShim) List(selector labels.Selector) (ret []runtime.Object, err error) {
objs, err := ns.namespaceLister.List(selector)
if err != nil {
return nil, err
}
ret = make([]runtime.Object, len(objs))
for index, obj := range objs {
ret[index] = obj
}
return ret, err
}
// Get will attempt to retrieve by namespace and name
func (ns *dynamicNamespaceListerShim) Get(name string) (runtime.Object, error) {
return ns.namespaceLister.Get(name)
}

View File

@@ -1,369 +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 fake
import (
"strings"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/testing"
)
func NewSimpleDynamicClient(scheme *runtime.Scheme, objects ...runtime.Object) *FakeDynamicClient {
// In order to use List with this client, you have to have the v1.List registered in your scheme. Neat thing though
// it does NOT have to be the *same* list
scheme.AddKnownTypeWithName(schema.GroupVersionKind{Group: "fake-dynamic-client-group", Version: "v1", Kind: "List"}, &unstructured.UnstructuredList{})
codecs := serializer.NewCodecFactory(scheme)
o := testing.NewObjectTracker(scheme, codecs.UniversalDecoder())
for _, obj := range objects {
if err := o.Add(obj); err != nil {
panic(err)
}
}
cs := &FakeDynamicClient{scheme: scheme}
cs.AddReactor("*", "*", testing.ObjectReaction(o))
cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) {
gvr := action.GetResource()
ns := action.GetNamespace()
watch, err := o.Watch(gvr, ns)
if err != nil {
return false, nil, err
}
return true, watch, nil
})
return cs
}
// Clientset implements clientset.Interface. Meant to be embedded into a
// struct to get a default implementation. This makes faking out just the method
// you want to test easier.
type FakeDynamicClient struct {
testing.Fake
scheme *runtime.Scheme
}
type dynamicResourceClient struct {
client *FakeDynamicClient
namespace string
resource schema.GroupVersionResource
}
var _ dynamic.Interface = &FakeDynamicClient{}
func (c *FakeDynamicClient) Resource(resource schema.GroupVersionResource) dynamic.NamespaceableResourceInterface {
return &dynamicResourceClient{client: c, resource: resource}
}
func (c *dynamicResourceClient) Namespace(ns string) dynamic.ResourceInterface {
ret := *c
ret.namespace = ns
return &ret
}
func (c *dynamicResourceClient) Create(obj *unstructured.Unstructured, opts metav1.CreateOptions, subresources ...string) (*unstructured.Unstructured, error) {
var uncastRet runtime.Object
var err error
switch {
case len(c.namespace) == 0 && len(subresources) == 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewRootCreateAction(c.resource, obj), obj)
case len(c.namespace) == 0 && len(subresources) > 0:
accessor, err := meta.Accessor(obj)
if err != nil {
return nil, err
}
name := accessor.GetName()
uncastRet, err = c.client.Fake.
Invokes(testing.NewRootCreateSubresourceAction(c.resource, name, strings.Join(subresources, "/"), obj), obj)
case len(c.namespace) > 0 && len(subresources) == 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewCreateAction(c.resource, c.namespace, obj), obj)
case len(c.namespace) > 0 && len(subresources) > 0:
accessor, err := meta.Accessor(obj)
if err != nil {
return nil, err
}
name := accessor.GetName()
uncastRet, err = c.client.Fake.
Invokes(testing.NewCreateSubresourceAction(c.resource, name, strings.Join(subresources, "/"), c.namespace, obj), obj)
}
if err != nil {
return nil, err
}
if uncastRet == nil {
return nil, err
}
ret := &unstructured.Unstructured{}
if err := c.client.scheme.Convert(uncastRet, ret, nil); err != nil {
return nil, err
}
return ret, err
}
func (c *dynamicResourceClient) Update(obj *unstructured.Unstructured, opts metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error) {
var uncastRet runtime.Object
var err error
switch {
case len(c.namespace) == 0 && len(subresources) == 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewRootUpdateAction(c.resource, obj), obj)
case len(c.namespace) == 0 && len(subresources) > 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewRootUpdateSubresourceAction(c.resource, strings.Join(subresources, "/"), obj), obj)
case len(c.namespace) > 0 && len(subresources) == 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewUpdateAction(c.resource, c.namespace, obj), obj)
case len(c.namespace) > 0 && len(subresources) > 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewUpdateSubresourceAction(c.resource, strings.Join(subresources, "/"), c.namespace, obj), obj)
}
if err != nil {
return nil, err
}
if uncastRet == nil {
return nil, err
}
ret := &unstructured.Unstructured{}
if err := c.client.scheme.Convert(uncastRet, ret, nil); err != nil {
return nil, err
}
return ret, err
}
func (c *dynamicResourceClient) UpdateStatus(obj *unstructured.Unstructured, opts metav1.UpdateOptions) (*unstructured.Unstructured, error) {
var uncastRet runtime.Object
var err error
switch {
case len(c.namespace) == 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewRootUpdateSubresourceAction(c.resource, "status", obj), obj)
case len(c.namespace) > 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewUpdateSubresourceAction(c.resource, "status", c.namespace, obj), obj)
}
if err != nil {
return nil, err
}
if uncastRet == nil {
return nil, err
}
ret := &unstructured.Unstructured{}
if err := c.client.scheme.Convert(uncastRet, ret, nil); err != nil {
return nil, err
}
return ret, err
}
func (c *dynamicResourceClient) Delete(name string, opts *metav1.DeleteOptions, subresources ...string) error {
var err error
switch {
case len(c.namespace) == 0 && len(subresources) == 0:
_, err = c.client.Fake.
Invokes(testing.NewRootDeleteAction(c.resource, name), &metav1.Status{Status: "dynamic delete fail"})
case len(c.namespace) == 0 && len(subresources) > 0:
_, err = c.client.Fake.
Invokes(testing.NewRootDeleteSubresourceAction(c.resource, strings.Join(subresources, "/"), name), &metav1.Status{Status: "dynamic delete fail"})
case len(c.namespace) > 0 && len(subresources) == 0:
_, err = c.client.Fake.
Invokes(testing.NewDeleteAction(c.resource, c.namespace, name), &metav1.Status{Status: "dynamic delete fail"})
case len(c.namespace) > 0 && len(subresources) > 0:
_, err = c.client.Fake.
Invokes(testing.NewDeleteSubresourceAction(c.resource, strings.Join(subresources, "/"), c.namespace, name), &metav1.Status{Status: "dynamic delete fail"})
}
return err
}
func (c *dynamicResourceClient) DeleteCollection(opts *metav1.DeleteOptions, listOptions metav1.ListOptions) error {
var err error
switch {
case len(c.namespace) == 0:
action := testing.NewRootDeleteCollectionAction(c.resource, listOptions)
_, err = c.client.Fake.Invokes(action, &metav1.Status{Status: "dynamic deletecollection fail"})
case len(c.namespace) > 0:
action := testing.NewDeleteCollectionAction(c.resource, c.namespace, listOptions)
_, err = c.client.Fake.Invokes(action, &metav1.Status{Status: "dynamic deletecollection fail"})
}
return err
}
func (c *dynamicResourceClient) Get(name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error) {
var uncastRet runtime.Object
var err error
switch {
case len(c.namespace) == 0 && len(subresources) == 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewRootGetAction(c.resource, name), &metav1.Status{Status: "dynamic get fail"})
case len(c.namespace) == 0 && len(subresources) > 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewRootGetSubresourceAction(c.resource, strings.Join(subresources, "/"), name), &metav1.Status{Status: "dynamic get fail"})
case len(c.namespace) > 0 && len(subresources) == 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewGetAction(c.resource, c.namespace, name), &metav1.Status{Status: "dynamic get fail"})
case len(c.namespace) > 0 && len(subresources) > 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewGetSubresourceAction(c.resource, c.namespace, strings.Join(subresources, "/"), name), &metav1.Status{Status: "dynamic get fail"})
}
if err != nil {
return nil, err
}
if uncastRet == nil {
return nil, err
}
ret := &unstructured.Unstructured{}
if err := c.client.scheme.Convert(uncastRet, ret, nil); err != nil {
return nil, err
}
return ret, err
}
func (c *dynamicResourceClient) List(opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {
var obj runtime.Object
var err error
switch {
case len(c.namespace) == 0:
obj, err = c.client.Fake.
Invokes(testing.NewRootListAction(c.resource, schema.GroupVersionKind{Group: "fake-dynamic-client-group", Version: "v1", Kind: "" /*List is appended by the tracker automatically*/}, opts), &metav1.Status{Status: "dynamic list fail"})
case len(c.namespace) > 0:
obj, err = c.client.Fake.
Invokes(testing.NewListAction(c.resource, schema.GroupVersionKind{Group: "fake-dynamic-client-group", Version: "v1", Kind: "" /*List is appended by the tracker automatically*/}, c.namespace, opts), &metav1.Status{Status: "dynamic list fail"})
}
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
retUnstructured := &unstructured.Unstructured{}
if err := c.client.scheme.Convert(obj, retUnstructured, nil); err != nil {
return nil, err
}
entireList, err := retUnstructured.ToList()
if err != nil {
return nil, err
}
list := &unstructured.UnstructuredList{}
for i := range entireList.Items {
item := &entireList.Items[i]
metadata, err := meta.Accessor(item)
if err != nil {
return nil, err
}
if label.Matches(labels.Set(metadata.GetLabels())) {
list.Items = append(list.Items, *item)
}
}
return list, nil
}
func (c *dynamicResourceClient) Watch(opts metav1.ListOptions) (watch.Interface, error) {
switch {
case len(c.namespace) == 0:
return c.client.Fake.
InvokesWatch(testing.NewRootWatchAction(c.resource, opts))
case len(c.namespace) > 0:
return c.client.Fake.
InvokesWatch(testing.NewWatchAction(c.resource, c.namespace, opts))
}
panic("math broke")
}
// TODO: opts are currently ignored.
func (c *dynamicResourceClient) Patch(name string, pt types.PatchType, data []byte, opts metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error) {
var uncastRet runtime.Object
var err error
switch {
case len(c.namespace) == 0 && len(subresources) == 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewRootPatchAction(c.resource, name, pt, data), &metav1.Status{Status: "dynamic patch fail"})
case len(c.namespace) == 0 && len(subresources) > 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewRootPatchSubresourceAction(c.resource, name, pt, data, subresources...), &metav1.Status{Status: "dynamic patch fail"})
case len(c.namespace) > 0 && len(subresources) == 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewPatchAction(c.resource, c.namespace, name, pt, data), &metav1.Status{Status: "dynamic patch fail"})
case len(c.namespace) > 0 && len(subresources) > 0:
uncastRet, err = c.client.Fake.
Invokes(testing.NewPatchSubresourceAction(c.resource, c.namespace, name, pt, data, subresources...), &metav1.Status{Status: "dynamic patch fail"})
}
if err != nil {
return nil, err
}
if uncastRet == nil {
return nil, err
}
ret := &unstructured.Unstructured{}
if err := c.client.scheme.Convert(uncastRet, ret, nil); err != nil {
return nil, err
}
return ret, err
}

View File

@@ -1,197 +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 fake
import (
"fmt"
"testing"
"k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/diff"
)
const (
testGroup = "testgroup"
testVersion = "testversion"
testResource = "testkinds"
testNamespace = "testns"
testName = "testname"
testKind = "TestKind"
testAPIVersion = "testgroup/testversion"
)
func newUnstructured(apiVersion, kind, namespace, name string) *unstructured.Unstructured {
return &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": apiVersion,
"kind": kind,
"metadata": map[string]interface{}{
"namespace": namespace,
"name": name,
},
},
}
}
func newUnstructuredWithSpec(spec map[string]interface{}) *unstructured.Unstructured {
u := newUnstructured(testAPIVersion, testKind, testNamespace, testName)
u.Object["spec"] = spec
return u
}
func TestList(t *testing.T) {
scheme := runtime.NewScheme()
client := NewSimpleDynamicClient(scheme,
newUnstructured("group/version", "TheKind", "ns-foo", "name-foo"),
newUnstructured("group2/version", "TheKind", "ns-foo", "name2-foo"),
newUnstructured("group/version", "TheKind", "ns-foo", "name-bar"),
newUnstructured("group/version", "TheKind", "ns-foo", "name-baz"),
newUnstructured("group2/version", "TheKind", "ns-foo", "name2-baz"),
)
listFirst, err := client.Resource(schema.GroupVersionResource{Group: "group", Version: "version", Resource: "thekinds"}).List(metav1.ListOptions{})
if err != nil {
t.Fatal(err)
}
expected := []unstructured.Unstructured{
*newUnstructured("group/version", "TheKind", "ns-foo", "name-foo"),
*newUnstructured("group/version", "TheKind", "ns-foo", "name-bar"),
*newUnstructured("group/version", "TheKind", "ns-foo", "name-baz"),
}
if !equality.Semantic.DeepEqual(listFirst.Items, expected) {
t.Fatal(diff.ObjectGoPrintDiff(expected, listFirst.Items))
}
}
type patchTestCase struct {
name string
object runtime.Object
patchType types.PatchType
patchBytes []byte
wantErrMsg string
expectedPatchedObject runtime.Object
}
func (tc *patchTestCase) runner(t *testing.T) {
client := NewSimpleDynamicClient(runtime.NewScheme(), tc.object)
resourceInterface := client.Resource(schema.GroupVersionResource{Group: testGroup, Version: testVersion, Resource: testResource}).Namespace(testNamespace)
got, recErr := resourceInterface.Patch(testName, tc.patchType, tc.patchBytes, metav1.UpdateOptions{})
if err := tc.verifyErr(recErr); err != nil {
t.Error(err)
}
if err := tc.verifyResult(got); err != nil {
t.Error(err)
}
}
// verifyErr verifies that the given error returned from Patch is the error
// expected by the test case.
func (tc *patchTestCase) verifyErr(err error) error {
if tc.wantErrMsg != "" && err == nil {
return fmt.Errorf("want error, got nil")
}
if tc.wantErrMsg == "" && err != nil {
return fmt.Errorf("want no error, got %v", err)
}
if err != nil {
if want, got := tc.wantErrMsg, err.Error(); want != got {
return fmt.Errorf("incorrect error: want: %q got: %q", want, got)
}
}
return nil
}
func (tc *patchTestCase) verifyResult(result *unstructured.Unstructured) error {
if tc.expectedPatchedObject == nil && result == nil {
return nil
}
if !equality.Semantic.DeepEqual(result, tc.expectedPatchedObject) {
return fmt.Errorf("unexpected diff in received object: %s", diff.ObjectGoPrintDiff(tc.expectedPatchedObject, result))
}
return nil
}
func TestPatch(t *testing.T) {
testCases := []patchTestCase{
{
name: "jsonpatch fails with merge type",
object: newUnstructuredWithSpec(map[string]interface{}{"foo": "bar"}),
patchType: types.StrategicMergePatchType,
patchBytes: []byte(`[]`),
wantErrMsg: "invalid JSON document",
}, {
name: "jsonpatch works with empty patch",
object: newUnstructuredWithSpec(map[string]interface{}{"foo": "bar"}),
patchType: types.JSONPatchType,
// No-op
patchBytes: []byte(`[]`),
expectedPatchedObject: newUnstructuredWithSpec(map[string]interface{}{"foo": "bar"}),
}, {
name: "jsonpatch works with simple change patch",
object: newUnstructuredWithSpec(map[string]interface{}{"foo": "bar"}),
patchType: types.JSONPatchType,
// change spec.foo from bar to foobar
patchBytes: []byte(`[{"op": "replace", "path": "/spec/foo", "value": "foobar"}]`),
expectedPatchedObject: newUnstructuredWithSpec(map[string]interface{}{"foo": "foobar"}),
}, {
name: "jsonpatch works with simple addition",
object: newUnstructuredWithSpec(map[string]interface{}{"foo": "bar"}),
patchType: types.JSONPatchType,
// add spec.newvalue = dummy
patchBytes: []byte(`[{"op": "add", "path": "/spec/newvalue", "value": "dummy"}]`),
expectedPatchedObject: newUnstructuredWithSpec(map[string]interface{}{"foo": "bar", "newvalue": "dummy"}),
}, {
name: "jsonpatch works with simple deletion",
object: newUnstructuredWithSpec(map[string]interface{}{"foo": "bar", "toremove": "shouldnotbehere"}),
patchType: types.JSONPatchType,
// remove spec.newvalue = dummy
patchBytes: []byte(`[{"op": "remove", "path": "/spec/toremove"}]`),
expectedPatchedObject: newUnstructuredWithSpec(map[string]interface{}{"foo": "bar"}),
}, {
name: "strategic merge patch fails with JSONPatch",
object: newUnstructuredWithSpec(map[string]interface{}{"foo": "bar"}),
patchType: types.StrategicMergePatchType,
// add spec.newvalue = dummy
patchBytes: []byte(`[{"op": "add", "path": "/spec/newvalue", "value": "dummy"}]`),
wantErrMsg: "invalid JSON document",
}, {
name: "merge patch fails as unsupported",
object: newUnstructured(testAPIVersion, testKind, testNamespace, testName),
patchType: types.MergePatchType,
patchBytes: []byte(`{}`),
wantErrMsg: "PatchType is not supported",
},
// TODO: Add tests for strategic merge using v1.Pod for example to ensure the test cases
// demonstrate expected use cases.
}
for _, tc := range testCases {
t.Run(tc.name, tc.runner)
}
}

View File

@@ -1,59 +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 dynamic
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
)
type Interface interface {
Resource(resource schema.GroupVersionResource) NamespaceableResourceInterface
}
type ResourceInterface interface {
Create(obj *unstructured.Unstructured, options metav1.CreateOptions, subresources ...string) (*unstructured.Unstructured, error)
Update(obj *unstructured.Unstructured, options metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error)
UpdateStatus(obj *unstructured.Unstructured, options metav1.UpdateOptions) (*unstructured.Unstructured, error)
Delete(name string, options *metav1.DeleteOptions, subresources ...string) error
DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error
Get(name string, options metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error)
List(opts metav1.ListOptions) (*unstructured.UnstructuredList, error)
Watch(opts metav1.ListOptions) (watch.Interface, error)
Patch(name string, pt types.PatchType, data []byte, options metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error)
}
type NamespaceableResourceInterface interface {
Namespace(string) ResourceInterface
ResourceInterface
}
// APIPathResolverFunc knows how to convert a groupVersion to its API path. The Kind field is optional.
// TODO find a better place to move this for existing callers
type APIPathResolverFunc func(kind schema.GroupVersionKind) string
// LegacyAPIPathResolverFunc can resolve paths properly with the legacy API.
// TODO find a better place to move this for existing callers
func LegacyAPIPathResolverFunc(kind schema.GroupVersionKind) string {
if len(kind.Group) == 0 {
return "/api"
}
return "/apis"
}

View File

@@ -1,98 +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 dynamic
import (
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"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/apimachinery/pkg/runtime/serializer/versioning"
)
var watchScheme = runtime.NewScheme()
var basicScheme = runtime.NewScheme()
var deleteScheme = runtime.NewScheme()
var parameterScheme = runtime.NewScheme()
var deleteOptionsCodec = serializer.NewCodecFactory(deleteScheme)
var dynamicParameterCodec = runtime.NewParameterCodec(parameterScheme)
var versionV1 = schema.GroupVersion{Version: "v1"}
func init() {
metav1.AddToGroupVersion(watchScheme, versionV1)
metav1.AddToGroupVersion(basicScheme, versionV1)
metav1.AddToGroupVersion(parameterScheme, versionV1)
metav1.AddToGroupVersion(deleteScheme, versionV1)
}
var watchJsonSerializerInfo = runtime.SerializerInfo{
MediaType: "application/json",
EncodesAsText: true,
Serializer: json.NewSerializer(json.DefaultMetaFactory, watchScheme, watchScheme, false),
PrettySerializer: json.NewSerializer(json.DefaultMetaFactory, watchScheme, watchScheme, true),
StreamSerializer: &runtime.StreamSerializerInfo{
EncodesAsText: true,
Serializer: json.NewSerializer(json.DefaultMetaFactory, watchScheme, watchScheme, false),
Framer: json.Framer,
},
}
// watchNegotiatedSerializer is used to read the wrapper of the watch stream
type watchNegotiatedSerializer struct{}
var watchNegotiatedSerializerInstance = watchNegotiatedSerializer{}
func (s watchNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo {
return []runtime.SerializerInfo{watchJsonSerializerInfo}
}
func (s watchNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {
return versioning.NewDefaultingCodecForScheme(watchScheme, encoder, nil, gv, nil)
}
func (s watchNegotiatedSerializer) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {
return versioning.NewDefaultingCodecForScheme(watchScheme, nil, decoder, nil, gv)
}
// basicNegotiatedSerializer is used to handle discovery and error handling serialization
type basicNegotiatedSerializer struct{}
func (s basicNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo {
return []runtime.SerializerInfo{
{
MediaType: "application/json",
EncodesAsText: true,
Serializer: json.NewSerializer(json.DefaultMetaFactory, basicScheme, basicScheme, false),
PrettySerializer: json.NewSerializer(json.DefaultMetaFactory, basicScheme, basicScheme, true),
StreamSerializer: &runtime.StreamSerializerInfo{
EncodesAsText: true,
Serializer: json.NewSerializer(json.DefaultMetaFactory, basicScheme, basicScheme, false),
Framer: json.Framer,
},
},
}
}
func (s basicNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {
return versioning.NewDefaultingCodecForScheme(watchScheme, encoder, nil, gv, nil)
}
func (s basicNegotiatedSerializer) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {
return versioning.NewDefaultingCodecForScheme(watchScheme, nil, decoder, nil, gv)
}

View File

@@ -1,326 +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 dynamic
import (
"io"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer/streaming"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/rest"
)
type dynamicClient struct {
client *rest.RESTClient
}
var _ Interface = &dynamicClient{}
// NewForConfigOrDie creates a new Interface for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) Interface {
ret, err := NewForConfig(c)
if err != nil {
panic(err)
}
return ret
}
func NewForConfig(inConfig *rest.Config) (Interface, error) {
config := rest.CopyConfig(inConfig)
// for serializing the options
config.GroupVersion = &schema.GroupVersion{}
config.APIPath = "/if-you-see-this-search-for-the-break"
config.AcceptContentTypes = "application/json"
config.ContentType = "application/json"
config.NegotiatedSerializer = basicNegotiatedSerializer{} // this gets used for discovery and error handling types
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
restClient, err := rest.RESTClientFor(config)
if err != nil {
return nil, err
}
return &dynamicClient{client: restClient}, nil
}
type dynamicResourceClient struct {
client *dynamicClient
namespace string
resource schema.GroupVersionResource
}
func (c *dynamicClient) Resource(resource schema.GroupVersionResource) NamespaceableResourceInterface {
return &dynamicResourceClient{client: c, resource: resource}
}
func (c *dynamicResourceClient) Namespace(ns string) ResourceInterface {
ret := *c
ret.namespace = ns
return &ret
}
func (c *dynamicResourceClient) Create(obj *unstructured.Unstructured, opts metav1.CreateOptions, subresources ...string) (*unstructured.Unstructured, error) {
outBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)
if err != nil {
return nil, err
}
name := ""
if len(subresources) > 0 {
accessor, err := meta.Accessor(obj)
if err != nil {
return nil, err
}
name = accessor.GetName()
}
result := c.client.client.
Post().
AbsPath(append(c.makeURLSegments(name), subresources...)...).
Body(outBytes).
SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).
Do()
if err := result.Error(); err != nil {
return nil, err
}
retBytes, err := result.Raw()
if err != nil {
return nil, err
}
uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
if err != nil {
return nil, err
}
return uncastObj.(*unstructured.Unstructured), nil
}
func (c *dynamicResourceClient) Update(obj *unstructured.Unstructured, opts metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error) {
accessor, err := meta.Accessor(obj)
if err != nil {
return nil, err
}
outBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)
if err != nil {
return nil, err
}
result := c.client.client.
Put().
AbsPath(append(c.makeURLSegments(accessor.GetName()), subresources...)...).
Body(outBytes).
SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).
Do()
if err := result.Error(); err != nil {
return nil, err
}
retBytes, err := result.Raw()
if err != nil {
return nil, err
}
uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
if err != nil {
return nil, err
}
return uncastObj.(*unstructured.Unstructured), nil
}
func (c *dynamicResourceClient) UpdateStatus(obj *unstructured.Unstructured, opts metav1.UpdateOptions) (*unstructured.Unstructured, error) {
accessor, err := meta.Accessor(obj)
if err != nil {
return nil, err
}
outBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)
if err != nil {
return nil, err
}
result := c.client.client.
Put().
AbsPath(append(c.makeURLSegments(accessor.GetName()), "status")...).
Body(outBytes).
SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).
Do()
if err := result.Error(); err != nil {
return nil, err
}
retBytes, err := result.Raw()
if err != nil {
return nil, err
}
uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
if err != nil {
return nil, err
}
return uncastObj.(*unstructured.Unstructured), nil
}
func (c *dynamicResourceClient) Delete(name string, opts *metav1.DeleteOptions, subresources ...string) error {
if opts == nil {
opts = &metav1.DeleteOptions{}
}
deleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: "v1"}), opts)
if err != nil {
return err
}
result := c.client.client.
Delete().
AbsPath(append(c.makeURLSegments(name), subresources...)...).
Body(deleteOptionsByte).
Do()
return result.Error()
}
func (c *dynamicResourceClient) DeleteCollection(opts *metav1.DeleteOptions, listOptions metav1.ListOptions) error {
if opts == nil {
opts = &metav1.DeleteOptions{}
}
deleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: "v1"}), opts)
if err != nil {
return err
}
result := c.client.client.
Delete().
AbsPath(c.makeURLSegments("")...).
Body(deleteOptionsByte).
SpecificallyVersionedParams(&listOptions, dynamicParameterCodec, versionV1).
Do()
return result.Error()
}
func (c *dynamicResourceClient) Get(name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error) {
result := c.client.client.Get().AbsPath(append(c.makeURLSegments(name), subresources...)...).SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).Do()
if err := result.Error(); err != nil {
return nil, err
}
retBytes, err := result.Raw()
if err != nil {
return nil, err
}
uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
if err != nil {
return nil, err
}
return uncastObj.(*unstructured.Unstructured), nil
}
func (c *dynamicResourceClient) List(opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {
result := c.client.client.Get().AbsPath(c.makeURLSegments("")...).SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).Do()
if err := result.Error(); err != nil {
return nil, err
}
retBytes, err := result.Raw()
if err != nil {
return nil, err
}
uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
if err != nil {
return nil, err
}
if list, ok := uncastObj.(*unstructured.UnstructuredList); ok {
return list, nil
}
list, err := uncastObj.(*unstructured.Unstructured).ToList()
if err != nil {
return nil, err
}
return list, nil
}
func (c *dynamicResourceClient) Watch(opts metav1.ListOptions) (watch.Interface, error) {
internalGV := schema.GroupVersions{
{Group: c.resource.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 := &rest.Serializers{
Encoder: watchNegotiatedSerializerInstance.EncoderForVersion(watchJsonSerializerInfo.Serializer, c.resource.GroupVersion()),
Decoder: watchNegotiatedSerializerInstance.DecoderToVersion(watchJsonSerializerInfo.Serializer, internalGV),
RenegotiatedDecoder: func(contentType string, params map[string]string) (runtime.Decoder, error) {
return watchNegotiatedSerializerInstance.DecoderToVersion(watchJsonSerializerInfo.Serializer, internalGV), nil
},
StreamingSerializer: watchJsonSerializerInfo.StreamSerializer.Serializer,
Framer: watchJsonSerializerInfo.StreamSerializer.Framer,
}
wrappedDecoderFn := func(body io.ReadCloser) streaming.Decoder {
framer := s.Framer.NewFrameReader(body)
return streaming.NewDecoder(framer, s.StreamingSerializer)
}
opts.Watch = true
return c.client.client.Get().AbsPath(c.makeURLSegments("")...).
SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).
WatchWithSpecificDecoders(wrappedDecoderFn, unstructured.UnstructuredJSONScheme)
}
func (c *dynamicResourceClient) Patch(name string, pt types.PatchType, data []byte, opts metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error) {
result := c.client.client.
Patch(pt).
AbsPath(append(c.makeURLSegments(name), subresources...)...).
Body(data).
SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).
Do()
if err := result.Error(); err != nil {
return nil, err
}
retBytes, err := result.Raw()
if err != nil {
return nil, err
}
uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)
if err != nil {
return nil, err
}
return uncastObj.(*unstructured.Unstructured), nil
}
func (c *dynamicResourceClient) makeURLSegments(name string) []string {
url := []string{}
if len(c.resource.Group) == 0 {
url = append(url, "api")
} else {
url = append(url, "apis", c.resource.Group)
}
url = append(url, c.resource.Version)
if len(c.namespace) > 0 {
url = append(url, "namespaces", c.namespace)
}
url = append(url, c.resource.Resource)
if len(name) > 0 {
url = append(url, name)
}
return url
}

View File

@@ -1,31 +0,0 @@
# client-go Examples
This directory contains examples that cover various use cases and functionality
for client-go.
### Configuration
- [**Authenticate in cluster**](./in-cluster-client-configuration): Configure a
client while running inside the Kubernetes cluster.
- [**Authenticate out of cluster**](./out-of-cluster-client-configuration):
Configure a client to access a Kubernetes cluster from outside.
### Basics
- [**Managing resources with API**](./create-update-delete-deployment): Create,
get, update, delete a Deployment resource.
### Advanced Concepts
- [**Work queues**](./workqueue): Create a hotloop-free controller with the
rate-limited workqueue and the [informer framework][informer].
- [**Custom Resource Definition (successor of TPR)**](https://git.k8s.io/apiextensions-apiserver/examples/client-go):
Register a custom resource type with the API, create/update/query this custom
type, and write a controller that drives the cluster state based on the changes to
the custom resources.
[informer]: https://godoc.org/k8s.io/client-go/tools/cache#NewInformer
### Testing
- [**Fake Client**](./fake-client): Use a fake client in tests.

View File

@@ -1,93 +0,0 @@
# Create, Update & Delete Deployment
This example program demonstrates the fundamental operations for managing on
[Deployment][1] resources, such as `Create`, `List`, `Update` and `Delete`.
You can adopt the source code from this example to write programs that manage
other types of resources through the Kubernetes API.
## Running this example
Make sure you have a Kubernetes cluster and `kubectl` is configured:
kubectl get nodes
Compile this example on your workstation:
```
cd create-update-delete-deployment
go build -o ./app
```
Now, run this application on your workstation with your local kubeconfig file:
```
./app
# or specify a kubeconfig file with flag
./app -kubeconfig=$HOME/.kube/config
```
Running this command will execute the following operations on your cluster:
1. **Create Deployment:** This will create a 2 replica Deployment. Verify with
`kubectl get pods`.
2. **Update Deployment:** This will update the Deployment resource created in
previous step by setting the replica count to 1 and changing the container
image to `nginx:1.13`. You are encouraged to inspect the retry loop that
handles conflicts. Verify the new replica count and container image with
`kubectl describe deployment demo`.
3. **Rollback Deployment:** This will rollback the Deployment to the last
revision. In this case, it's the revision that was created in Step 1.
Use `kubectl describe` to verify the container image is now `nginx:1.12`.
Also note that the Deployment's replica count is still 1; this is because a
Deployment revision is created if and only if the Deployment's pod template
(`.spec.template`) is changed.
4. **List Deployments:** This will retrieve Deployments in the `default`
namespace and print their names and replica counts.
5. **Delete Deployment:** This will delete the Deployment object and its
dependent ReplicaSet resource. Verify with `kubectl get deployments`.
Each step is separated by an interactive prompt. You must hit the
<kbd>Return</kbd> key to proceed to the next step. You can use these prompts as
a break to take time to run `kubectl` and inspect the result of the operations
executed.
You should see an output like the following:
```
Creating deployment...
Created deployment "demo-deployment".
-> Press Return key to continue.
Updating deployment...
Updated deployment...
-> Press Return key to continue.
Rolling back deployment...
Rolled back deployment...
-> Press Return key to continue.
Listing deployments in namespace "default":
* demo-deployment (1 replicas)
-> Press Return key to continue.
Deleting deployment...
Deleted deployment.
```
## Cleanup
Successfully running this program will clean the created artifacts. If you
terminate the program without completing, you can clean up the created
deployment with:
kubectl delete deploy demo-deployment
## Troubleshooting
If you are getting the following error, make sure Kubernetes version of your
cluster is v1.6 or above in `kubectl version`:
panic: the server could not find the requested resource
[1]: https://kubernetes.io/docs/user-guide/deployments/

View File

@@ -1,171 +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.
*/
// Note: the example only works with the code within the same release/branch.
package main
import (
"bufio"
"flag"
"fmt"
"os"
"path/filepath"
appsv1 "k8s.io/api/apps/v1"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
"k8s.io/client-go/util/retry"
// Uncomment the following line to load the gcp plugin (only required to authenticate against GKE clusters).
// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
)
func main() {
var kubeconfig *string
if home := homedir.HomeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err)
}
deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)
deployment := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "demo-deployment",
},
Spec: appsv1.DeploymentSpec{
Replicas: int32Ptr(2),
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "demo",
},
},
Template: apiv1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": "demo",
},
},
Spec: apiv1.PodSpec{
Containers: []apiv1.Container{
{
Name: "web",
Image: "nginx:1.12",
Ports: []apiv1.ContainerPort{
{
Name: "http",
Protocol: apiv1.ProtocolTCP,
ContainerPort: 80,
},
},
},
},
},
},
},
}
// Create Deployment
fmt.Println("Creating deployment...")
result, err := deploymentsClient.Create(deployment)
if err != nil {
panic(err)
}
fmt.Printf("Created deployment %q.\n", result.GetObjectMeta().GetName())
// Update Deployment
prompt()
fmt.Println("Updating deployment...")
// You have two options to Update() this Deployment:
//
// 1. Modify the "deployment" variable and call: Update(deployment).
// This works like the "kubectl replace" command and it overwrites/loses changes
// made by other clients between you Create() and Update() the object.
// 2. Modify the "result" returned by Get() and retry Update(result) until
// you no longer get a conflict error. This way, you can preserve changes made
// by other clients between Create() and Update(). This is implemented below
// using the retry utility package included with client-go. (RECOMMENDED)
//
// More Info:
// https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#concurrency-control-and-consistency
retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
// Retrieve the latest version of Deployment before attempting update
// RetryOnConflict uses exponential backoff to avoid exhausting the apiserver
result, getErr := deploymentsClient.Get("demo-deployment", metav1.GetOptions{})
if getErr != nil {
panic(fmt.Errorf("Failed to get latest version of Deployment: %v", getErr))
}
result.Spec.Replicas = int32Ptr(1) // reduce replica count
result.Spec.Template.Spec.Containers[0].Image = "nginx:1.13" // change nginx version
_, updateErr := deploymentsClient.Update(result)
return updateErr
})
if retryErr != nil {
panic(fmt.Errorf("Update failed: %v", retryErr))
}
fmt.Println("Updated deployment...")
// List Deployments
prompt()
fmt.Printf("Listing deployments in namespace %q:\n", apiv1.NamespaceDefault)
list, err := deploymentsClient.List(metav1.ListOptions{})
if err != nil {
panic(err)
}
for _, d := range list.Items {
fmt.Printf(" * %s (%d replicas)\n", d.Name, *d.Spec.Replicas)
}
// Delete Deployment
prompt()
fmt.Println("Deleting deployment...")
deletePolicy := metav1.DeletePropagationForeground
if err := deploymentsClient.Delete("demo-deployment", &metav1.DeleteOptions{
PropagationPolicy: &deletePolicy,
}); err != nil {
panic(err)
}
fmt.Println("Deleted deployment.")
}
func prompt() {
fmt.Printf("-> Press Return key to continue.")
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
break
}
if err := scanner.Err(); err != nil {
panic(err)
}
fmt.Println()
}
func int32Ptr(i int32) *int32 { return &i }

View File

@@ -1,14 +0,0 @@
# Fake Client Example
This example demonstrates how to use a fake client with SharedInformerFactory in tests.
It covers:
* Creating the fake client
* Setting up real informers
* Injecting events into those informers
## Running
```
go test -v k8s.io/client-go/examples/fake-client
```

View File

@@ -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.
*/
// Package fakeclient contains examples on how to use fakeclient in tests.
// Note: This file is here to avoid warnings on go build since there are no
// non-test files in this package.
package fakeclient

View File

@@ -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 fakeclient
import (
"context"
"testing"
"time"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/tools/cache"
)
// TestFakeClient demonstrates how to use a fake client with SharedInformerFactory in tests.
func TestFakeClient(t *testing.T) {
// Use a timeout to keep the test from hanging.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// Create the fake client.
client := fake.NewSimpleClientset()
// We will create an informer that writes added pods to a channel.
pods := make(chan *v1.Pod, 1)
informers := informers.NewSharedInformerFactory(client, 0)
podInformer := informers.Core().V1().Pods().Informer()
podInformer.AddEventHandler(&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
pod := obj.(*v1.Pod)
t.Logf("pod added: %s/%s", pod.Namespace, pod.Name)
pods <- pod
cancel()
},
})
// Make sure informers are running.
informers.Start(ctx.Done())
// This is not required in tests, but it serves as a proof-of-concept by
// ensuring that the informer goroutine have warmed up and called List before
// we send any events to it.
for !podInformer.HasSynced() {
time.Sleep(10 * time.Millisecond)
}
// Inject an event into the fake client.
p := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "my-pod"}}
_, err := client.Core().Pods("test-ns").Create(p)
if err != nil {
t.Errorf("error injecting pod add: %v", err)
}
// Wait and check result.
<-ctx.Done()
select {
case pod := <-pods:
t.Logf("Got pod from channel: %s/%s", pod.Namespace, pod.Name)
default:
t.Error("Informer did not get the added pod")
}
}

View File

@@ -1,17 +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.
FROM debian
COPY ./app /app
ENTRYPOINT /app

View File

@@ -1,56 +0,0 @@
# Authenticating inside the cluster
This example shows you how to configure a client with client-go to authenticate
to the Kubernetes API from an application running inside the Kubernetes cluster.
client-go uses the [Service Account token][sa] mounted inside the Pod at the
`/var/run/secrets/kubernetes.io/serviceaccount` path when the
`rest.InClusterConfig()` is used.
## Running this example
First compile the application for Linux:
cd in-cluster-client-configuration
GOOS=linux go build -o ./app .
Then package it to a docker image using the provided Dockerfile to run it on
Kubernetes.
If you are running a [Minikube][mk] cluster, you can build this image directly
on the Docker engine of the Minikube node without pushing it to a registry. To
build the image on Minikube:
eval $(minikube docker-env)
docker build -t in-cluster .
If you are not using Minikube, you should build this image and push it to a registry
that your Kubernetes cluster can pull from. If you have RBAC enabled, use the following
snippet to create role binding which will grant the default service account view
permissions.
```
kubectl create clusterrolebinding default-view --clusterrole=view --serviceaccount=default:default
```
Then, run the image in a Pod with a single instance Deployment:
$ kubectl run --rm -i demo --image=in-cluster --image-pull-policy=Never
There are 4 pods in the cluster
There are 4 pods in the cluster
There are 4 pods in the cluster
...
The example now runs on Kubernetes API and successfully queries the number of
pods in the cluster every 10 seconds.
### Clean up
To stop this example and clean up the pod, press <kbd>Ctrl</kbd>+<kbd>C</kbd> on
the `kubectl run` command and then run:
kubectl delete deployment demo
[sa]: https://kubernetes.io/docs/admin/authentication/#service-account-tokens
[mk]: https://kubernetes.io/docs/getting-started-guides/minikube/

View File

@@ -1,64 +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.
*/
// Note: the example only works with the code within the same release/branch.
package main
import (
"fmt"
"time"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
func main() {
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
for {
pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
// Examples for error handling:
// - Use helper functions like e.g. errors.IsNotFound()
// - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
_, err = clientset.CoreV1().Pods("default").Get("example-xxxxx", metav1.GetOptions{})
if errors.IsNotFound(err) {
fmt.Printf("Pod not found\n")
} else if statusError, isStatus := err.(*errors.StatusError); isStatus {
fmt.Printf("Error getting pod %v\n", statusError.ErrStatus.Message)
} else if err != nil {
panic(err.Error())
} else {
fmt.Printf("Found pod\n")
}
time.Sleep(10 * time.Second)
}
}

View File

@@ -1,35 +0,0 @@
# Authenticating outside the cluster
This example shows you how to configure a client with client-go to authenticate
to the Kubernetes API from an application running outside the Kubernetes
cluster.
You can use your kubeconfig file that contains the context information
of your cluster to initialize a client. The kubeconfig file is also used
by the `kubectl` command to authenticate to the clusters.
## Running this example
Make sure your `kubectl` is configured and pointed to a cluster. Run
`kubectl get nodes` to confirm.
Run this application with:
cd out-of-cluster-client-configuration
go build -o app .
./app
Running this application will use the kubeconfig file and then authenticate to the
cluster, and print the number of nodes in the cluster every 10 seconds:
$ ./app
There are 3 pods in the cluster
There are 3 pods in the cluster
There are 3 pods in the cluster
...
Press <kbd>Ctrl</kbd>+<kbd>C</kbd> to quit this application.
> **Note:** You can use the `-kubeconfig` option to use a different config file. By default
this program picks up the default file used by kubectl (when `KUBECONFIG`
environment variable is not set).

View File

@@ -1,88 +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.
*/
// Note: the example only works with the code within the same release/branch.
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"time"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
// Uncomment the following line to load the gcp plugin (only required to authenticate against GKE clusters).
// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
)
func main() {
var kubeconfig *string
if home := homeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
for {
pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
// Examples for error handling:
// - Use helper functions like e.g. errors.IsNotFound()
// - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
namespace := "default"
pod := "example-xxxxx"
_, err = clientset.CoreV1().Pods(namespace).Get(pod, metav1.GetOptions{})
if errors.IsNotFound(err) {
fmt.Printf("Pod %s in namespace %s not found\n", pod, namespace)
} else if statusError, isStatus := err.(*errors.StatusError); isStatus {
fmt.Printf("Error getting pod %s in namespace %s: %v\n",
pod, namespace, statusError.ErrStatus.Message)
} else if err != nil {
panic(err.Error())
} else {
fmt.Printf("Found pod %s in namespace %s\n", pod, namespace)
}
time.Sleep(10 * time.Second)
}
}
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}

View File

@@ -1,17 +0,0 @@
# Workqueue Example
This example demonstrates how to write a controller which follows the states
of watched resources.
It demonstrates how to:
* combine the workqueue with a cache to a full controller
* synchronize the controller on startup
The example is based on https://git.k8s.io/community/contributors/devel/controllers.md.
## Running
```
# if outside of the cluster
go run *.go -kubeconfig=/my/config -logtostderr=true
```

View File

@@ -1,217 +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 main
import (
"flag"
"fmt"
"time"
"k8s.io/klog"
"k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/workqueue"
)
type Controller struct {
indexer cache.Indexer
queue workqueue.RateLimitingInterface
informer cache.Controller
}
func NewController(queue workqueue.RateLimitingInterface, indexer cache.Indexer, informer cache.Controller) *Controller {
return &Controller{
informer: informer,
indexer: indexer,
queue: queue,
}
}
func (c *Controller) processNextItem() bool {
// Wait until there is a new item in the working queue
key, quit := c.queue.Get()
if quit {
return false
}
// Tell the queue that we are done with processing this key. This unblocks the key for other workers
// This allows safe parallel processing because two pods with the same key are never processed in
// parallel.
defer c.queue.Done(key)
// Invoke the method containing the business logic
err := c.syncToStdout(key.(string))
// Handle the error if something went wrong during the execution of the business logic
c.handleErr(err, key)
return true
}
// syncToStdout is the business logic of the controller. In this controller it simply prints
// information about the pod to stdout. In case an error happened, it has to simply return the error.
// The retry logic should not be part of the business logic.
func (c *Controller) syncToStdout(key string) error {
obj, exists, err := c.indexer.GetByKey(key)
if err != nil {
klog.Errorf("Fetching object with key %s from store failed with %v", key, err)
return err
}
if !exists {
// Below we will warm up our cache with a Pod, so that we will see a delete for one pod
fmt.Printf("Pod %s does not exist anymore\n", key)
} else {
// Note that you also have to check the uid if you have a local controlled resource, which
// is dependent on the actual instance, to detect that a Pod was recreated with the same name
fmt.Printf("Sync/Add/Update for Pod %s\n", obj.(*v1.Pod).GetName())
}
return nil
}
// handleErr checks if an error happened and makes sure we will retry later.
func (c *Controller) handleErr(err error, key interface{}) {
if err == nil {
// Forget about the #AddRateLimited history of the key on every successful synchronization.
// This ensures that future processing of updates for this key is not delayed because of
// an outdated error history.
c.queue.Forget(key)
return
}
// This controller retries 5 times if something goes wrong. After that, it stops trying.
if c.queue.NumRequeues(key) < 5 {
klog.Infof("Error syncing pod %v: %v", key, err)
// Re-enqueue the key rate limited. Based on the rate limiter on the
// queue and the re-enqueue history, the key will be processed later again.
c.queue.AddRateLimited(key)
return
}
c.queue.Forget(key)
// Report to an external entity that, even after several retries, we could not successfully process this key
runtime.HandleError(err)
klog.Infof("Dropping pod %q out of the queue: %v", key, err)
}
func (c *Controller) Run(threadiness int, stopCh chan struct{}) {
defer runtime.HandleCrash()
// Let the workers stop when we are done
defer c.queue.ShutDown()
klog.Info("Starting Pod controller")
go c.informer.Run(stopCh)
// Wait for all involved caches to be synced, before processing items from the queue is started
if !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) {
runtime.HandleError(fmt.Errorf("Timed out waiting for caches to sync"))
return
}
for i := 0; i < threadiness; i++ {
go wait.Until(c.runWorker, time.Second, stopCh)
}
<-stopCh
klog.Info("Stopping Pod controller")
}
func (c *Controller) runWorker() {
for c.processNextItem() {
}
}
func main() {
var kubeconfig string
var master string
flag.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")
flag.StringVar(&master, "master", "", "master url")
flag.Parse()
// creates the connection
config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
if err != nil {
klog.Fatal(err)
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
klog.Fatal(err)
}
// create the pod watcher
podListWatcher := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), "pods", v1.NamespaceDefault, fields.Everything())
// create the workqueue
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())
// Bind the workqueue to a cache with the help of an informer. This way we make sure that
// whenever the cache is updated, the pod key is added to the workqueue.
// Note that when we finally process the item from the workqueue, we might see a newer version
// of the Pod than the version which was responsible for triggering the update.
indexer, informer := cache.NewIndexerInformer(podListWatcher, &v1.Pod{}, 0, cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
UpdateFunc: func(old interface{}, new interface{}) {
key, err := cache.MetaNamespaceKeyFunc(new)
if err == nil {
queue.Add(key)
}
},
DeleteFunc: func(obj interface{}) {
// IndexerInformer uses a delta queue, therefore for deletes we have to use this
// key function.
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
}, cache.Indexers{})
controller := NewController(queue, indexer, informer)
// We can now warm up the cache for initial synchronization.
// Let's suppose that we knew about a pod "mypod" on our last run, therefore add it to the cache.
// If this pod is not there anymore, the controller will be notified about the removal after the
// cache has synchronized.
indexer.Add(&v1.Pod{
ObjectMeta: meta_v1.ObjectMeta{
Name: "mypod",
Namespace: v1.NamespaceDefault,
},
})
// Now let's start the controller
stop := make(chan struct{})
defer close(stop)
go controller.Run(1, stop)
// Wait forever
select {}
}

View File

@@ -1,7 +0,0 @@
approvers:
- sig-auth-authenticators-approvers
reviewers:
- sig-auth-authenticators-reviewers
labels:
- sig/auth

View File

@@ -1,7 +0,0 @@
approvers:
- sig-auth-authorizers-approvers
reviewers:
- sig-auth-authorizers-reviewers
labels:
- sig/auth

View File

@@ -1,7 +0,0 @@
approvers:
- sig-auth-authorizers-approvers
reviewers:
- sig-auth-authorizers-reviewers
labels:
- sig/auth

View File

@@ -1,60 +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 kubernetes_test
import (
"bytes"
"io/ioutil"
"net/http"
"testing"
"github.com/davecgh/go-spew/spew"
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
manualfake "k8s.io/client-go/rest/fake"
)
func TestListTimeout(t *testing.T) {
fakeClient := &manualfake.RESTClient{
GroupVersion: appsv1.SchemeGroupVersion,
NegotiatedSerializer: scheme.Codecs,
Client: manualfake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
if req.URL.Query().Get("timeout") != "21s" {
t.Fatal(spew.Sdump(req.URL.Query()))
}
return &http.Response{StatusCode: http.StatusNotFound, Body: ioutil.NopCloser(&bytes.Buffer{})}, nil
}),
}
clientConfig := &rest.Config{
APIPath: "/apis",
ContentConfig: rest.ContentConfig{
NegotiatedSerializer: scheme.Codecs,
GroupVersion: &appsv1.SchemeGroupVersion,
},
}
restClient, _ := rest.RESTClientFor(clientConfig)
restClient.Client = fakeClient.Client
realClient := kubernetes.New(restClient)
timeout := int64(21)
realClient.AppsV1().DaemonSets("").List(metav1.ListOptions{TimeoutSeconds: &timeout})
realClient.AppsV1().DaemonSets("").Watch(metav1.ListOptions{TimeoutSeconds: &timeout})
}

View File

@@ -1,7 +0,0 @@
approvers:
- sig-auth-authenticators-approvers
reviewers:
- sig-auth-authenticators-reviewers
labels:
- sig/auth

View File

@@ -1,23 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1
// TokenReviewListerExpansion allows custom methods to be added to
// TokenReviewLister.
type TokenReviewListerExpansion interface{}

View File

@@ -1,65 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1
import (
v1 "k8s.io/api/authentication/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// TokenReviewLister helps list TokenReviews.
type TokenReviewLister interface {
// List lists all TokenReviews in the indexer.
List(selector labels.Selector) (ret []*v1.TokenReview, err error)
// Get retrieves the TokenReview from the index for a given name.
Get(name string) (*v1.TokenReview, error)
TokenReviewListerExpansion
}
// tokenReviewLister implements the TokenReviewLister interface.
type tokenReviewLister struct {
indexer cache.Indexer
}
// NewTokenReviewLister returns a new TokenReviewLister.
func NewTokenReviewLister(indexer cache.Indexer) TokenReviewLister {
return &tokenReviewLister{indexer: indexer}
}
// List lists all TokenReviews in the indexer.
func (s *tokenReviewLister) List(selector labels.Selector) (ret []*v1.TokenReview, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1.TokenReview))
})
return ret, err
}
// Get retrieves the TokenReview from the index for a given name.
func (s *tokenReviewLister) Get(name string) (*v1.TokenReview, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1.Resource("tokenreview"), name)
}
return obj.(*v1.TokenReview), nil
}

View File

@@ -1,23 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1beta1
// TokenReviewListerExpansion allows custom methods to be added to
// TokenReviewLister.
type TokenReviewListerExpansion interface{}

View File

@@ -1,65 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1beta1
import (
v1beta1 "k8s.io/api/authentication/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// TokenReviewLister helps list TokenReviews.
type TokenReviewLister interface {
// List lists all TokenReviews in the indexer.
List(selector labels.Selector) (ret []*v1beta1.TokenReview, err error)
// Get retrieves the TokenReview from the index for a given name.
Get(name string) (*v1beta1.TokenReview, error)
TokenReviewListerExpansion
}
// tokenReviewLister implements the TokenReviewLister interface.
type tokenReviewLister struct {
indexer cache.Indexer
}
// NewTokenReviewLister returns a new TokenReviewLister.
func NewTokenReviewLister(indexer cache.Indexer) TokenReviewLister {
return &tokenReviewLister{indexer: indexer}
}
// List lists all TokenReviews in the indexer.
func (s *tokenReviewLister) List(selector labels.Selector) (ret []*v1beta1.TokenReview, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1beta1.TokenReview))
})
return ret, err
}
// Get retrieves the TokenReview from the index for a given name.
func (s *tokenReviewLister) Get(name string) (*v1beta1.TokenReview, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1beta1.Resource("tokenreview"), name)
}
return obj.(*v1beta1.TokenReview), nil
}

View File

@@ -1,7 +0,0 @@
approvers:
- sig-auth-authorizers-approvers
reviewers:
- sig-auth-authorizers-reviewers
labels:
- sig/auth

View File

@@ -1,39 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1
// LocalSubjectAccessReviewListerExpansion allows custom methods to be added to
// LocalSubjectAccessReviewLister.
type LocalSubjectAccessReviewListerExpansion interface{}
// LocalSubjectAccessReviewNamespaceListerExpansion allows custom methods to be added to
// LocalSubjectAccessReviewNamespaceLister.
type LocalSubjectAccessReviewNamespaceListerExpansion interface{}
// SelfSubjectAccessReviewListerExpansion allows custom methods to be added to
// SelfSubjectAccessReviewLister.
type SelfSubjectAccessReviewListerExpansion interface{}
// SelfSubjectRulesReviewListerExpansion allows custom methods to be added to
// SelfSubjectRulesReviewLister.
type SelfSubjectRulesReviewListerExpansion interface{}
// SubjectAccessReviewListerExpansion allows custom methods to be added to
// SubjectAccessReviewLister.
type SubjectAccessReviewListerExpansion interface{}

View File

@@ -1,94 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1
import (
v1 "k8s.io/api/authorization/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// LocalSubjectAccessReviewLister helps list LocalSubjectAccessReviews.
type LocalSubjectAccessReviewLister interface {
// List lists all LocalSubjectAccessReviews in the indexer.
List(selector labels.Selector) (ret []*v1.LocalSubjectAccessReview, err error)
// LocalSubjectAccessReviews returns an object that can list and get LocalSubjectAccessReviews.
LocalSubjectAccessReviews(namespace string) LocalSubjectAccessReviewNamespaceLister
LocalSubjectAccessReviewListerExpansion
}
// localSubjectAccessReviewLister implements the LocalSubjectAccessReviewLister interface.
type localSubjectAccessReviewLister struct {
indexer cache.Indexer
}
// NewLocalSubjectAccessReviewLister returns a new LocalSubjectAccessReviewLister.
func NewLocalSubjectAccessReviewLister(indexer cache.Indexer) LocalSubjectAccessReviewLister {
return &localSubjectAccessReviewLister{indexer: indexer}
}
// List lists all LocalSubjectAccessReviews in the indexer.
func (s *localSubjectAccessReviewLister) List(selector labels.Selector) (ret []*v1.LocalSubjectAccessReview, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1.LocalSubjectAccessReview))
})
return ret, err
}
// LocalSubjectAccessReviews returns an object that can list and get LocalSubjectAccessReviews.
func (s *localSubjectAccessReviewLister) LocalSubjectAccessReviews(namespace string) LocalSubjectAccessReviewNamespaceLister {
return localSubjectAccessReviewNamespaceLister{indexer: s.indexer, namespace: namespace}
}
// LocalSubjectAccessReviewNamespaceLister helps list and get LocalSubjectAccessReviews.
type LocalSubjectAccessReviewNamespaceLister interface {
// List lists all LocalSubjectAccessReviews in the indexer for a given namespace.
List(selector labels.Selector) (ret []*v1.LocalSubjectAccessReview, err error)
// Get retrieves the LocalSubjectAccessReview from the indexer for a given namespace and name.
Get(name string) (*v1.LocalSubjectAccessReview, error)
LocalSubjectAccessReviewNamespaceListerExpansion
}
// localSubjectAccessReviewNamespaceLister implements the LocalSubjectAccessReviewNamespaceLister
// interface.
type localSubjectAccessReviewNamespaceLister struct {
indexer cache.Indexer
namespace string
}
// List lists all LocalSubjectAccessReviews in the indexer for a given namespace.
func (s localSubjectAccessReviewNamespaceLister) List(selector labels.Selector) (ret []*v1.LocalSubjectAccessReview, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v1.LocalSubjectAccessReview))
})
return ret, err
}
// Get retrieves the LocalSubjectAccessReview from the indexer for a given namespace and name.
func (s localSubjectAccessReviewNamespaceLister) Get(name string) (*v1.LocalSubjectAccessReview, error) {
obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1.Resource("localsubjectaccessreview"), name)
}
return obj.(*v1.LocalSubjectAccessReview), nil
}

View File

@@ -1,65 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1
import (
v1 "k8s.io/api/authorization/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// SelfSubjectAccessReviewLister helps list SelfSubjectAccessReviews.
type SelfSubjectAccessReviewLister interface {
// List lists all SelfSubjectAccessReviews in the indexer.
List(selector labels.Selector) (ret []*v1.SelfSubjectAccessReview, err error)
// Get retrieves the SelfSubjectAccessReview from the index for a given name.
Get(name string) (*v1.SelfSubjectAccessReview, error)
SelfSubjectAccessReviewListerExpansion
}
// selfSubjectAccessReviewLister implements the SelfSubjectAccessReviewLister interface.
type selfSubjectAccessReviewLister struct {
indexer cache.Indexer
}
// NewSelfSubjectAccessReviewLister returns a new SelfSubjectAccessReviewLister.
func NewSelfSubjectAccessReviewLister(indexer cache.Indexer) SelfSubjectAccessReviewLister {
return &selfSubjectAccessReviewLister{indexer: indexer}
}
// List lists all SelfSubjectAccessReviews in the indexer.
func (s *selfSubjectAccessReviewLister) List(selector labels.Selector) (ret []*v1.SelfSubjectAccessReview, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1.SelfSubjectAccessReview))
})
return ret, err
}
// Get retrieves the SelfSubjectAccessReview from the index for a given name.
func (s *selfSubjectAccessReviewLister) Get(name string) (*v1.SelfSubjectAccessReview, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1.Resource("selfsubjectaccessreview"), name)
}
return obj.(*v1.SelfSubjectAccessReview), nil
}

View File

@@ -1,65 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1
import (
v1 "k8s.io/api/authorization/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// SelfSubjectRulesReviewLister helps list SelfSubjectRulesReviews.
type SelfSubjectRulesReviewLister interface {
// List lists all SelfSubjectRulesReviews in the indexer.
List(selector labels.Selector) (ret []*v1.SelfSubjectRulesReview, err error)
// Get retrieves the SelfSubjectRulesReview from the index for a given name.
Get(name string) (*v1.SelfSubjectRulesReview, error)
SelfSubjectRulesReviewListerExpansion
}
// selfSubjectRulesReviewLister implements the SelfSubjectRulesReviewLister interface.
type selfSubjectRulesReviewLister struct {
indexer cache.Indexer
}
// NewSelfSubjectRulesReviewLister returns a new SelfSubjectRulesReviewLister.
func NewSelfSubjectRulesReviewLister(indexer cache.Indexer) SelfSubjectRulesReviewLister {
return &selfSubjectRulesReviewLister{indexer: indexer}
}
// List lists all SelfSubjectRulesReviews in the indexer.
func (s *selfSubjectRulesReviewLister) List(selector labels.Selector) (ret []*v1.SelfSubjectRulesReview, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1.SelfSubjectRulesReview))
})
return ret, err
}
// Get retrieves the SelfSubjectRulesReview from the index for a given name.
func (s *selfSubjectRulesReviewLister) Get(name string) (*v1.SelfSubjectRulesReview, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1.Resource("selfsubjectrulesreview"), name)
}
return obj.(*v1.SelfSubjectRulesReview), nil
}

View File

@@ -1,65 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1
import (
v1 "k8s.io/api/authorization/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// SubjectAccessReviewLister helps list SubjectAccessReviews.
type SubjectAccessReviewLister interface {
// List lists all SubjectAccessReviews in the indexer.
List(selector labels.Selector) (ret []*v1.SubjectAccessReview, err error)
// Get retrieves the SubjectAccessReview from the index for a given name.
Get(name string) (*v1.SubjectAccessReview, error)
SubjectAccessReviewListerExpansion
}
// subjectAccessReviewLister implements the SubjectAccessReviewLister interface.
type subjectAccessReviewLister struct {
indexer cache.Indexer
}
// NewSubjectAccessReviewLister returns a new SubjectAccessReviewLister.
func NewSubjectAccessReviewLister(indexer cache.Indexer) SubjectAccessReviewLister {
return &subjectAccessReviewLister{indexer: indexer}
}
// List lists all SubjectAccessReviews in the indexer.
func (s *subjectAccessReviewLister) List(selector labels.Selector) (ret []*v1.SubjectAccessReview, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1.SubjectAccessReview))
})
return ret, err
}
// Get retrieves the SubjectAccessReview from the index for a given name.
func (s *subjectAccessReviewLister) Get(name string) (*v1.SubjectAccessReview, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1.Resource("subjectaccessreview"), name)
}
return obj.(*v1.SubjectAccessReview), nil
}

View File

@@ -1,39 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1beta1
// LocalSubjectAccessReviewListerExpansion allows custom methods to be added to
// LocalSubjectAccessReviewLister.
type LocalSubjectAccessReviewListerExpansion interface{}
// LocalSubjectAccessReviewNamespaceListerExpansion allows custom methods to be added to
// LocalSubjectAccessReviewNamespaceLister.
type LocalSubjectAccessReviewNamespaceListerExpansion interface{}
// SelfSubjectAccessReviewListerExpansion allows custom methods to be added to
// SelfSubjectAccessReviewLister.
type SelfSubjectAccessReviewListerExpansion interface{}
// SelfSubjectRulesReviewListerExpansion allows custom methods to be added to
// SelfSubjectRulesReviewLister.
type SelfSubjectRulesReviewListerExpansion interface{}
// SubjectAccessReviewListerExpansion allows custom methods to be added to
// SubjectAccessReviewLister.
type SubjectAccessReviewListerExpansion interface{}

View File

@@ -1,94 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1beta1
import (
v1beta1 "k8s.io/api/authorization/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// LocalSubjectAccessReviewLister helps list LocalSubjectAccessReviews.
type LocalSubjectAccessReviewLister interface {
// List lists all LocalSubjectAccessReviews in the indexer.
List(selector labels.Selector) (ret []*v1beta1.LocalSubjectAccessReview, err error)
// LocalSubjectAccessReviews returns an object that can list and get LocalSubjectAccessReviews.
LocalSubjectAccessReviews(namespace string) LocalSubjectAccessReviewNamespaceLister
LocalSubjectAccessReviewListerExpansion
}
// localSubjectAccessReviewLister implements the LocalSubjectAccessReviewLister interface.
type localSubjectAccessReviewLister struct {
indexer cache.Indexer
}
// NewLocalSubjectAccessReviewLister returns a new LocalSubjectAccessReviewLister.
func NewLocalSubjectAccessReviewLister(indexer cache.Indexer) LocalSubjectAccessReviewLister {
return &localSubjectAccessReviewLister{indexer: indexer}
}
// List lists all LocalSubjectAccessReviews in the indexer.
func (s *localSubjectAccessReviewLister) List(selector labels.Selector) (ret []*v1beta1.LocalSubjectAccessReview, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1beta1.LocalSubjectAccessReview))
})
return ret, err
}
// LocalSubjectAccessReviews returns an object that can list and get LocalSubjectAccessReviews.
func (s *localSubjectAccessReviewLister) LocalSubjectAccessReviews(namespace string) LocalSubjectAccessReviewNamespaceLister {
return localSubjectAccessReviewNamespaceLister{indexer: s.indexer, namespace: namespace}
}
// LocalSubjectAccessReviewNamespaceLister helps list and get LocalSubjectAccessReviews.
type LocalSubjectAccessReviewNamespaceLister interface {
// List lists all LocalSubjectAccessReviews in the indexer for a given namespace.
List(selector labels.Selector) (ret []*v1beta1.LocalSubjectAccessReview, err error)
// Get retrieves the LocalSubjectAccessReview from the indexer for a given namespace and name.
Get(name string) (*v1beta1.LocalSubjectAccessReview, error)
LocalSubjectAccessReviewNamespaceListerExpansion
}
// localSubjectAccessReviewNamespaceLister implements the LocalSubjectAccessReviewNamespaceLister
// interface.
type localSubjectAccessReviewNamespaceLister struct {
indexer cache.Indexer
namespace string
}
// List lists all LocalSubjectAccessReviews in the indexer for a given namespace.
func (s localSubjectAccessReviewNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.LocalSubjectAccessReview, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v1beta1.LocalSubjectAccessReview))
})
return ret, err
}
// Get retrieves the LocalSubjectAccessReview from the indexer for a given namespace and name.
func (s localSubjectAccessReviewNamespaceLister) Get(name string) (*v1beta1.LocalSubjectAccessReview, error) {
obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1beta1.Resource("localsubjectaccessreview"), name)
}
return obj.(*v1beta1.LocalSubjectAccessReview), nil
}

View File

@@ -1,65 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1beta1
import (
v1beta1 "k8s.io/api/authorization/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// SelfSubjectAccessReviewLister helps list SelfSubjectAccessReviews.
type SelfSubjectAccessReviewLister interface {
// List lists all SelfSubjectAccessReviews in the indexer.
List(selector labels.Selector) (ret []*v1beta1.SelfSubjectAccessReview, err error)
// Get retrieves the SelfSubjectAccessReview from the index for a given name.
Get(name string) (*v1beta1.SelfSubjectAccessReview, error)
SelfSubjectAccessReviewListerExpansion
}
// selfSubjectAccessReviewLister implements the SelfSubjectAccessReviewLister interface.
type selfSubjectAccessReviewLister struct {
indexer cache.Indexer
}
// NewSelfSubjectAccessReviewLister returns a new SelfSubjectAccessReviewLister.
func NewSelfSubjectAccessReviewLister(indexer cache.Indexer) SelfSubjectAccessReviewLister {
return &selfSubjectAccessReviewLister{indexer: indexer}
}
// List lists all SelfSubjectAccessReviews in the indexer.
func (s *selfSubjectAccessReviewLister) List(selector labels.Selector) (ret []*v1beta1.SelfSubjectAccessReview, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1beta1.SelfSubjectAccessReview))
})
return ret, err
}
// Get retrieves the SelfSubjectAccessReview from the index for a given name.
func (s *selfSubjectAccessReviewLister) Get(name string) (*v1beta1.SelfSubjectAccessReview, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1beta1.Resource("selfsubjectaccessreview"), name)
}
return obj.(*v1beta1.SelfSubjectAccessReview), nil
}

View File

@@ -1,65 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1beta1
import (
v1beta1 "k8s.io/api/authorization/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// SelfSubjectRulesReviewLister helps list SelfSubjectRulesReviews.
type SelfSubjectRulesReviewLister interface {
// List lists all SelfSubjectRulesReviews in the indexer.
List(selector labels.Selector) (ret []*v1beta1.SelfSubjectRulesReview, err error)
// Get retrieves the SelfSubjectRulesReview from the index for a given name.
Get(name string) (*v1beta1.SelfSubjectRulesReview, error)
SelfSubjectRulesReviewListerExpansion
}
// selfSubjectRulesReviewLister implements the SelfSubjectRulesReviewLister interface.
type selfSubjectRulesReviewLister struct {
indexer cache.Indexer
}
// NewSelfSubjectRulesReviewLister returns a new SelfSubjectRulesReviewLister.
func NewSelfSubjectRulesReviewLister(indexer cache.Indexer) SelfSubjectRulesReviewLister {
return &selfSubjectRulesReviewLister{indexer: indexer}
}
// List lists all SelfSubjectRulesReviews in the indexer.
func (s *selfSubjectRulesReviewLister) List(selector labels.Selector) (ret []*v1beta1.SelfSubjectRulesReview, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1beta1.SelfSubjectRulesReview))
})
return ret, err
}
// Get retrieves the SelfSubjectRulesReview from the index for a given name.
func (s *selfSubjectRulesReviewLister) Get(name string) (*v1beta1.SelfSubjectRulesReview, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1beta1.Resource("selfsubjectrulesreview"), name)
}
return obj.(*v1beta1.SelfSubjectRulesReview), nil
}

View File

@@ -1,65 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1beta1
import (
v1beta1 "k8s.io/api/authorization/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// SubjectAccessReviewLister helps list SubjectAccessReviews.
type SubjectAccessReviewLister interface {
// List lists all SubjectAccessReviews in the indexer.
List(selector labels.Selector) (ret []*v1beta1.SubjectAccessReview, err error)
// Get retrieves the SubjectAccessReview from the index for a given name.
Get(name string) (*v1beta1.SubjectAccessReview, error)
SubjectAccessReviewListerExpansion
}
// subjectAccessReviewLister implements the SubjectAccessReviewLister interface.
type subjectAccessReviewLister struct {
indexer cache.Indexer
}
// NewSubjectAccessReviewLister returns a new SubjectAccessReviewLister.
func NewSubjectAccessReviewLister(indexer cache.Indexer) SubjectAccessReviewLister {
return &subjectAccessReviewLister{indexer: indexer}
}
// List lists all SubjectAccessReviews in the indexer.
func (s *subjectAccessReviewLister) List(selector labels.Selector) (ret []*v1beta1.SubjectAccessReview, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1beta1.SubjectAccessReview))
})
return ret, err
}
// Get retrieves the SubjectAccessReview from the index for a given name.
func (s *subjectAccessReviewLister) Get(name string) (*v1beta1.SubjectAccessReview, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1beta1.Resource("subjectaccessreview"), name)
}
return obj.(*v1beta1.SubjectAccessReview), nil
}

View File

@@ -1,152 +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 v1beta1
import (
"testing"
"k8s.io/api/core/v1"
extensions "k8s.io/api/extensions/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/tools/cache"
)
func TestDaemonSetLister(t *testing.T) {
store := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{"namespace": cache.MetaNamespaceIndexFunc})
lister := NewDaemonSetLister(store)
testCases := []struct {
inDSs []*extensions.DaemonSet
list func() ([]*extensions.DaemonSet, error)
outDaemonSetNames sets.String
expectErr bool
}{
// Basic listing
{
inDSs: []*extensions.DaemonSet{
{ObjectMeta: metav1.ObjectMeta{Name: "basic"}},
},
list: func() ([]*extensions.DaemonSet, error) {
return lister.List(labels.Everything())
},
outDaemonSetNames: sets.NewString("basic"),
},
// Listing multiple daemon sets
{
inDSs: []*extensions.DaemonSet{
{ObjectMeta: metav1.ObjectMeta{Name: "basic"}},
{ObjectMeta: metav1.ObjectMeta{Name: "complex"}},
{ObjectMeta: metav1.ObjectMeta{Name: "complex2"}},
},
list: func() ([]*extensions.DaemonSet, error) {
return lister.List(labels.Everything())
},
outDaemonSetNames: sets.NewString("basic", "complex", "complex2"),
},
// No pod labels
{
inDSs: []*extensions.DaemonSet{
{
ObjectMeta: metav1.ObjectMeta{Name: "basic", Namespace: "ns"},
Spec: extensions.DaemonSetSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"foo": "baz"}},
},
},
},
list: func() ([]*extensions.DaemonSet, error) {
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "pod1", Namespace: "ns"},
}
return lister.GetPodDaemonSets(pod)
},
outDaemonSetNames: sets.NewString(),
expectErr: true,
},
// No DS selectors
{
inDSs: []*extensions.DaemonSet{
{
ObjectMeta: metav1.ObjectMeta{Name: "basic", Namespace: "ns"},
},
},
list: func() ([]*extensions.DaemonSet, error) {
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "pod1",
Namespace: "ns",
Labels: map[string]string{"foo": "bar"},
},
}
return lister.GetPodDaemonSets(pod)
},
outDaemonSetNames: sets.NewString(),
expectErr: true,
},
// Matching labels to selectors and namespace
{
inDSs: []*extensions.DaemonSet{
{
ObjectMeta: metav1.ObjectMeta{Name: "foo"},
Spec: extensions.DaemonSetSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}},
},
},
{
ObjectMeta: metav1.ObjectMeta{Name: "bar", Namespace: "ns"},
Spec: extensions.DaemonSetSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}},
},
},
},
list: func() ([]*extensions.DaemonSet, error) {
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "pod1",
Labels: map[string]string{"foo": "bar"},
Namespace: "ns",
},
}
return lister.GetPodDaemonSets(pod)
},
outDaemonSetNames: sets.NewString("bar"),
},
}
for _, c := range testCases {
for _, r := range c.inDSs {
store.Add(r)
}
daemonSets, err := c.list()
if err != nil && c.expectErr {
continue
} else if c.expectErr {
t.Error("Expected error, got none")
continue
} else if err != nil {
t.Errorf("Unexpected error %#v", err)
continue
}
daemonSetNames := make([]string, len(daemonSets))
for ix := range daemonSets {
daemonSetNames[ix] = daemonSets[ix].Name
}
if !c.outDaemonSetNames.HasAll(daemonSetNames...) || len(daemonSetNames) != len(c.outDaemonSetNames) {
t.Errorf("Unexpected got controllers %+v expected %+v", daemonSetNames, c.outDaemonSetNames)
}
}
}

View File

@@ -1,23 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1alpha1
// ImageReviewListerExpansion allows custom methods to be added to
// ImageReviewLister.
type ImageReviewListerExpansion interface{}

View File

@@ -1,65 +0,0 @@
/*
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 lister-gen. DO NOT EDIT.
package v1alpha1
import (
v1alpha1 "k8s.io/api/imagepolicy/v1alpha1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// ImageReviewLister helps list ImageReviews.
type ImageReviewLister interface {
// List lists all ImageReviews in the indexer.
List(selector labels.Selector) (ret []*v1alpha1.ImageReview, err error)
// Get retrieves the ImageReview from the index for a given name.
Get(name string) (*v1alpha1.ImageReview, error)
ImageReviewListerExpansion
}
// imageReviewLister implements the ImageReviewLister interface.
type imageReviewLister struct {
indexer cache.Indexer
}
// NewImageReviewLister returns a new ImageReviewLister.
func NewImageReviewLister(indexer cache.Indexer) ImageReviewLister {
return &imageReviewLister{indexer: indexer}
}
// List lists all ImageReviews in the indexer.
func (s *imageReviewLister) List(selector labels.Selector) (ret []*v1alpha1.ImageReview, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.ImageReview))
})
return ret, err
}
// Get retrieves the ImageReview from the index for a given name.
func (s *imageReviewLister) Get(name string) (*v1alpha1.ImageReview, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1alpha1.Resource("imagereview"), name)
}
return obj.(*v1alpha1.ImageReview), nil
}

View File

@@ -1,7 +0,0 @@
approvers:
- sig-auth-authorizers-approvers
reviewers:
- sig-auth-authorizers-reviewers
labels:
- sig/auth

View File

@@ -1,7 +0,0 @@
# approval on api packages bubbles to api-approvers
reviewers:
- sig-auth-authenticators-approvers
- sig-auth-authenticators-reviewers
labels:
- sig/auth

View File

@@ -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 install installs the experimental API group, making it available as
// an option to all of the API encoding/decoding machinery.
package install
import (
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/pkg/apis/clientauthentication"
"k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1"
)
// Install registers the API group and adds types to a scheme
func Install(scheme *runtime.Scheme) {
utilruntime.Must(clientauthentication.AddToScheme(scheme))
utilruntime.Must(v1alpha1.AddToScheme(scheme))
utilruntime.Must(scheme.SetVersionPriority(v1alpha1.SchemeGroupVersion))
}

View File

@@ -1 +0,0 @@
base.go export-subst

View File

@@ -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

View File

@@ -1,7 +0,0 @@
approvers:
- sig-auth-authenticators-approvers
reviewers:
- sig-auth-authenticators-reviewers
labels:
- sig/auth

View File

@@ -1,50 +0,0 @@
# Azure Active Directory plugin for client authentication
This plugin provides an integration with Azure Active Directory device flow. If no tokens are present in the kubectl configuration, it will prompt a device code which can be used to login in a browser. After login it will automatically fetch the tokens and store them in the kubectl configuration. In addition it will refresh and update the tokens in the configuration when expired.
## Usage
1. Create an Azure Active Directory *Web App / API* application for `apiserver` following these [instructions](https://docs.microsoft.com/en-us/azure/active-directory/active-directory-app-registration). The callback URL does not matter (just cannot be empty).
2. Create a second Azure Active Directory native application for `kubectl`. The callback URL does not matter (just cannot be empty).
3. On `kubectl` application's configuration page in Azure portal grant permissions to `apiserver` application by clicking on *Required Permissions*, click the *Add* button and search for the apiserver application created in step 1. Select "Access apiserver" under the *DELEGATED PERMISSIONS*. Once added click the *Grant Permissions* button to apply the changes.
4. Configure the `apiserver` to use the Azure Active Directory as an OIDC provider with following options
```
--oidc-client-id="spn:APISERVER_APPLICATION_ID" \
--oidc-issuer-url="https://sts.windows.net/TENANT_ID/"
--oidc-username-claim="sub"
```
* Replace the `APISERVER_APPLICATION_ID` with the application ID of `apiserver` application
* Replace `TENANT_ID` with your tenant ID.
  * For a list of alternative username claims that are supported by the OIDC issuer check the JSON response at `https://sts.windows.net/TENANT_ID/.well-known/openid-configuration`.
5. Configure `kubectl` to use the `azure` authentication provider
```
kubectl config set-credentials "USER_NAME" --auth-provider=azure \
--auth-provider-arg=environment=AzurePublicCloud \
--auth-provider-arg=client-id=APPLICATION_ID \
--auth-provider-arg=tenant-id=TENANT_ID \
--auth-provider-arg=apiserver-id=APISERVER_APPLICATION_ID
```
* Supported environments: `AzurePublicCloud`, `AzureUSGovernmentCloud`, `AzureChinaCloud`, `AzureGermanCloud`
* Replace `USER_NAME` and `TENANT_ID` with your user name and tenant ID
* Replace `APPLICATION_ID` with the application ID of your`kubectl` application ID
* Replace `APISERVER_APPLICATION_ID` with the application ID of your `apiserver` application ID
* Be sure to also (create and) select a context that uses above user
6. The access token is acquired when first `kubectl` command is executed
```
kubectl get pods
To sign in, use a web browser to open the page https://aka.ms/devicelogin and enter the code DEC7D48GA to authenticate.
```
* After signing in a web browser, the token is stored in the configuration, and it will be reused when executing further commands.
* The resulting username in Kubernetes depends on your [configuration of the `--oidc-username-claim` and `--oidc-username-prefix` flags on the API server](https://kubernetes.io/docs/admin/authentication/#configuring-the-api-server). If you are using any authorization method you need to give permissions to that user, e.g. by binding the user to a role in the case of RBAC.

View File

@@ -1,360 +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 azure
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"sync"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure"
"k8s.io/klog"
"k8s.io/apimachinery/pkg/util/net"
restclient "k8s.io/client-go/rest"
)
const (
azureTokenKey = "azureTokenKey"
tokenType = "Bearer"
authHeader = "Authorization"
cfgClientID = "client-id"
cfgTenantID = "tenant-id"
cfgAccessToken = "access-token"
cfgRefreshToken = "refresh-token"
cfgExpiresIn = "expires-in"
cfgExpiresOn = "expires-on"
cfgEnvironment = "environment"
cfgApiserverID = "apiserver-id"
)
func init() {
if err := restclient.RegisterAuthProviderPlugin("azure", newAzureAuthProvider); err != nil {
klog.Fatalf("Failed to register azure auth plugin: %v", err)
}
}
var cache = newAzureTokenCache()
type azureTokenCache struct {
lock sync.Mutex
cache map[string]*azureToken
}
func newAzureTokenCache() *azureTokenCache {
return &azureTokenCache{cache: make(map[string]*azureToken)}
}
func (c *azureTokenCache) getToken(tokenKey string) *azureToken {
c.lock.Lock()
defer c.lock.Unlock()
return c.cache[tokenKey]
}
func (c *azureTokenCache) setToken(tokenKey string, token *azureToken) {
c.lock.Lock()
defer c.lock.Unlock()
c.cache[tokenKey] = token
}
func newAzureAuthProvider(_ string, cfg map[string]string, persister restclient.AuthProviderConfigPersister) (restclient.AuthProvider, error) {
var ts tokenSource
environment, err := azure.EnvironmentFromName(cfg[cfgEnvironment])
if err != nil {
environment = azure.PublicCloud
}
ts, err = newAzureTokenSourceDeviceCode(environment, cfg[cfgClientID], cfg[cfgTenantID], cfg[cfgApiserverID])
if err != nil {
return nil, fmt.Errorf("creating a new azure token source for device code authentication: %v", err)
}
cacheSource := newAzureTokenSource(ts, cache, cfg, persister)
return &azureAuthProvider{
tokenSource: cacheSource,
}, nil
}
type azureAuthProvider struct {
tokenSource tokenSource
}
func (p *azureAuthProvider) Login() error {
return errors.New("not yet implemented")
}
func (p *azureAuthProvider) WrapTransport(rt http.RoundTripper) http.RoundTripper {
return &azureRoundTripper{
tokenSource: p.tokenSource,
roundTripper: rt,
}
}
type azureRoundTripper struct {
tokenSource tokenSource
roundTripper http.RoundTripper
}
var _ net.RoundTripperWrapper = &azureRoundTripper{}
func (r *azureRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
if len(req.Header.Get(authHeader)) != 0 {
return r.roundTripper.RoundTrip(req)
}
token, err := r.tokenSource.Token()
if err != nil {
klog.Errorf("Failed to acquire a token: %v", err)
return nil, fmt.Errorf("acquiring a token for authorization header: %v", err)
}
// clone the request in order to avoid modifying the headers of the original request
req2 := new(http.Request)
*req2 = *req
req2.Header = make(http.Header, len(req.Header))
for k, s := range req.Header {
req2.Header[k] = append([]string(nil), s...)
}
req2.Header.Set(authHeader, fmt.Sprintf("%s %s", tokenType, token.token.AccessToken))
return r.roundTripper.RoundTrip(req2)
}
func (r *azureRoundTripper) WrappedRoundTripper() http.RoundTripper { return r.roundTripper }
type azureToken struct {
token adal.Token
clientID string
tenantID string
apiserverID string
}
type tokenSource interface {
Token() (*azureToken, error)
}
type azureTokenSource struct {
source tokenSource
cache *azureTokenCache
lock sync.Mutex
cfg map[string]string
persister restclient.AuthProviderConfigPersister
}
func newAzureTokenSource(source tokenSource, cache *azureTokenCache, cfg map[string]string, persister restclient.AuthProviderConfigPersister) tokenSource {
return &azureTokenSource{
source: source,
cache: cache,
cfg: cfg,
persister: persister,
}
}
// Token fetches a token from the cache of configuration if present otherwise
// acquires a new token from the configured source. Automatically refreshes
// the token if expired.
func (ts *azureTokenSource) Token() (*azureToken, error) {
ts.lock.Lock()
defer ts.lock.Unlock()
var err error
token := ts.cache.getToken(azureTokenKey)
if token == nil {
token, err = ts.retrieveTokenFromCfg()
if err != nil {
token, err = ts.source.Token()
if err != nil {
return nil, fmt.Errorf("acquiring a new fresh token: %v", err)
}
}
if !token.token.IsExpired() {
ts.cache.setToken(azureTokenKey, token)
err = ts.storeTokenInCfg(token)
if err != nil {
return nil, fmt.Errorf("storing the token in configuration: %v", err)
}
}
}
if token.token.IsExpired() {
token, err = ts.refreshToken(token)
if err != nil {
return nil, fmt.Errorf("refreshing the expired token: %v", err)
}
ts.cache.setToken(azureTokenKey, token)
err = ts.storeTokenInCfg(token)
if err != nil {
return nil, fmt.Errorf("storing the refreshed token in configuration: %v", err)
}
}
return token, nil
}
func (ts *azureTokenSource) retrieveTokenFromCfg() (*azureToken, error) {
accessToken := ts.cfg[cfgAccessToken]
if accessToken == "" {
return nil, fmt.Errorf("no access token in cfg: %s", cfgAccessToken)
}
refreshToken := ts.cfg[cfgRefreshToken]
if refreshToken == "" {
return nil, fmt.Errorf("no refresh token in cfg: %s", cfgRefreshToken)
}
clientID := ts.cfg[cfgClientID]
if clientID == "" {
return nil, fmt.Errorf("no client ID in cfg: %s", cfgClientID)
}
tenantID := ts.cfg[cfgTenantID]
if tenantID == "" {
return nil, fmt.Errorf("no tenant ID in cfg: %s", cfgTenantID)
}
apiserverID := ts.cfg[cfgApiserverID]
if apiserverID == "" {
return nil, fmt.Errorf("no apiserver ID in cfg: %s", apiserverID)
}
expiresIn := ts.cfg[cfgExpiresIn]
if expiresIn == "" {
return nil, fmt.Errorf("no expiresIn in cfg: %s", cfgExpiresIn)
}
expiresOn := ts.cfg[cfgExpiresOn]
if expiresOn == "" {
return nil, fmt.Errorf("no expiresOn in cfg: %s", cfgExpiresOn)
}
return &azureToken{
token: adal.Token{
AccessToken: accessToken,
RefreshToken: refreshToken,
ExpiresIn: json.Number(expiresIn),
ExpiresOn: json.Number(expiresOn),
NotBefore: json.Number(expiresOn),
Resource: fmt.Sprintf("spn:%s", apiserverID),
Type: tokenType,
},
clientID: clientID,
tenantID: tenantID,
apiserverID: apiserverID,
}, nil
}
func (ts *azureTokenSource) storeTokenInCfg(token *azureToken) error {
newCfg := make(map[string]string)
newCfg[cfgAccessToken] = token.token.AccessToken
newCfg[cfgRefreshToken] = token.token.RefreshToken
newCfg[cfgClientID] = token.clientID
newCfg[cfgTenantID] = token.tenantID
newCfg[cfgApiserverID] = token.apiserverID
newCfg[cfgExpiresIn] = string(token.token.ExpiresIn)
newCfg[cfgExpiresOn] = string(token.token.ExpiresOn)
err := ts.persister.Persist(newCfg)
if err != nil {
return fmt.Errorf("persisting the configuration: %v", err)
}
ts.cfg = newCfg
return nil
}
func (ts *azureTokenSource) refreshToken(token *azureToken) (*azureToken, error) {
oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, token.tenantID)
if err != nil {
return nil, fmt.Errorf("building the OAuth configuration for token refresh: %v", err)
}
callback := func(t adal.Token) error {
return nil
}
spt, err := adal.NewServicePrincipalTokenFromManualToken(
*oauthConfig,
token.clientID,
token.apiserverID,
token.token,
callback)
if err != nil {
return nil, fmt.Errorf("creating new service principal for token refresh: %v", err)
}
if err := spt.Refresh(); err != nil {
return nil, fmt.Errorf("refreshing token: %v", err)
}
return &azureToken{
token: spt.Token(),
clientID: token.clientID,
tenantID: token.tenantID,
apiserverID: token.apiserverID,
}, nil
}
type azureTokenSourceDeviceCode struct {
environment azure.Environment
clientID string
tenantID string
apiserverID string
}
func newAzureTokenSourceDeviceCode(environment azure.Environment, clientID string, tenantID string, apiserverID string) (tokenSource, error) {
if clientID == "" {
return nil, errors.New("client-id is empty")
}
if tenantID == "" {
return nil, errors.New("tenant-id is empty")
}
if apiserverID == "" {
return nil, errors.New("apiserver-id is empty")
}
return &azureTokenSourceDeviceCode{
environment: environment,
clientID: clientID,
tenantID: tenantID,
apiserverID: apiserverID,
}, nil
}
func (ts *azureTokenSourceDeviceCode) Token() (*azureToken, error) {
oauthConfig, err := adal.NewOAuthConfig(ts.environment.ActiveDirectoryEndpoint, ts.tenantID)
if err != nil {
return nil, fmt.Errorf("building the OAuth configuration for device code authentication: %v", err)
}
client := &autorest.Client{}
deviceCode, err := adal.InitiateDeviceAuth(client, *oauthConfig, ts.clientID, ts.apiserverID)
if err != nil {
return nil, fmt.Errorf("initialing the device code authentication: %v", err)
}
_, err = fmt.Fprintln(os.Stderr, *deviceCode.Message)
if err != nil {
return nil, fmt.Errorf("prompting the device code message: %v", err)
}
token, err := adal.WaitForUserCompletion(client, deviceCode)
if err != nil {
return nil, fmt.Errorf("waiting for device code authentication to complete: %v", err)
}
return &azureToken{
token: *token,
clientID: ts.clientID,
tenantID: ts.tenantID,
apiserverID: ts.apiserverID,
}, nil
}

View File

@@ -1,134 +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 azure
import (
"encoding/json"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/Azure/go-autorest/autorest/adal"
)
func TestAzureTokenSource(t *testing.T) {
fakeAccessToken := "fake token 1"
fakeSource := fakeTokenSource{
accessToken: fakeAccessToken,
expiresOn: strconv.FormatInt(time.Now().Add(3600*time.Second).Unix(), 10),
}
cfg := make(map[string]string)
persiter := &fakePersister{cache: make(map[string]string)}
tokenCache := newAzureTokenCache()
tokenSource := newAzureTokenSource(&fakeSource, tokenCache, cfg, persiter)
token, err := tokenSource.Token()
if err != nil {
t.Errorf("failed to retrieve the token form cache: %v", err)
}
wantCacheLen := 1
if len(tokenCache.cache) != wantCacheLen {
t.Errorf("Token() cache length error: got %v, want %v", len(tokenCache.cache), wantCacheLen)
}
if token != tokenCache.cache[azureTokenKey] {
t.Error("Token() returned token != cached token")
}
wantCfg := token2Cfg(token)
persistedCfg := persiter.Cache()
for k, v := range persistedCfg {
if strings.Compare(v, wantCfg[k]) != 0 {
t.Errorf("Token() persisted cfg %s: got %v, want %v", k, v, wantCfg[k])
}
}
fakeSource.accessToken = "fake token 2"
token, err = tokenSource.Token()
if err != nil {
t.Errorf("failed to retrieve the cached token: %v", err)
}
if token.token.AccessToken != fakeAccessToken {
t.Errorf("Token() didn't return the cached token")
}
}
type fakePersister struct {
lock sync.Mutex
cache map[string]string
}
func (p *fakePersister) Persist(cache map[string]string) error {
p.lock.Lock()
defer p.lock.Unlock()
p.cache = map[string]string{}
for k, v := range cache {
p.cache[k] = v
}
return nil
}
func (p *fakePersister) Cache() map[string]string {
ret := map[string]string{}
p.lock.Lock()
defer p.lock.Unlock()
for k, v := range p.cache {
ret[k] = v
}
return ret
}
type fakeTokenSource struct {
expiresOn string
accessToken string
}
func (ts *fakeTokenSource) Token() (*azureToken, error) {
return &azureToken{
token: newFackeAzureToken(ts.accessToken, ts.expiresOn),
clientID: "fake",
tenantID: "fake",
apiserverID: "fake",
}, nil
}
func token2Cfg(token *azureToken) map[string]string {
cfg := make(map[string]string)
cfg[cfgAccessToken] = token.token.AccessToken
cfg[cfgRefreshToken] = token.token.RefreshToken
cfg[cfgClientID] = token.clientID
cfg[cfgTenantID] = token.tenantID
cfg[cfgApiserverID] = token.apiserverID
cfg[cfgExpiresIn] = string(token.token.ExpiresIn)
cfg[cfgExpiresOn] = string(token.token.ExpiresOn)
return cfg
}
func newFackeAzureToken(accessToken string, expiresOn string) adal.Token {
return adal.Token{
AccessToken: accessToken,
RefreshToken: "fake",
ExpiresIn: "3600",
ExpiresOn: json.Number(expiresOn),
NotBefore: json.Number(expiresOn),
Resource: "fake",
Type: "fake",
}
}

View File

@@ -1,748 +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"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/pkg/apis/clientauthentication"
"k8s.io/client-go/tools/clientcmd/api"
"k8s.io/client-go/transport"
)
var (
certData = []byte(`-----BEGIN CERTIFICATE-----
MIIC6jCCAdSgAwIBAgIBCzALBgkqhkiG9w0BAQswIzEhMB8GA1UEAwwYMTAuMTMu
MTI5LjEwNkAxNDIxMzU5MDU4MB4XDTE1MDExNTIyMDEzMVoXDTE2MDExNTIyMDEz
MlowGzEZMBcGA1UEAxMQb3BlbnNoaWZ0LWNsaWVudDCCASIwDQYJKoZIhvcNAQEB
BQADggEPADCCAQoCggEBAKtdhz0+uCLXw5cSYns9rU/XifFSpb/x24WDdrm72S/v
b9BPYsAStiP148buylr1SOuNi8sTAZmlVDDIpIVwMLff+o2rKYDicn9fjbrTxTOj
lI4pHJBH+JU3AJ0tbajupioh70jwFS0oYpwtneg2zcnE2Z4l6mhrj2okrc5Q1/X2
I2HChtIU4JYTisObtin10QKJX01CLfYXJLa8upWzKZ4/GOcHG+eAV3jXWoXidtjb
1Usw70amoTZ6mIVCkiu1QwCoa8+ycojGfZhvqMsAp1536ZcCul+Na+AbCv4zKS7F
kQQaImVrXdUiFansIoofGlw/JNuoKK6ssVpS5Ic3pgcCAwEAAaM1MDMwDgYDVR0P
AQH/BAQDAgCgMBMGA1UdJQQMMAoGCCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAwCwYJ
KoZIhvcNAQELA4IBAQCKLREH7bXtXtZ+8vI6cjD7W3QikiArGqbl36bAhhWsJLp/
p/ndKz39iFNaiZ3GlwIURWOOKx3y3GA0x9m8FR+Llthf0EQ8sUjnwaknWs0Y6DQ3
jjPFZOpV3KPCFrdMJ3++E3MgwFC/Ih/N2ebFX9EcV9Vcc6oVWMdwT0fsrhu683rq
6GSR/3iVX1G/pmOiuaR0fNUaCyCfYrnI4zHBDgSfnlm3vIvN2lrsR/DQBakNL8DJ
HBgKxMGeUPoneBv+c8DMXIL0EhaFXRlBv9QW45/GiAIOuyFJ0i6hCtGZpJjq4OpQ
BRjCI+izPzFTjsxD4aORE+WOkyWFCGPWKfNejfw0
-----END CERTIFICATE-----`)
keyData = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAq12HPT64ItfDlxJiez2tT9eJ8VKlv/HbhYN2ubvZL+9v0E9i
wBK2I/Xjxu7KWvVI642LyxMBmaVUMMikhXAwt9/6jaspgOJyf1+NutPFM6OUjikc
kEf4lTcAnS1tqO6mKiHvSPAVLShinC2d6DbNycTZniXqaGuPaiStzlDX9fYjYcKG
0hTglhOKw5u2KfXRAolfTUIt9hcktry6lbMpnj8Y5wcb54BXeNdaheJ22NvVSzDv
RqahNnqYhUKSK7VDAKhrz7JyiMZ9mG+oywCnXnfplwK6X41r4BsK/jMpLsWRBBoi
ZWtd1SIVqewiih8aXD8k26gorqyxWlLkhzemBwIDAQABAoIBAD2XYRs3JrGHQUpU
FkdbVKZkvrSY0vAZOqBTLuH0zUv4UATb8487anGkWBjRDLQCgxH+jucPTrztekQK
aW94clo0S3aNtV4YhbSYIHWs1a0It0UdK6ID7CmdWkAj6s0T8W8lQT7C46mWYVLm
5mFnCTHi6aB42jZrqmEpC7sivWwuU0xqj3Ml8kkxQCGmyc9JjmCB4OrFFC8NNt6M
ObvQkUI6Z3nO4phTbpxkE1/9dT0MmPIF7GhHVzJMS+EyyRYUDllZ0wvVSOM3qZT0
JMUaBerkNwm9foKJ1+dv2nMKZZbJajv7suUDCfU44mVeaEO+4kmTKSGCGjjTBGkr
7L1ySDECgYEA5ElIMhpdBzIivCuBIH8LlUeuzd93pqssO1G2Xg0jHtfM4tz7fyeI
cr90dc8gpli24dkSxzLeg3Tn3wIj/Bu64m2TpZPZEIlukYvgdgArmRIPQVxerYey
OkrfTNkxU1HXsYjLCdGcGXs5lmb+K/kuTcFxaMOs7jZi7La+jEONwf8CgYEAwCs/
rUOOA0klDsWWisbivOiNPII79c9McZCNBqncCBfMUoiGe8uWDEO4TFHN60vFuVk9
8PkwpCfvaBUX+ajvbafIfHxsnfk1M04WLGCeqQ/ym5Q4sQoQOcC1b1y9qc/xEWfg
nIUuia0ukYRpl7qQa3tNg+BNFyjypW8zukUAC/kCgYB1/Kojuxx5q5/oQVPrx73k
2bevD+B3c+DYh9MJqSCNwFtUpYIWpggPxoQan4LwdsmO0PKzocb/ilyNFj4i/vII
NToqSc/WjDFpaDIKyuu9oWfhECye45NqLWhb/6VOuu4QA/Nsj7luMhIBehnEAHW+
GkzTKM8oD1PxpEG3nPKXYQKBgQC6AuMPRt3XBl1NkCrpSBy/uObFlFaP2Enpf39S
3OZ0Gv0XQrnSaL1kP8TMcz68rMrGX8DaWYsgytstR4W+jyy7WvZwsUu+GjTJ5aMG
77uEcEBpIi9CBzivfn7hPccE8ZgqPf+n4i6q66yxBJflW5xhvafJqDtW2LcPNbW/
bvzdmQKBgExALRUXpq+5dbmkdXBHtvXdRDZ6rVmrnjy4nI5bPw+1GqQqk6uAR6B/
F6NmLCQOO4PDG/cuatNHIr2FrwTmGdEL6ObLUGWn9Oer9gJhHVqqsY5I4sEPo4XX
stR0Yiw0buV6DL/moUO0HIM9Bjh96HJp+LxiIS6UCdIhMPp5HoQa
-----END RSA PRIVATE KEY-----`)
validCert *tls.Certificate
)
func init() {
cert, err := tls.X509KeyPair(certData, keyData)
if err != nil {
panic(err)
}
validCert = &cert
}
func TestCacheKey(t *testing.T) {
c1 := &api.ExecConfig{
Command: "foo-bar",
Args: []string{"1", "2"},
Env: []api.ExecEnvVar{
{Name: "3", Value: "4"},
{Name: "5", Value: "6"},
{Name: "7", Value: "8"},
},
APIVersion: "client.authentication.k8s.io/v1alpha1",
}
c2 := &api.ExecConfig{
Command: "foo-bar",
Args: []string{"1", "2"},
Env: []api.ExecEnvVar{
{Name: "3", Value: "4"},
{Name: "5", Value: "6"},
{Name: "7", Value: "8"},
},
APIVersion: "client.authentication.k8s.io/v1alpha1",
}
c3 := &api.ExecConfig{
Command: "foo-bar",
Args: []string{"1", "2"},
Env: []api.ExecEnvVar{
{Name: "3", Value: "4"},
{Name: "5", Value: "6"},
},
APIVersion: "client.authentication.k8s.io/v1alpha1",
}
key1 := cacheKey(c1)
key2 := cacheKey(c2)
key3 := cacheKey(c3)
if key1 != key2 {
t.Error("key1 and key2 didn't match")
}
if key1 == key3 {
t.Error("key1 and key3 matched")
}
if key2 == key3 {
t.Error("key2 and key3 matched")
}
}
func compJSON(t *testing.T, got, want []byte) {
t.Helper()
gotJSON := &bytes.Buffer{}
wantJSON := &bytes.Buffer{}
if err := json.Indent(gotJSON, got, "", " "); err != nil {
t.Errorf("got invalid JSON: %v", err)
}
if err := json.Indent(wantJSON, want, "", " "); err != nil {
t.Errorf("want invalid JSON: %v", err)
}
g := strings.TrimSpace(gotJSON.String())
w := strings.TrimSpace(wantJSON.String())
if g != w {
t.Errorf("wanted %q, got %q", w, g)
}
}
func TestRefreshCreds(t *testing.T) {
tests := []struct {
name string
config api.ExecConfig
output string
interactive bool
response *clientauthentication.Response
wantInput string
wantCreds credentials
wantExpiry time.Time
wantErr bool
}{
{
name: "basic-request",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
},
wantInput: `{
"kind":"ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1",
"spec": {}
}`,
output: `{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"status": {
"token": "foo-bar"
}
}`,
wantCreds: credentials{token: "foo-bar"},
},
{
name: "interactive",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
},
interactive: true,
wantInput: `{
"kind":"ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1",
"spec": {
"interactive": true
}
}`,
output: `{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"status": {
"token": "foo-bar"
}
}`,
wantCreds: credentials{token: "foo-bar"},
},
{
name: "response",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
},
response: &clientauthentication.Response{
Header: map[string][]string{
"WWW-Authenticate": {`Basic realm="Access to the staging site", charset="UTF-8"`},
},
Code: 401,
},
wantInput: `{
"kind":"ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1",
"spec": {
"response": {
"header": {
"WWW-Authenticate": [
"Basic realm=\"Access to the staging site\", charset=\"UTF-8\""
]
},
"code": 401
}
}
}`,
output: `{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"status": {
"token": "foo-bar"
}
}`,
wantCreds: credentials{token: "foo-bar"},
},
{
name: "expiry",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
},
wantInput: `{
"kind":"ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1",
"spec": {}
}`,
output: `{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"status": {
"token": "foo-bar",
"expirationTimestamp": "2006-01-02T15:04:05Z"
}
}`,
wantExpiry: time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC),
wantCreds: credentials{token: "foo-bar"},
},
{
name: "no-group-version",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
},
wantInput: `{
"kind":"ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1",
"spec": {}
}`,
output: `{
"kind": "ExecCredential",
"status": {
"token": "foo-bar"
}
}`,
wantErr: true,
},
{
name: "no-status",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
},
wantInput: `{
"kind":"ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1",
"spec": {}
}`,
output: `{
"kind": "ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1"
}`,
wantErr: true,
},
{
name: "no-creds",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
},
wantInput: `{
"kind":"ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1",
"spec": {}
}`,
output: `{
"kind": "ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1",
"status": {}
}`,
wantErr: true,
},
{
name: "TLS credentials",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
},
wantInput: `{
"kind":"ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1",
"spec": {}
}`,
output: fmt.Sprintf(`{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"status": {
"clientKeyData": %q,
"clientCertificateData": %q
}
}`, keyData, certData),
wantCreds: credentials{cert: validCert},
},
{
name: "bad TLS credentials",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
},
wantInput: `{
"kind":"ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1",
"spec": {}
}`,
output: `{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"status": {
"clientKeyData": "foo",
"clientCertificateData": "bar"
}
}`,
wantErr: true,
},
{
name: "cert but no key",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
},
wantInput: `{
"kind":"ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1alpha1",
"spec": {}
}`,
output: fmt.Sprintf(`{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"status": {
"clientCertificateData": %q
}
}`, certData),
wantErr: true,
},
{
name: "beta-basic-request",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1beta1",
},
output: `{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1beta1",
"status": {
"token": "foo-bar"
}
}`,
wantCreds: credentials{token: "foo-bar"},
},
{
name: "beta-expiry",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1beta1",
},
output: `{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1beta1",
"status": {
"token": "foo-bar",
"expirationTimestamp": "2006-01-02T15:04:05Z"
}
}`,
wantExpiry: time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC),
wantCreds: credentials{token: "foo-bar"},
},
{
name: "beta-no-group-version",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1beta1",
},
output: `{
"kind": "ExecCredential",
"status": {
"token": "foo-bar"
}
}`,
wantErr: true,
},
{
name: "beta-no-status",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1beta1",
},
output: `{
"kind": "ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1beta1"
}`,
wantErr: true,
},
{
name: "beta-no-token",
config: api.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1beta1",
},
output: `{
"kind": "ExecCredential",
"apiVersion":"client.authentication.k8s.io/v1beta1",
"status": {}
}`,
wantErr: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
c := test.config
c.Command = "./testdata/test-plugin.sh"
c.Env = append(c.Env, api.ExecEnvVar{
Name: "TEST_OUTPUT",
Value: test.output,
})
a, err := newAuthenticator(newCache(), &c)
if err != nil {
t.Fatal(err)
}
stderr := &bytes.Buffer{}
a.stderr = stderr
a.interactive = test.interactive
a.environ = func() []string { return nil }
if err := a.refreshCredsLocked(test.response); err != nil {
if !test.wantErr {
t.Errorf("get token %v", err)
}
return
}
if test.wantErr {
t.Fatal("expected error getting token")
}
if !reflect.DeepEqual(a.cachedCreds, &test.wantCreds) {
t.Errorf("expected credentials %+v got %+v", &test.wantCreds, a.cachedCreds)
}
if !a.exp.Equal(test.wantExpiry) {
t.Errorf("expected expiry %v got %v", test.wantExpiry, a.exp)
}
if test.wantInput == "" {
if got := strings.TrimSpace(stderr.String()); got != "" {
t.Errorf("expected no input parameters, got %q", got)
}
return
}
compJSON(t, stderr.Bytes(), []byte(test.wantInput))
})
}
}
func TestRoundTripper(t *testing.T) {
wantToken := ""
n := time.Now()
now := func() time.Time { return n }
env := []string{""}
environ := func() []string {
s := make([]string, len(env))
copy(s, env)
return s
}
setOutput := func(s string) {
env[0] = "TEST_OUTPUT=" + s
}
handler := func(w http.ResponseWriter, r *http.Request) {
gotToken := ""
parts := strings.Split(r.Header.Get("Authorization"), " ")
if len(parts) > 1 && strings.EqualFold(parts[0], "bearer") {
gotToken = parts[1]
}
if wantToken != gotToken {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
fmt.Fprintln(w, "ok")
}
server := httptest.NewServer(http.HandlerFunc(handler))
c := api.ExecConfig{
Command: "./testdata/test-plugin.sh",
APIVersion: "client.authentication.k8s.io/v1alpha1",
}
a, err := newAuthenticator(newCache(), &c)
if err != nil {
t.Fatal(err)
}
a.environ = environ
a.now = now
a.stderr = ioutil.Discard
tc := &transport.Config{}
if err := a.UpdateTransportConfig(tc); err != nil {
t.Fatal(err)
}
client := http.Client{
Transport: tc.WrapTransport(http.DefaultTransport),
}
get := func(t *testing.T, statusCode int) {
t.Helper()
resp, err := client.Get(server.URL)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != statusCode {
t.Errorf("wanted status %d got %d", statusCode, resp.StatusCode)
}
}
setOutput(`{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"status": {
"token": "token1"
}
}`)
wantToken = "token1"
get(t, http.StatusOK)
setOutput(`{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"status": {
"token": "token2"
}
}`)
// Previous token should be cached
get(t, http.StatusOK)
wantToken = "token2"
// Token is still cached, hits unauthorized but causes token to rotate.
get(t, http.StatusUnauthorized)
// Follow up request uses the rotated token.
get(t, http.StatusOK)
setOutput(`{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"status": {
"token": "token3",
"expirationTimestamp": "` + now().Add(time.Hour).Format(time.RFC3339Nano) + `"
}
}`)
wantToken = "token3"
// Token is still cached, hit's unauthorized but causes rotation to token with an expiry.
get(t, http.StatusUnauthorized)
get(t, http.StatusOK)
// Move time forward 2 hours, "token3" is now expired.
n = n.Add(time.Hour * 2)
setOutput(`{
"kind": "ExecCredential",
"apiVersion": "client.authentication.k8s.io/v1alpha1",
"status": {
"token": "token4",
"expirationTimestamp": "` + now().Add(time.Hour).Format(time.RFC3339Nano) + `"
}
}`)
wantToken = "token4"
// Old token is expired, should refresh automatically without hitting a 401.
get(t, http.StatusOK)
}
func TestTLSCredentials(t *testing.T) {
now := time.Now()
certPool := x509.NewCertPool()
cert, key := genClientCert(t)
if !certPool.AppendCertsFromPEM(cert) {
t.Fatal("failed to add client cert to CertPool")
}
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "ok")
}))
server.TLS = &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: certPool,
}
server.StartTLS()
defer server.Close()
a, err := newAuthenticator(newCache(), &api.ExecConfig{
Command: "./testdata/test-plugin.sh",
APIVersion: "client.authentication.k8s.io/v1alpha1",
})
if err != nil {
t.Fatal(err)
}
var output *clientauthentication.ExecCredential
a.environ = func() []string {
data, err := runtime.Encode(codecs.LegacyCodec(a.group), output)
if err != nil {
t.Fatal(err)
}
return []string{"TEST_OUTPUT=" + string(data)}
}
a.now = func() time.Time { return now }
a.stderr = ioutil.Discard
// We're not interested in server's cert, this test is about client cert.
tc := &transport.Config{TLS: transport.TLSConfig{Insecure: true}}
if err := a.UpdateTransportConfig(tc); err != nil {
t.Fatal(err)
}
get := func(t *testing.T, desc string, wantErr bool) {
t.Run(desc, func(t *testing.T) {
tlsCfg, err := transport.TLSConfigFor(tc)
if err != nil {
t.Fatal("TLSConfigFor:", err)
}
client := http.Client{
Transport: &http.Transport{TLSClientConfig: tlsCfg},
}
resp, err := client.Get(server.URL)
switch {
case err != nil && !wantErr:
t.Errorf("got client.Get error: %q, want nil", err)
case err == nil && wantErr:
t.Error("got nil client.Get error, want non-nil")
}
if err == nil {
resp.Body.Close()
}
})
}
output = &clientauthentication.ExecCredential{
Status: &clientauthentication.ExecCredentialStatus{
ClientCertificateData: string(cert),
ClientKeyData: string(key),
ExpirationTimestamp: &v1.Time{now.Add(time.Hour)},
},
}
get(t, "valid TLS cert", false)
// Advance time to force re-exec.
nCert, nKey := genClientCert(t)
now = now.Add(time.Hour * 2)
output = &clientauthentication.ExecCredential{
Status: &clientauthentication.ExecCredentialStatus{
ClientCertificateData: string(nCert),
ClientKeyData: string(nKey),
ExpirationTimestamp: &v1.Time{now.Add(time.Hour)},
},
}
get(t, "untrusted TLS cert", true)
now = now.Add(time.Hour * 2)
output = &clientauthentication.ExecCredential{
Status: &clientauthentication.ExecCredentialStatus{
ClientCertificateData: string(cert),
ClientKeyData: string(key),
ExpirationTimestamp: &v1.Time{now.Add(time.Hour)},
},
}
get(t, "valid TLS cert again", false)
}
// genClientCert generates an x509 certificate for testing. Certificate and key
// are returned in PEM encoding.
func genClientCert(t *testing.T) ([]byte, []byte) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
keyRaw, err := x509.MarshalECPrivateKey(key)
if err != nil {
t.Fatal(err)
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
t.Fatal(err)
}
cert := &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{Organization: []string{"Acme Co"}},
NotBefore: time.Now(),
NotAfter: time.Now().Add(24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
}
certRaw, err := x509.CreateCertificate(rand.Reader, cert, cert, key.Public(), key)
if err != nil {
t.Fatal(err)
}
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certRaw}),
pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyRaw})
}

View File

@@ -1,18 +0,0 @@
#!/bin/bash -e
# 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.
>&2 echo "$KUBERNETES_EXEC_INFO"
echo "$TEST_OUTPUT"

View File

@@ -1,6 +0,0 @@
approvers:
- cjcullen
- jlowdermilk
reviewers:
- cjcullen
- jlowdermilk

View File

@@ -1,383 +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 gcp
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os/exec"
"strings"
"sync"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"k8s.io/apimachinery/pkg/util/net"
"k8s.io/apimachinery/pkg/util/yaml"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/util/jsonpath"
"k8s.io/klog"
)
func init() {
if err := restclient.RegisterAuthProviderPlugin("gcp", newGCPAuthProvider); err != nil {
klog.Fatalf("Failed to register gcp auth plugin: %v", err)
}
}
var (
// Stubbable for testing
execCommand = exec.Command
// defaultScopes:
// - cloud-platform is the base scope to authenticate to GCP.
// - userinfo.email is used to authenticate to GKE APIs with gserviceaccount
// email instead of numeric uniqueID.
defaultScopes = []string{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/userinfo.email"}
)
// gcpAuthProvider is an auth provider plugin that uses GCP credentials to provide
// tokens for kubectl to authenticate itself to the apiserver. A sample json config
// is provided below with all recognized options described.
//
// {
// 'auth-provider': {
// # Required
// "name": "gcp",
//
// 'config': {
// # Authentication options
// # These options are used while getting a token.
//
// # comma-separated list of GCP API scopes. default value of this field
// # is "https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email".
// # to override the API scopes, specify this field explicitly.
// "scopes": "https://www.googleapis.com/auth/cloud-platform"
//
// # Caching options
//
// # Raw string data representing cached access token.
// "access-token": "ya29.CjWdA4GiBPTt",
// # RFC3339Nano expiration timestamp for cached access token.
// "expiry": "2016-10-31 22:31:9.123",
//
// # Command execution options
// # These options direct the plugin to execute a specified command and parse
// # token and expiry time from the output of the command.
//
// # Command to execute for access token. Command output will be parsed as JSON.
// # If "cmd-args" is not present, this value will be split on whitespace, with
// # the first element interpreted as the command, remaining elements as args.
// "cmd-path": "/usr/bin/gcloud",
//
// # Arguments to pass to command to execute for access token.
// "cmd-args": "config config-helper --output=json"
//
// # JSONPath to the string field that represents the access token in
// # command output. If omitted, defaults to "{.access_token}".
// "token-key": "{.credential.access_token}",
//
// # JSONPath to the string field that represents expiration timestamp
// # of the access token in the command output. If omitted, defaults to
// # "{.token_expiry}"
// "expiry-key": ""{.credential.token_expiry}",
//
// # golang reference time in the format that the expiration timestamp uses.
// # If omitted, defaults to time.RFC3339Nano
// "time-fmt": "2006-01-02 15:04:05.999999999"
// }
// }
// }
//
type gcpAuthProvider struct {
tokenSource oauth2.TokenSource
persister restclient.AuthProviderConfigPersister
}
func newGCPAuthProvider(_ string, gcpConfig map[string]string, persister restclient.AuthProviderConfigPersister) (restclient.AuthProvider, error) {
ts, err := tokenSource(isCmdTokenSource(gcpConfig), gcpConfig)
if err != nil {
return nil, err
}
cts, err := newCachedTokenSource(gcpConfig["access-token"], gcpConfig["expiry"], persister, ts, gcpConfig)
if err != nil {
return nil, err
}
return &gcpAuthProvider{cts, persister}, nil
}
func isCmdTokenSource(gcpConfig map[string]string) bool {
_, ok := gcpConfig["cmd-path"]
return ok
}
func tokenSource(isCmd bool, gcpConfig map[string]string) (oauth2.TokenSource, error) {
// Command-based token source
if isCmd {
cmd := gcpConfig["cmd-path"]
if len(cmd) == 0 {
return nil, fmt.Errorf("missing access token cmd")
}
if gcpConfig["scopes"] != "" {
return nil, fmt.Errorf("scopes can only be used when kubectl is using a gcp service account key")
}
var args []string
if cmdArgs, ok := gcpConfig["cmd-args"]; ok {
args = strings.Fields(cmdArgs)
} else {
fields := strings.Fields(cmd)
cmd = fields[0]
args = fields[1:]
}
return newCmdTokenSource(cmd, args, gcpConfig["token-key"], gcpConfig["expiry-key"], gcpConfig["time-fmt"]), nil
}
// Google Application Credentials-based token source
scopes := parseScopes(gcpConfig)
ts, err := google.DefaultTokenSource(context.Background(), scopes...)
if err != nil {
return nil, fmt.Errorf("cannot construct google default token source: %v", err)
}
return ts, nil
}
// parseScopes constructs a list of scopes that should be included in token source
// from the config map.
func parseScopes(gcpConfig map[string]string) []string {
scopes, ok := gcpConfig["scopes"]
if !ok {
return defaultScopes
}
if scopes == "" {
return []string{}
}
return strings.Split(gcpConfig["scopes"], ",")
}
func (g *gcpAuthProvider) WrapTransport(rt http.RoundTripper) http.RoundTripper {
var resetCache map[string]string
if cts, ok := g.tokenSource.(*cachedTokenSource); ok {
resetCache = cts.baseCache()
} else {
resetCache = make(map[string]string)
}
return &conditionalTransport{&oauth2.Transport{Source: g.tokenSource, Base: rt}, g.persister, resetCache}
}
func (g *gcpAuthProvider) Login() error { return nil }
type cachedTokenSource struct {
lk sync.Mutex
source oauth2.TokenSource
accessToken string
expiry time.Time
persister restclient.AuthProviderConfigPersister
cache map[string]string
}
func newCachedTokenSource(accessToken, expiry string, persister restclient.AuthProviderConfigPersister, ts oauth2.TokenSource, cache map[string]string) (*cachedTokenSource, error) {
var expiryTime time.Time
if parsedTime, err := time.Parse(time.RFC3339Nano, expiry); err == nil {
expiryTime = parsedTime
}
if cache == nil {
cache = make(map[string]string)
}
return &cachedTokenSource{
source: ts,
accessToken: accessToken,
expiry: expiryTime,
persister: persister,
cache: cache,
}, nil
}
func (t *cachedTokenSource) Token() (*oauth2.Token, error) {
tok := t.cachedToken()
if tok.Valid() && !tok.Expiry.IsZero() {
return tok, nil
}
tok, err := t.source.Token()
if err != nil {
return nil, err
}
cache := t.update(tok)
if t.persister != nil {
if err := t.persister.Persist(cache); err != nil {
klog.V(4).Infof("Failed to persist token: %v", err)
}
}
return tok, nil
}
func (t *cachedTokenSource) cachedToken() *oauth2.Token {
t.lk.Lock()
defer t.lk.Unlock()
return &oauth2.Token{
AccessToken: t.accessToken,
TokenType: "Bearer",
Expiry: t.expiry,
}
}
func (t *cachedTokenSource) update(tok *oauth2.Token) map[string]string {
t.lk.Lock()
defer t.lk.Unlock()
t.accessToken = tok.AccessToken
t.expiry = tok.Expiry
ret := map[string]string{}
for k, v := range t.cache {
ret[k] = v
}
ret["access-token"] = t.accessToken
ret["expiry"] = t.expiry.Format(time.RFC3339Nano)
return ret
}
// baseCache is the base configuration value for this TokenSource, without any cached ephemeral tokens.
func (t *cachedTokenSource) baseCache() map[string]string {
t.lk.Lock()
defer t.lk.Unlock()
ret := map[string]string{}
for k, v := range t.cache {
ret[k] = v
}
delete(ret, "access-token")
delete(ret, "expiry")
return ret
}
type commandTokenSource struct {
cmd string
args []string
tokenKey string
expiryKey string
timeFmt string
}
func newCmdTokenSource(cmd string, args []string, tokenKey, expiryKey, timeFmt string) *commandTokenSource {
if len(timeFmt) == 0 {
timeFmt = time.RFC3339Nano
}
if len(tokenKey) == 0 {
tokenKey = "{.access_token}"
}
if len(expiryKey) == 0 {
expiryKey = "{.token_expiry}"
}
return &commandTokenSource{
cmd: cmd,
args: args,
tokenKey: tokenKey,
expiryKey: expiryKey,
timeFmt: timeFmt,
}
}
func (c *commandTokenSource) Token() (*oauth2.Token, error) {
fullCmd := strings.Join(append([]string{c.cmd}, c.args...), " ")
cmd := execCommand(c.cmd, c.args...)
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("error executing access token command %q: err=%v output=%s stderr=%s", fullCmd, err, output, string(stderr.Bytes()))
}
token, err := c.parseTokenCmdOutput(output)
if err != nil {
return nil, fmt.Errorf("error parsing output for access token command %q: %v", fullCmd, err)
}
return token, nil
}
func (c *commandTokenSource) parseTokenCmdOutput(output []byte) (*oauth2.Token, error) {
output, err := yaml.ToJSON(output)
if err != nil {
return nil, err
}
var data interface{}
if err := json.Unmarshal(output, &data); err != nil {
return nil, err
}
accessToken, err := parseJSONPath(data, "token-key", c.tokenKey)
if err != nil {
return nil, fmt.Errorf("error parsing token-key %q from %q: %v", c.tokenKey, string(output), err)
}
expiryStr, err := parseJSONPath(data, "expiry-key", c.expiryKey)
if err != nil {
return nil, fmt.Errorf("error parsing expiry-key %q from %q: %v", c.expiryKey, string(output), err)
}
var expiry time.Time
if t, err := time.Parse(c.timeFmt, expiryStr); err != nil {
klog.V(4).Infof("Failed to parse token expiry from %s (fmt=%s): %v", expiryStr, c.timeFmt, err)
} else {
expiry = t
}
return &oauth2.Token{
AccessToken: accessToken,
TokenType: "Bearer",
Expiry: expiry,
}, nil
}
func parseJSONPath(input interface{}, name, template string) (string, error) {
j := jsonpath.New(name)
buf := new(bytes.Buffer)
if err := j.Parse(template); err != nil {
return "", err
}
if err := j.Execute(buf, input); err != nil {
return "", err
}
return buf.String(), nil
}
type conditionalTransport struct {
oauthTransport *oauth2.Transport
persister restclient.AuthProviderConfigPersister
resetCache map[string]string
}
var _ net.RoundTripperWrapper = &conditionalTransport{}
func (t *conditionalTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if len(req.Header.Get("Authorization")) != 0 {
return t.oauthTransport.Base.RoundTrip(req)
}
res, err := t.oauthTransport.RoundTrip(req)
if err != nil {
return nil, err
}
if res.StatusCode == 401 {
klog.V(4).Infof("The credentials that were supplied are invalid for the target cluster")
t.persister.Persist(t.resetCache)
}
return res, nil
}
func (t *conditionalTransport) WrappedRoundTripper() http.RoundTripper { return t.oauthTransport.Base }

View File

@@ -1,527 +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 gcp
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"reflect"
"strings"
"sync"
"testing"
"time"
"golang.org/x/oauth2"
)
type fakeOutput struct {
args []string
output string
}
var (
wantCmd []string
// Output for fakeExec, keyed by command
execOutputs = map[string]fakeOutput{
"/default/no/args": {
args: []string{},
output: `{
"access_token": "faketoken",
"token_expiry": "2016-10-31T22:31:09.123000000Z"
}`},
"/default/legacy/args": {
args: []string{"arg1", "arg2", "arg3"},
output: `{
"access_token": "faketoken",
"token_expiry": "2016-10-31T22:31:09.123000000Z"
}`},
"/space in path/customkeys": {
args: []string{"can", "haz", "auth"},
output: `{
"token": "faketoken",
"token_expiry": {
"datetime": "2016-10-31 22:31:09.123"
}
}`},
"missing/tokenkey/noargs": {
args: []string{},
output: `{
"broken": "faketoken",
"token_expiry": {
"datetime": "2016-10-31 22:31:09.123000000Z"
}
}`},
"missing/expirykey/legacyargs": {
args: []string{"split", "on", "whitespace"},
output: `{
"access_token": "faketoken",
"expires": "2016-10-31T22:31:09.123000000Z"
}`},
"invalid expiry/timestamp": {
args: []string{"foo", "--bar", "--baz=abc,def"},
output: `{
"access_token": "faketoken",
"token_expiry": "sometime soon, idk"
}`},
"badjson": {
args: []string{},
output: `{
"access_token": "faketoken",
"token_expiry": "sometime soon, idk"
------
`},
}
)
func fakeExec(command string, args ...string) *exec.Cmd {
cs := []string{"-test.run=TestHelperProcess", "--", command}
cs = append(cs, args...)
cmd := exec.Command(os.Args[0], cs...)
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
return cmd
}
func TestHelperProcess(t *testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
return
}
// Strip out the leading args used to exec into this function.
gotCmd := os.Args[3]
gotArgs := os.Args[4:]
output, ok := execOutputs[gotCmd]
if !ok {
fmt.Fprintf(os.Stdout, "unexpected call cmd=%q args=%v\n", gotCmd, gotArgs)
os.Exit(1)
} else if !reflect.DeepEqual(output.args, gotArgs) {
fmt.Fprintf(os.Stdout, "call cmd=%q got args %v, want: %v\n", gotCmd, gotArgs, output.args)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, output.output)
os.Exit(0)
}
func Test_isCmdTokenSource(t *testing.T) {
c1 := map[string]string{"cmd-path": "foo"}
if v := isCmdTokenSource(c1); !v {
t.Fatalf("cmd-path present in config (%+v), but got %v", c1, v)
}
c2 := map[string]string{"cmd-args": "foo bar"}
if v := isCmdTokenSource(c2); v {
t.Fatalf("cmd-path not present in config (%+v), but got %v", c2, v)
}
}
func Test_tokenSource_cmd(t *testing.T) {
if _, err := tokenSource(true, map[string]string{}); err == nil {
t.Fatalf("expected error, cmd-args not present in config")
}
c := map[string]string{
"cmd-path": "foo",
"cmd-args": "bar"}
ts, err := tokenSource(true, c)
if err != nil {
t.Fatalf("failed to return cmd token source: %+v", err)
}
if ts == nil {
t.Fatal("returned nil token source")
}
if _, ok := ts.(*commandTokenSource); !ok {
t.Fatalf("returned token source type:(%T) expected:(*commandTokenSource)", ts)
}
}
func Test_tokenSource_cmdCannotBeUsedWithScopes(t *testing.T) {
c := map[string]string{
"cmd-path": "foo",
"scopes": "A,B"}
if _, err := tokenSource(true, c); err == nil {
t.Fatal("expected error when scopes is used with cmd-path")
}
}
func Test_tokenSource_applicationDefaultCredentials_fails(t *testing.T) {
// try to use empty ADC file
fakeTokenFile, err := ioutil.TempFile("", "adctoken")
if err != nil {
t.Fatalf("failed to create fake token file: +%v", err)
}
fakeTokenFile.Close()
defer os.Remove(fakeTokenFile.Name())
os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", fakeTokenFile.Name())
defer os.Unsetenv("GOOGLE_APPLICATION_CREDENTIALS")
if _, err := tokenSource(false, map[string]string{}); err == nil {
t.Fatalf("expected error because specified ADC token file is not a JSON")
}
}
func Test_tokenSource_applicationDefaultCredentials(t *testing.T) {
fakeTokenFile, err := ioutil.TempFile("", "adctoken")
if err != nil {
t.Fatalf("failed to create fake token file: +%v", err)
}
fakeTokenFile.Close()
defer os.Remove(fakeTokenFile.Name())
if err := ioutil.WriteFile(fakeTokenFile.Name(), []byte(`{"type":"service_account"}`), 0600); err != nil {
t.Fatalf("failed to write to fake token file: %+v", err)
}
os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", fakeTokenFile.Name())
defer os.Unsetenv("GOOGLE_APPLICATION_CREDENTIALS")
ts, err := tokenSource(false, map[string]string{})
if err != nil {
t.Fatalf("failed to get a token source: %+v", err)
}
if ts == nil {
t.Fatal("returned nil token source")
}
}
func Test_parseScopes(t *testing.T) {
cases := []struct {
in map[string]string
out []string
}{
{
map[string]string{},
[]string{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/userinfo.email"},
},
{
map[string]string{"scopes": ""},
[]string{},
},
{
map[string]string{"scopes": "A,B,C"},
[]string{"A", "B", "C"},
},
}
for _, c := range cases {
got := parseScopes(c.in)
if !reflect.DeepEqual(got, c.out) {
t.Errorf("expected=%v, got=%v", c.out, got)
}
}
}
func errEquiv(got, want error) bool {
if got == want {
return true
}
if got != nil && want != nil {
return strings.Contains(got.Error(), want.Error())
}
return false
}
func TestCmdTokenSource(t *testing.T) {
execCommand = fakeExec
fakeExpiry := time.Date(2016, 10, 31, 22, 31, 9, 123000000, time.UTC)
customFmt := "2006-01-02 15:04:05.999999999"
tests := []struct {
name string
gcpConfig map[string]string
tok *oauth2.Token
newErr, tokenErr error
}{
{
"default",
map[string]string{
"cmd-path": "/default/no/args",
},
&oauth2.Token{
AccessToken: "faketoken",
TokenType: "Bearer",
Expiry: fakeExpiry,
},
nil,
nil,
},
{
"default legacy args",
map[string]string{
"cmd-path": "/default/legacy/args arg1 arg2 arg3",
},
&oauth2.Token{
AccessToken: "faketoken",
TokenType: "Bearer",
Expiry: fakeExpiry,
},
nil,
nil,
},
{
"custom keys",
map[string]string{
"cmd-path": "/space in path/customkeys",
"cmd-args": "can haz auth",
"token-key": "{.token}",
"expiry-key": "{.token_expiry.datetime}",
"time-fmt": customFmt,
},
&oauth2.Token{
AccessToken: "faketoken",
TokenType: "Bearer",
Expiry: fakeExpiry,
},
nil,
nil,
},
{
"missing cmd",
map[string]string{
"cmd-path": "",
},
nil,
fmt.Errorf("missing access token cmd"),
nil,
},
{
"missing token-key",
map[string]string{
"cmd-path": "missing/tokenkey/noargs",
"token-key": "{.token}",
},
nil,
nil,
fmt.Errorf("error parsing token-key %q", "{.token}"),
},
{
"missing expiry-key",
map[string]string{
"cmd-path": "missing/expirykey/legacyargs split on whitespace",
"expiry-key": "{.expiry}",
},
nil,
nil,
fmt.Errorf("error parsing expiry-key %q", "{.expiry}"),
},
{
"invalid expiry timestamp",
map[string]string{
"cmd-path": "invalid expiry/timestamp",
"cmd-args": "foo --bar --baz=abc,def",
},
&oauth2.Token{
AccessToken: "faketoken",
TokenType: "Bearer",
Expiry: time.Time{},
},
nil,
nil,
},
{
"bad JSON",
map[string]string{
"cmd-path": "badjson",
},
nil,
nil,
fmt.Errorf("invalid character '-' after object key:value pair"),
},
}
for _, tc := range tests {
provider, err := newGCPAuthProvider("", tc.gcpConfig, nil /* persister */)
if !errEquiv(err, tc.newErr) {
t.Errorf("%q newGCPAuthProvider error: got %v, want %v", tc.name, err, tc.newErr)
continue
}
if err != nil {
continue
}
ts := provider.(*gcpAuthProvider).tokenSource.(*cachedTokenSource).source.(*commandTokenSource)
wantCmd = append([]string{ts.cmd}, ts.args...)
tok, err := ts.Token()
if !errEquiv(err, tc.tokenErr) {
t.Errorf("%q Token() error: got %v, want %v", tc.name, err, tc.tokenErr)
}
if !reflect.DeepEqual(tok, tc.tok) {
t.Errorf("%q Token() got %v, want %v", tc.name, tok, tc.tok)
}
}
}
type fakePersister struct {
lk sync.Mutex
cache map[string]string
}
func (f *fakePersister) Persist(cache map[string]string) error {
f.lk.Lock()
defer f.lk.Unlock()
f.cache = map[string]string{}
for k, v := range cache {
f.cache[k] = v
}
return nil
}
func (f *fakePersister) read() map[string]string {
ret := map[string]string{}
f.lk.Lock()
defer f.lk.Unlock()
for k, v := range f.cache {
ret[k] = v
}
return ret
}
type fakeTokenSource struct {
token *oauth2.Token
err error
}
func (f *fakeTokenSource) Token() (*oauth2.Token, error) {
return f.token, f.err
}
func TestCachedTokenSource(t *testing.T) {
tok := &oauth2.Token{AccessToken: "fakeaccesstoken"}
persister := &fakePersister{}
source := &fakeTokenSource{
token: tok,
err: nil,
}
cache := map[string]string{
"foo": "bar",
"baz": "bazinga",
}
ts, err := newCachedTokenSource("fakeaccesstoken", "", persister, source, cache)
if err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
_, err := ts.Token()
if err != nil {
t.Errorf("unexpected error: %s", err)
}
wg.Done()
}()
}
wg.Wait()
cache["access-token"] = "fakeaccesstoken"
cache["expiry"] = tok.Expiry.Format(time.RFC3339Nano)
if got := persister.read(); !reflect.DeepEqual(got, cache) {
t.Errorf("got cache %v, want %v", got, cache)
}
}
type MockTransport struct {
res *http.Response
}
func (t *MockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return t.res, nil
}
func Test_cmdTokenSource_roundTrip(t *testing.T) {
accessToken := "fakeToken"
fakeExpiry := time.Now().Add(time.Hour)
fakeExpiryStr := fakeExpiry.Format(time.RFC3339Nano)
fs := &fakeTokenSource{
token: &oauth2.Token{
AccessToken: accessToken,
Expiry: fakeExpiry,
},
}
cmdCache := map[string]string{
"cmd-path": "/path/to/tokensource/cmd",
"cmd-args": "--output=json",
}
cmdCacheUpdated := map[string]string{
"cmd-path": "/path/to/tokensource/cmd",
"cmd-args": "--output=json",
"access-token": accessToken,
"expiry": fakeExpiryStr,
}
simpleCacheUpdated := map[string]string{
"access-token": accessToken,
"expiry": fakeExpiryStr,
}
tests := []struct {
name string
res http.Response
baseCache, expectedCache map[string]string
}{
{
"Unauthorized",
http.Response{StatusCode: 401},
make(map[string]string),
make(map[string]string),
},
{
"Unauthorized, nonempty defaultCache",
http.Response{StatusCode: 401},
cmdCache,
cmdCache,
},
{
"Authorized",
http.Response{StatusCode: 200},
make(map[string]string),
simpleCacheUpdated,
},
{
"Authorized, nonempty defaultCache",
http.Response{StatusCode: 200},
cmdCache,
cmdCacheUpdated,
},
}
persister := &fakePersister{}
req := http.Request{Header: http.Header{}}
for _, tc := range tests {
cts, err := newCachedTokenSource(accessToken, fakeExpiry.String(), persister, fs, tc.baseCache)
if err != nil {
t.Fatalf("unexpected error from newCachedTokenSource: %v", err)
}
authProvider := gcpAuthProvider{cts, persister}
fakeTransport := MockTransport{&tc.res}
transport := (authProvider.WrapTransport(&fakeTransport))
// call Token to persist/update cache
if _, err := cts.Token(); err != nil {
t.Fatalf("unexpected error from cachedTokenSource.Token(): %v", err)
}
transport.RoundTrip(&req)
if got := persister.read(); !reflect.DeepEqual(got, tc.expectedCache) {
t.Errorf("got cache %v, want %v", got, tc.expectedCache)
}
}
}

View File

@@ -1,5 +0,0 @@
approvers:
- ericchiang
reviewers:
- ericchiang
- rithujohn191

View File

@@ -1,379 +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 oidc
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"sync"
"time"
"golang.org/x/oauth2"
"k8s.io/apimachinery/pkg/util/net"
restclient "k8s.io/client-go/rest"
"k8s.io/klog"
)
const (
cfgIssuerUrl = "idp-issuer-url"
cfgClientID = "client-id"
cfgClientSecret = "client-secret"
cfgCertificateAuthority = "idp-certificate-authority"
cfgCertificateAuthorityData = "idp-certificate-authority-data"
cfgIDToken = "id-token"
cfgRefreshToken = "refresh-token"
// Unused. Scopes aren't sent during refreshing.
cfgExtraScopes = "extra-scopes"
)
func init() {
if err := restclient.RegisterAuthProviderPlugin("oidc", newOIDCAuthProvider); err != nil {
klog.Fatalf("Failed to register oidc auth plugin: %v", err)
}
}
// expiryDelta determines how earlier a token should be considered
// expired than its actual expiration time. It is used to avoid late
// expirations due to client-server time mismatches.
//
// NOTE(ericchiang): this is take from golang.org/x/oauth2
const expiryDelta = 10 * time.Second
var cache = newClientCache()
// Like TLS transports, keep a cache of OIDC clients indexed by issuer URL. This ensures
// current requests from different clients don't concurrently attempt to refresh the same
// set of credentials.
type clientCache struct {
mu sync.RWMutex
cache map[cacheKey]*oidcAuthProvider
}
func newClientCache() *clientCache {
return &clientCache{cache: make(map[cacheKey]*oidcAuthProvider)}
}
type cacheKey struct {
// Canonical issuer URL string of the provider.
issuerURL string
clientID string
}
func (c *clientCache) getClient(issuer, clientID string) (*oidcAuthProvider, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
client, ok := c.cache[cacheKey{issuer, clientID}]
return client, ok
}
// setClient attempts to put the client in the cache but may return any clients
// with the same keys set before. This is so there's only ever one client for a provider.
func (c *clientCache) setClient(issuer, clientID string, client *oidcAuthProvider) *oidcAuthProvider {
c.mu.Lock()
defer c.mu.Unlock()
key := cacheKey{issuer, clientID}
// If another client has already initialized a client for the given provider we want
// to use that client instead of the one we're trying to set. This is so all transports
// share a client and can coordinate around the same mutex when refreshing and writing
// to the kubeconfig.
if oldClient, ok := c.cache[key]; ok {
return oldClient
}
c.cache[key] = client
return client
}
func newOIDCAuthProvider(_ string, cfg map[string]string, persister restclient.AuthProviderConfigPersister) (restclient.AuthProvider, error) {
issuer := cfg[cfgIssuerUrl]
if issuer == "" {
return nil, fmt.Errorf("Must provide %s", cfgIssuerUrl)
}
clientID := cfg[cfgClientID]
if clientID == "" {
return nil, fmt.Errorf("Must provide %s", cfgClientID)
}
// Check cache for existing provider.
if provider, ok := cache.getClient(issuer, clientID); ok {
return provider, nil
}
if len(cfg[cfgExtraScopes]) > 0 {
klog.V(2).Infof("%s auth provider field depricated, refresh request don't send scopes",
cfgExtraScopes)
}
var certAuthData []byte
var err error
if cfg[cfgCertificateAuthorityData] != "" {
certAuthData, err = base64.StdEncoding.DecodeString(cfg[cfgCertificateAuthorityData])
if err != nil {
return nil, err
}
}
clientConfig := restclient.Config{
TLSClientConfig: restclient.TLSClientConfig{
CAFile: cfg[cfgCertificateAuthority],
CAData: certAuthData,
},
}
trans, err := restclient.TransportFor(&clientConfig)
if err != nil {
return nil, err
}
hc := &http.Client{Transport: trans}
provider := &oidcAuthProvider{
client: hc,
now: time.Now,
cfg: cfg,
persister: persister,
}
return cache.setClient(issuer, clientID, provider), nil
}
type oidcAuthProvider struct {
client *http.Client
// Method for determining the current time.
now func() time.Time
// Mutex guards persisting to the kubeconfig file and allows synchronized
// updates to the in-memory config. It also ensures concurrent calls to
// the RoundTripper only trigger a single refresh request.
mu sync.Mutex
cfg map[string]string
persister restclient.AuthProviderConfigPersister
}
func (p *oidcAuthProvider) WrapTransport(rt http.RoundTripper) http.RoundTripper {
return &roundTripper{
wrapped: rt,
provider: p,
}
}
func (p *oidcAuthProvider) Login() error {
return errors.New("not yet implemented")
}
type roundTripper struct {
provider *oidcAuthProvider
wrapped http.RoundTripper
}
var _ net.RoundTripperWrapper = &roundTripper{}
func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
if len(req.Header.Get("Authorization")) != 0 {
return r.wrapped.RoundTrip(req)
}
token, err := r.provider.idToken()
if err != nil {
return nil, err
}
// shallow copy of the struct
r2 := new(http.Request)
*r2 = *req
// deep copy of the Header so we don't modify the original
// request's Header (as per RoundTripper contract).
r2.Header = make(http.Header)
for k, s := range req.Header {
r2.Header[k] = s
}
r2.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
return r.wrapped.RoundTrip(r2)
}
func (t *roundTripper) WrappedRoundTripper() http.RoundTripper { return t.wrapped }
func (p *oidcAuthProvider) idToken() (string, error) {
p.mu.Lock()
defer p.mu.Unlock()
if idToken, ok := p.cfg[cfgIDToken]; ok && len(idToken) > 0 {
valid, err := idTokenExpired(p.now, idToken)
if err != nil {
return "", err
}
if valid {
// If the cached id token is still valid use it.
return idToken, nil
}
}
// Try to request a new token using the refresh token.
rt, ok := p.cfg[cfgRefreshToken]
if !ok || len(rt) == 0 {
return "", errors.New("No valid id-token, and cannot refresh without refresh-token")
}
// Determine provider's OAuth2 token endpoint.
tokenURL, err := tokenEndpoint(p.client, p.cfg[cfgIssuerUrl])
if err != nil {
return "", err
}
config := oauth2.Config{
ClientID: p.cfg[cfgClientID],
ClientSecret: p.cfg[cfgClientSecret],
Endpoint: oauth2.Endpoint{TokenURL: tokenURL},
}
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, p.client)
token, err := config.TokenSource(ctx, &oauth2.Token{RefreshToken: rt}).Token()
if err != nil {
return "", fmt.Errorf("failed to refresh token: %v", err)
}
idToken, ok := token.Extra("id_token").(string)
if !ok {
// id_token isn't a required part of a refresh token response, so some
// providers (Okta) don't return this value.
//
// See https://github.com/kubernetes/kubernetes/issues/36847
return "", fmt.Errorf("token response did not contain an id_token, either the scope \"openid\" wasn't requested upon login, or the provider doesn't support id_tokens as part of the refresh response.")
}
// Create a new config to persist.
newCfg := make(map[string]string)
for key, val := range p.cfg {
newCfg[key] = val
}
// Update the refresh token if the server returned another one.
if token.RefreshToken != "" && token.RefreshToken != rt {
newCfg[cfgRefreshToken] = token.RefreshToken
}
newCfg[cfgIDToken] = idToken
// Persist new config and if successful, update the in memory config.
if err = p.persister.Persist(newCfg); err != nil {
return "", fmt.Errorf("could not persist new tokens: %v", err)
}
p.cfg = newCfg
return idToken, nil
}
// tokenEndpoint uses OpenID Connect discovery to determine the OAuth2 token
// endpoint for the provider, the endpoint the client will use the refresh
// token against.
func tokenEndpoint(client *http.Client, issuer string) (string, error) {
// Well known URL for getting OpenID Connect metadata.
//
// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig
wellKnown := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration"
resp, err := client.Get(wellKnown)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
// Don't produce an error that's too huge (e.g. if we get HTML back for some reason).
const n = 80
if len(body) > n {
body = append(body[:n], []byte("...")...)
}
return "", fmt.Errorf("oidc: failed to query metadata endpoint %s: %q", resp.Status, body)
}
// Metadata object. We only care about the token_endpoint, the thing endpoint
// we'll be refreshing against.
//
// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
var metadata struct {
TokenURL string `json:"token_endpoint"`
}
if err := json.Unmarshal(body, &metadata); err != nil {
return "", fmt.Errorf("oidc: failed to decode provider discovery object: %v", err)
}
if metadata.TokenURL == "" {
return "", fmt.Errorf("oidc: discovery object doesn't contain a token_endpoint")
}
return metadata.TokenURL, nil
}
func idTokenExpired(now func() time.Time, idToken string) (bool, error) {
parts := strings.Split(idToken, ".")
if len(parts) != 3 {
return false, fmt.Errorf("ID Token is not a valid JWT")
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return false, err
}
var claims struct {
Expiry jsonTime `json:"exp"`
}
if err := json.Unmarshal(payload, &claims); err != nil {
return false, fmt.Errorf("parsing claims: %v", err)
}
return now().Add(expiryDelta).Before(time.Time(claims.Expiry)), nil
}
// jsonTime is a json.Unmarshaler that parses a unix timestamp.
// Because JSON numbers don't differentiate between ints and floats,
// we want to ensure we can parse either.
type jsonTime time.Time
func (j *jsonTime) UnmarshalJSON(b []byte) error {
var n json.Number
if err := json.Unmarshal(b, &n); err != nil {
return err
}
var unix int64
if t, err := n.Int64(); err == nil {
unix = t
} else {
f, err := n.Float64()
if err != nil {
return err
}
unix = int64(f)
}
*j = jsonTime(time.Unix(unix, 0))
return nil
}
func (j jsonTime) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Time(j).Unix())
}

View File

@@ -1,138 +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 oidc
import (
"encoding/base64"
"encoding/json"
"fmt"
"testing"
"time"
)
func TestJSONTime(t *testing.T) {
data := `{
"t1": 1493851263,
"t2": 1.493851263e9
}`
var v struct {
T1 jsonTime `json:"t1"`
T2 jsonTime `json:"t2"`
}
if err := json.Unmarshal([]byte(data), &v); err != nil {
t.Fatal(err)
}
wantT1 := time.Unix(1493851263, 0)
wantT2 := time.Unix(1493851263, 0)
gotT1 := time.Time(v.T1)
gotT2 := time.Time(v.T2)
if !wantT1.Equal(gotT1) {
t.Errorf("t1 value: wanted %s got %s", wantT1, gotT1)
}
if !wantT2.Equal(gotT2) {
t.Errorf("t2 value: wanted %s got %s", wantT2, gotT2)
}
}
func encodeJWT(header, payload, sig string) string {
e := func(s string) string {
return base64.RawURLEncoding.EncodeToString([]byte(s))
}
return e(header) + "." + e(payload) + "." + e(sig)
}
func TestExpired(t *testing.T) {
now := time.Now()
nowFunc := func() time.Time { return now }
tests := []struct {
name string
idToken string
wantErr bool
wantExpired bool
}{
{
name: "valid",
idToken: encodeJWT(
"{}",
fmt.Sprintf(`{"exp":%d}`, now.Add(time.Hour).Unix()),
"blah", // signature isn't veified.
),
},
{
name: "expired",
idToken: encodeJWT(
"{}",
fmt.Sprintf(`{"exp":%d}`, now.Add(-time.Hour).Unix()),
"blah", // signature isn't veified.
),
wantExpired: true,
},
{
name: "bad exp claim",
idToken: encodeJWT(
"{}",
`{"exp":"foobar"}`,
"blah", // signature isn't veified.
),
wantErr: true,
},
{
name: "not an id token",
idToken: "notanidtoken",
wantErr: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
valid, err := idTokenExpired(nowFunc, test.idToken)
if err != nil {
if !test.wantErr {
t.Errorf("parse error: %v", err)
}
return
}
if test.wantExpired == valid {
t.Errorf("wanted expired %t, got %t", test.wantExpired, !valid)
}
})
}
}
func TestClientCache(t *testing.T) {
cache := newClientCache()
if _, ok := cache.getClient("issuer1", "id1"); ok {
t.Fatalf("got client before putting one in the cache")
}
cli1 := new(oidcAuthProvider)
cli2 := new(oidcAuthProvider)
gotcli := cache.setClient("issuer1", "id1", cli1)
if cli1 != gotcli {
t.Fatalf("set first client and got a different one")
}
gotcli = cache.setClient("issuer1", "id1", cli2)
if cli1 != gotcli {
t.Fatalf("set a second client and didn't get the first")
}
}

View File

@@ -1,193 +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 openstack
import (
"fmt"
"net/http"
"sync"
"time"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack"
"k8s.io/klog"
"k8s.io/apimachinery/pkg/util/net"
restclient "k8s.io/client-go/rest"
)
func init() {
if err := restclient.RegisterAuthProviderPlugin("openstack", newOpenstackAuthProvider); err != nil {
klog.Fatalf("Failed to register openstack auth plugin: %s", err)
}
}
// DefaultTTLDuration is the time before a token gets expired.
const DefaultTTLDuration = 10 * time.Minute
// openstackAuthProvider is an authprovider for openstack. this provider reads
// the environment variables to determine the client identity, and generates a
// token which will be inserted into the request header later.
type openstackAuthProvider struct {
ttl time.Duration
tokenGetter TokenGetter
}
// TokenGetter returns a bearer token that can be inserted into request.
type TokenGetter interface {
Token() (string, error)
}
type tokenGetter struct {
authOpt *gophercloud.AuthOptions
}
// Token creates a token by authenticate with keystone.
func (t *tokenGetter) Token() (string, error) {
var options gophercloud.AuthOptions
var err error
if t.authOpt == nil {
// reads the config from the environment
klog.V(4).Info("reading openstack config from the environment variables")
options, err = openstack.AuthOptionsFromEnv()
if err != nil {
return "", fmt.Errorf("failed to read openstack env vars: %s", err)
}
} else {
options = *t.authOpt
}
client, err := openstack.AuthenticatedClient(options)
if err != nil {
return "", fmt.Errorf("authentication failed: %s", err)
}
return client.TokenID, nil
}
// cachedGetter caches a token until it gets expired, after the expiration, it will
// generate another token and cache it.
type cachedGetter struct {
mutex sync.Mutex
tokenGetter TokenGetter
token string
born time.Time
ttl time.Duration
}
// Token returns the current available token, create a new one if expired.
func (c *cachedGetter) Token() (string, error) {
c.mutex.Lock()
defer c.mutex.Unlock()
var err error
// no token or exceeds the TTL
if c.token == "" || time.Since(c.born) > c.ttl {
c.token, err = c.tokenGetter.Token()
if err != nil {
return "", fmt.Errorf("failed to get token: %s", err)
}
c.born = time.Now()
}
return c.token, nil
}
// tokenRoundTripper implements the RoundTripper interface: adding the bearer token
// into the request header.
type tokenRoundTripper struct {
http.RoundTripper
tokenGetter TokenGetter
}
var _ net.RoundTripperWrapper = &tokenRoundTripper{}
// RoundTrip adds the bearer token into the request.
func (t *tokenRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
// if the authorization header already present, use it.
if req.Header.Get("Authorization") != "" {
return t.RoundTripper.RoundTrip(req)
}
token, err := t.tokenGetter.Token()
if err == nil {
req.Header.Set("Authorization", "Bearer "+token)
} else {
klog.V(4).Infof("failed to get token: %s", err)
}
return t.RoundTripper.RoundTrip(req)
}
func (t *tokenRoundTripper) WrappedRoundTripper() http.RoundTripper { return t.RoundTripper }
// newOpenstackAuthProvider creates an auth provider which works with openstack
// environment.
func newOpenstackAuthProvider(_ string, config map[string]string, persister restclient.AuthProviderConfigPersister) (restclient.AuthProvider, error) {
var ttlDuration time.Duration
var err error
klog.Warningf("WARNING: in-tree openstack auth plugin is now deprecated. please use the \"client-keystone-auth\" kubectl/client-go credential plugin instead")
ttl, found := config["ttl"]
if !found {
ttlDuration = DefaultTTLDuration
// persist to config
config["ttl"] = ttlDuration.String()
if err = persister.Persist(config); err != nil {
return nil, fmt.Errorf("failed to persist config: %s", err)
}
} else {
ttlDuration, err = time.ParseDuration(ttl)
if err != nil {
return nil, fmt.Errorf("failed to parse ttl config: %s", err)
}
}
authOpt := gophercloud.AuthOptions{
IdentityEndpoint: config["identityEndpoint"],
Username: config["username"],
Password: config["password"],
DomainName: config["name"],
TenantID: config["tenantId"],
TenantName: config["tenantName"],
}
getter := tokenGetter{}
// not empty
if (authOpt != gophercloud.AuthOptions{}) {
if len(authOpt.IdentityEndpoint) == 0 {
return nil, fmt.Errorf("empty %q in the config for openstack auth provider", "identityEndpoint")
}
getter.authOpt = &authOpt
}
return &openstackAuthProvider{
ttl: ttlDuration,
tokenGetter: &getter,
}, nil
}
func (oap *openstackAuthProvider) WrapTransport(rt http.RoundTripper) http.RoundTripper {
return &tokenRoundTripper{
RoundTripper: rt,
tokenGetter: &cachedGetter{
tokenGetter: oap.tokenGetter,
ttl: oap.ttl,
},
}
}
func (oap *openstackAuthProvider) Login() error { return nil }

View File

@@ -1,173 +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 openstack
import (
"math/rand"
"net/http"
"testing"
"time"
)
// testTokenGetter is a simple random token getter.
type testTokenGetter struct{}
const LetterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func RandStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = LetterBytes[rand.Intn(len(LetterBytes))]
}
return string(b)
}
func (*testTokenGetter) Token() (string, error) {
return RandStringBytes(32), nil
}
// testRoundTripper is mocked roundtripper which responds with unauthorized when
// there is no authorization header, otherwise returns status ok.
type testRoundTripper struct{}
func (trt *testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
authHeader := req.Header.Get("Authorization")
if authHeader == "" || authHeader == "Bearer " {
return &http.Response{
StatusCode: http.StatusUnauthorized,
}, nil
}
return &http.Response{StatusCode: http.StatusOK}, nil
}
func TestOpenstackAuthProvider(t *testing.T) {
trt := &tokenRoundTripper{
RoundTripper: &testRoundTripper{},
}
tests := []struct {
name string
ttl time.Duration
interval time.Duration
same bool
}{
{
name: "normal",
ttl: 2 * time.Second,
interval: 1 * time.Second,
same: true,
},
{
name: "expire",
ttl: 1 * time.Second,
interval: 2 * time.Second,
same: false,
},
}
for _, test := range tests {
trt.tokenGetter = &cachedGetter{
tokenGetter: &testTokenGetter{},
ttl: test.ttl,
}
req, err := http.NewRequest(http.MethodPost, "https://test-api-server.com", nil)
if err != nil {
t.Errorf("failed to new request: %s", err)
}
trt.RoundTrip(req)
header := req.Header.Get("Authorization")
if header == "" {
t.Errorf("expect to see token in header, but is absent")
}
time.Sleep(test.interval)
req, err = http.NewRequest(http.MethodPost, "https://test-api-server.com", nil)
if err != nil {
t.Errorf("failed to new request: %s", err)
}
trt.RoundTrip(req)
newHeader := req.Header.Get("Authorization")
if newHeader == "" {
t.Errorf("expect to see token in header, but is absent")
}
same := newHeader == header
if same != test.same {
t.Errorf("expect to get %t when compare header, but saw %t", test.same, same)
}
}
}
type fakePersister struct{}
func (i *fakePersister) Persist(map[string]string) error {
return nil
}
func TestNewOpenstackAuthProvider(t *testing.T) {
tests := []struct {
name string
config map[string]string
expectError bool
}{
{
name: "normal config without openstack configurations",
config: map[string]string{
"ttl": "1s",
"foo": "bar",
},
},
{
name: "openstack auth provider: missing identityEndpoint",
config: map[string]string{
"ttl": "1s",
"foo": "bar",
"username": "xyz",
"password": "123",
"tenantName": "admin",
},
expectError: true,
},
{
name: "openstack auth provider",
config: map[string]string{
"ttl": "1s",
"foo": "bar",
"identityEndpoint": "http://controller:35357/v3",
"username": "xyz",
"password": "123",
"tenantName": "admin",
},
},
}
for _, test := range tests {
_, err := newOpenstackAuthProvider("test", test.config, &fakePersister{})
if err != nil {
if !test.expectError {
t.Errorf("unexpected error: %v", err)
}
} else {
if test.expectError {
t.Error("expect error, but nil")
}
}
}
}

View File

@@ -1,25 +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 auth
import (
// Initialize all known client auth plugins.
_ "k8s.io/client-go/plugin/pkg/client/auth/azure"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
_ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
)

24
vendor/k8s.io/client-go/rest/OWNERS generated vendored
View File

@@ -1,24 +0,0 @@
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

View File

@@ -1,343 +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 (
"net/http"
"net/http/httptest"
"net/url"
"os"
"reflect"
"testing"
"time"
"fmt"
"k8s.io/api/core/v1"
v1beta1 "k8s.io/api/extensions/v1beta1"
"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/types"
"k8s.io/apimachinery/pkg/util/diff"
"k8s.io/client-go/kubernetes/scheme"
utiltesting "k8s.io/client-go/util/testing"
)
type TestParam struct {
actualError error
expectingError bool
actualCreated bool
expCreated bool
expStatus *metav1.Status
testBody bool
testBodyErrorIsNotNil bool
}
// TestSerializer makes sure that you're always able to decode metav1.Status
func TestSerializer(t *testing.T) {
gv := v1beta1.SchemeGroupVersion
contentConfig := ContentConfig{
ContentType: "application/json",
GroupVersion: &gv,
NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs},
}
serializer, err := createSerializers(contentConfig)
if err != nil {
t.Fatal(err)
}
// bytes based on actual return from API server when encoding an "unversioned" object
obj, err := runtime.Decode(serializer.Decoder, []byte(`{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Success"}`))
t.Log(obj)
if err != nil {
t.Fatal(err)
}
}
func TestDoRequestSuccess(t *testing.T) {
testServer, fakeHandler, status := testServerEnv(t, 200)
defer testServer.Close()
c, err := restClient(testServer)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
body, err := c.Get().Prefix("test").Do().Raw()
testParam := TestParam{actualError: err, expectingError: false, expCreated: true,
expStatus: status, testBody: true, testBodyErrorIsNotNil: false}
validate(testParam, t, body, fakeHandler)
}
func TestDoRequestFailed(t *testing.T) {
status := &metav1.Status{
Code: http.StatusNotFound,
Status: metav1.StatusFailure,
Reason: metav1.StatusReasonNotFound,
Message: " \"\" not found",
Details: &metav1.StatusDetails{},
}
expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), status)
fakeHandler := utiltesting.FakeHandler{
StatusCode: 404,
ResponseBody: string(expectedBody),
T: t,
}
testServer := httptest.NewServer(&fakeHandler)
defer testServer.Close()
c, err := restClient(testServer)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
err = c.Get().Do().Error()
if err == nil {
t.Errorf("unexpected non-error")
}
ss, ok := err.(errors.APIStatus)
if !ok {
t.Errorf("unexpected error type %v", err)
}
actual := ss.Status()
if !reflect.DeepEqual(status, &actual) {
t.Errorf("Unexpected mis-match: %s", diff.ObjectReflectDiff(status, &actual))
}
}
func TestDoRawRequestFailed(t *testing.T) {
status := &metav1.Status{
Code: http.StatusNotFound,
Status: metav1.StatusFailure,
Reason: metav1.StatusReasonNotFound,
Message: "the server could not find the requested resource",
Details: &metav1.StatusDetails{
Causes: []metav1.StatusCause{
{Type: metav1.CauseTypeUnexpectedServerResponse, Message: "unknown"},
},
},
}
expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), status)
fakeHandler := utiltesting.FakeHandler{
StatusCode: 404,
ResponseBody: string(expectedBody),
T: t,
}
testServer := httptest.NewServer(&fakeHandler)
defer testServer.Close()
c, err := restClient(testServer)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
body, err := c.Get().Do().Raw()
if err == nil || body == nil {
t.Errorf("unexpected non-error: %#v", body)
}
ss, ok := err.(errors.APIStatus)
if !ok {
t.Errorf("unexpected error type %v", err)
}
actual := ss.Status()
if !reflect.DeepEqual(status, &actual) {
t.Errorf("Unexpected mis-match: %s", diff.ObjectReflectDiff(status, &actual))
}
}
func TestDoRequestCreated(t *testing.T) {
testServer, fakeHandler, status := testServerEnv(t, 201)
defer testServer.Close()
c, err := restClient(testServer)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
created := false
body, err := c.Get().Prefix("test").Do().WasCreated(&created).Raw()
testParam := TestParam{actualError: err, expectingError: false, expCreated: true,
expStatus: status, testBody: false}
validate(testParam, t, body, fakeHandler)
}
func TestDoRequestNotCreated(t *testing.T) {
testServer, fakeHandler, expectedStatus := testServerEnv(t, 202)
defer testServer.Close()
c, err := restClient(testServer)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
created := false
body, err := c.Get().Prefix("test").Do().WasCreated(&created).Raw()
testParam := TestParam{actualError: err, expectingError: false, expCreated: false,
expStatus: expectedStatus, testBody: false}
validate(testParam, t, body, fakeHandler)
}
func TestDoRequestAcceptedNoContentReturned(t *testing.T) {
testServer, fakeHandler, _ := testServerEnv(t, 204)
defer testServer.Close()
c, err := restClient(testServer)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
created := false
body, err := c.Get().Prefix("test").Do().WasCreated(&created).Raw()
testParam := TestParam{actualError: err, expectingError: false, expCreated: false,
testBody: false}
validate(testParam, t, body, fakeHandler)
}
func TestBadRequest(t *testing.T) {
testServer, fakeHandler, _ := testServerEnv(t, 400)
defer testServer.Close()
c, err := restClient(testServer)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
created := false
body, err := c.Get().Prefix("test").Do().WasCreated(&created).Raw()
testParam := TestParam{actualError: err, expectingError: true, expCreated: false,
testBody: true}
validate(testParam, t, body, fakeHandler)
}
func validate(testParam TestParam, t *testing.T, body []byte, fakeHandler *utiltesting.FakeHandler) {
switch {
case testParam.expectingError && testParam.actualError == nil:
t.Errorf("Expected error")
case !testParam.expectingError && testParam.actualError != nil:
t.Error(testParam.actualError)
}
if !testParam.expCreated {
if testParam.actualCreated {
t.Errorf("Expected object not to be created")
}
}
statusOut, err := runtime.Decode(scheme.Codecs.UniversalDeserializer(), body)
if testParam.testBody {
if testParam.testBodyErrorIsNotNil && err == nil {
t.Errorf("Expected Error")
}
if !testParam.testBodyErrorIsNotNil && err != nil {
t.Errorf("Unexpected Error: %v", err)
}
}
if testParam.expStatus != nil {
if !reflect.DeepEqual(testParam.expStatus, statusOut) {
t.Errorf("Unexpected mis-match. Expected %#v. Saw %#v", testParam.expStatus, statusOut)
}
}
fakeHandler.ValidateRequest(t, "/"+v1.SchemeGroupVersion.String()+"/test", "GET", nil)
}
func TestHttpMethods(t *testing.T) {
testServer, _, _ := testServerEnv(t, 200)
defer testServer.Close()
c, _ := restClient(testServer)
request := c.Post()
if request == nil {
t.Errorf("Post : Object returned should not be nil")
}
request = c.Get()
if request == nil {
t.Errorf("Get: Object returned should not be nil")
}
request = c.Put()
if request == nil {
t.Errorf("Put : Object returned should not be nil")
}
request = c.Delete()
if request == nil {
t.Errorf("Delete : Object returned should not be nil")
}
request = c.Patch(types.JSONPatchType)
if request == nil {
t.Errorf("Patch : Object returned should not be nil")
}
}
func TestCreateBackoffManager(t *testing.T) {
theUrl, _ := url.Parse("http://localhost")
// 1 second base backoff + duration of 2 seconds -> exponential backoff for requests.
os.Setenv(envBackoffBase, "1")
os.Setenv(envBackoffDuration, "2")
backoff := readExpBackoffConfig()
backoff.UpdateBackoff(theUrl, nil, 500)
backoff.UpdateBackoff(theUrl, nil, 500)
if backoff.CalculateBackoff(theUrl)/time.Second != 2 {
t.Errorf("Backoff env not working.")
}
// 0 duration -> no backoff.
os.Setenv(envBackoffBase, "1")
os.Setenv(envBackoffDuration, "0")
backoff.UpdateBackoff(theUrl, nil, 500)
backoff.UpdateBackoff(theUrl, nil, 500)
backoff = readExpBackoffConfig()
if backoff.CalculateBackoff(theUrl)/time.Second != 0 {
t.Errorf("Zero backoff duration, but backoff still occurring.")
}
// No env -> No backoff.
os.Setenv(envBackoffBase, "")
os.Setenv(envBackoffDuration, "")
backoff = readExpBackoffConfig()
backoff.UpdateBackoff(theUrl, nil, 500)
backoff.UpdateBackoff(theUrl, nil, 500)
if backoff.CalculateBackoff(theUrl)/time.Second != 0 {
t.Errorf("Backoff should have been 0.")
}
}
func testServerEnv(t *testing.T, statusCode int) (*httptest.Server, *utiltesting.FakeHandler, *metav1.Status) {
status := &metav1.Status{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Status"}, Status: fmt.Sprintf("%s", metav1.StatusSuccess)}
expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), status)
fakeHandler := utiltesting.FakeHandler{
StatusCode: statusCode,
ResponseBody: string(expectedBody),
T: t,
}
testServer := httptest.NewServer(&fakeHandler)
return testServer, &fakeHandler, status
}
func restClient(testServer *httptest.Server) (*RESTClient, error) {
c, err := RESTClientFor(&Config{
Host: testServer.URL,
ContentConfig: ContentConfig{
GroupVersion: &v1.SchemeGroupVersion,
NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs},
},
Username: "user",
Password: "pass",
})
return c, err
}

View File

@@ -1,375 +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"
"io"
"net"
"net/http"
"path/filepath"
"reflect"
"strings"
"testing"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/diff"
"k8s.io/client-go/kubernetes/scheme"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/client-go/util/flowcontrol"
fuzz "github.com/google/gofuzz"
"github.com/stretchr/testify/assert"
)
func TestIsConfigTransportTLS(t *testing.T) {
testCases := []struct {
Config *Config
TransportTLS bool
}{
{
Config: &Config{},
TransportTLS: false,
},
{
Config: &Config{
Host: "https://localhost",
},
TransportTLS: true,
},
{
Config: &Config{
Host: "localhost",
TLSClientConfig: TLSClientConfig{
CertFile: "foo",
},
},
TransportTLS: true,
},
{
Config: &Config{
Host: "///:://localhost",
TLSClientConfig: TLSClientConfig{
CertFile: "foo",
},
},
TransportTLS: false,
},
{
Config: &Config{
Host: "1.2.3.4:567",
TLSClientConfig: TLSClientConfig{
Insecure: true,
},
},
TransportTLS: true,
},
}
for _, testCase := range testCases {
if err := SetKubernetesDefaults(testCase.Config); err != nil {
t.Errorf("setting defaults failed for %#v: %v", testCase.Config, err)
continue
}
useTLS := IsConfigTransportTLS(*testCase.Config)
if testCase.TransportTLS != useTLS {
t.Errorf("expected %v for %#v", testCase.TransportTLS, testCase.Config)
}
}
}
func TestSetKubernetesDefaultsUserAgent(t *testing.T) {
config := &Config{}
if err := SetKubernetesDefaults(config); err != nil {
t.Errorf("unexpected error: %v", err)
}
if !strings.Contains(config.UserAgent, "kubernetes/") {
t.Errorf("no user agent set: %#v", config)
}
}
func TestAdjustVersion(t *testing.T) {
assert := assert.New(t)
assert.Equal("1.2.3", adjustVersion("1.2.3-alpha4"))
assert.Equal("1.2.3", adjustVersion("1.2.3-alpha"))
assert.Equal("1.2.3", adjustVersion("1.2.3"))
assert.Equal("unknown", adjustVersion(""))
}
func TestAdjustCommit(t *testing.T) {
assert := assert.New(t)
assert.Equal("1234567", adjustCommit("1234567890"))
assert.Equal("123456", adjustCommit("123456"))
assert.Equal("unknown", adjustCommit(""))
}
func TestAdjustCommand(t *testing.T) {
assert := assert.New(t)
assert.Equal("beans", adjustCommand(filepath.Join("home", "bob", "Downloads", "beans")))
assert.Equal("beans", adjustCommand(filepath.Join(".", "beans")))
assert.Equal("beans", adjustCommand("beans"))
assert.Equal("unknown", adjustCommand(""))
}
func TestBuildUserAgent(t *testing.T) {
assert.New(t).Equal(
"lynx/nicest (beos/itanium) kubernetes/baaaaaaaaad",
buildUserAgent(
"lynx", "nicest",
"beos", "itanium", "baaaaaaaaad"))
}
// This function untestable since it doesn't accept arguments.
func TestDefaultKubernetesUserAgent(t *testing.T) {
assert.New(t).Contains(DefaultKubernetesUserAgent(), "kubernetes")
}
func TestRESTClientRequires(t *testing.T) {
if _, err := RESTClientFor(&Config{Host: "127.0.0.1", ContentConfig: ContentConfig{NegotiatedSerializer: scheme.Codecs}}); err == nil {
t.Errorf("unexpected non-error")
}
if _, err := RESTClientFor(&Config{Host: "127.0.0.1", ContentConfig: ContentConfig{GroupVersion: &v1.SchemeGroupVersion}}); err == nil {
t.Errorf("unexpected non-error")
}
if _, err := RESTClientFor(&Config{Host: "127.0.0.1", ContentConfig: ContentConfig{GroupVersion: &v1.SchemeGroupVersion, NegotiatedSerializer: scheme.Codecs}}); err != nil {
t.Errorf("unexpected error: %v", err)
}
}
type fakeLimiter struct {
FakeSaturation float64
FakeQPS float32
}
func (t *fakeLimiter) TryAccept() bool {
return true
}
func (t *fakeLimiter) Saturation() float64 {
return t.FakeSaturation
}
func (t *fakeLimiter) QPS() float32 {
return t.FakeQPS
}
func (t *fakeLimiter) Stop() {}
func (t *fakeLimiter) Accept() {}
type fakeCodec struct{}
func (c *fakeCodec) Decode([]byte, *schema.GroupVersionKind, runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
return nil, nil, nil
}
func (c *fakeCodec) Encode(obj runtime.Object, stream io.Writer) error {
return nil
}
type fakeRoundTripper struct{}
func (r *fakeRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {
return nil, nil
}
var fakeWrapperFunc = func(http.RoundTripper) http.RoundTripper {
return &fakeRoundTripper{}
}
type fakeNegotiatedSerializer struct{}
func (n *fakeNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo {
return nil
}
func (n *fakeNegotiatedSerializer) EncoderForVersion(serializer runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {
return &fakeCodec{}
}
func (n *fakeNegotiatedSerializer) DecoderToVersion(serializer runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {
return &fakeCodec{}
}
var fakeDialFunc = func(ctx context.Context, network, addr string) (net.Conn, error) {
return nil, fakeDialerError
}
var fakeDialerError = errors.New("fakedialer")
type fakeAuthProviderConfigPersister struct{}
func (fakeAuthProviderConfigPersister) Persist(map[string]string) error {
return fakeAuthProviderConfigPersisterError
}
var fakeAuthProviderConfigPersisterError = errors.New("fakeAuthProviderConfigPersisterError")
func TestAnonymousConfig(t *testing.T) {
f := fuzz.New().NilChance(0.0).NumElements(1, 1)
f.Funcs(
func(r *runtime.Codec, f fuzz.Continue) {
codec := &fakeCodec{}
f.Fuzz(codec)
*r = codec
},
func(r *http.RoundTripper, f fuzz.Continue) {
roundTripper := &fakeRoundTripper{}
f.Fuzz(roundTripper)
*r = roundTripper
},
func(fn *func(http.RoundTripper) http.RoundTripper, f fuzz.Continue) {
*fn = fakeWrapperFunc
},
func(r *runtime.NegotiatedSerializer, f fuzz.Continue) {
serializer := &fakeNegotiatedSerializer{}
f.Fuzz(serializer)
*r = serializer
},
func(r *flowcontrol.RateLimiter, f fuzz.Continue) {
limiter := &fakeLimiter{}
f.Fuzz(limiter)
*r = limiter
},
// Authentication does not require fuzzer
func(r *AuthProviderConfigPersister, f fuzz.Continue) {},
func(r *clientcmdapi.AuthProviderConfig, f fuzz.Continue) {
r.Config = map[string]string{}
},
// Dial does not require fuzzer
func(r *func(ctx context.Context, network, addr string) (net.Conn, error), f fuzz.Continue) {},
)
for i := 0; i < 20; i++ {
original := &Config{}
f.Fuzz(original)
actual := AnonymousClientConfig(original)
expected := *original
// this is the list of known security related fields, add to this list if a new field
// is added to Config, update AnonymousClientConfig to preserve the field otherwise.
expected.Impersonate = ImpersonationConfig{}
expected.BearerToken = ""
expected.Username = ""
expected.Password = ""
expected.AuthProvider = nil
expected.AuthConfigPersister = nil
expected.ExecProvider = nil
expected.TLSClientConfig.CertData = nil
expected.TLSClientConfig.CertFile = ""
expected.TLSClientConfig.KeyData = nil
expected.TLSClientConfig.KeyFile = ""
// The DeepEqual cannot handle the func comparison, so we just verify if the
// function return the expected object.
if actual.WrapTransport == nil || !reflect.DeepEqual(expected.WrapTransport(nil), &fakeRoundTripper{}) {
t.Fatalf("AnonymousClientConfig dropped the WrapTransport field")
} else {
actual.WrapTransport = nil
expected.WrapTransport = nil
}
if actual.Dial != nil {
_, actualError := actual.Dial(context.Background(), "", "")
_, expectedError := expected.Dial(context.Background(), "", "")
if !reflect.DeepEqual(expectedError, actualError) {
t.Fatalf("CopyConfig dropped the Dial field")
}
} else {
actual.Dial = nil
expected.Dial = nil
}
if !reflect.DeepEqual(*actual, expected) {
t.Fatalf("AnonymousClientConfig dropped unexpected fields, identify whether they are security related or not: %s", diff.ObjectGoPrintDiff(expected, actual))
}
}
}
func TestCopyConfig(t *testing.T) {
f := fuzz.New().NilChance(0.0).NumElements(1, 1)
f.Funcs(
func(r *runtime.Codec, f fuzz.Continue) {
codec := &fakeCodec{}
f.Fuzz(codec)
*r = codec
},
func(r *http.RoundTripper, f fuzz.Continue) {
roundTripper := &fakeRoundTripper{}
f.Fuzz(roundTripper)
*r = roundTripper
},
func(fn *func(http.RoundTripper) http.RoundTripper, f fuzz.Continue) {
*fn = fakeWrapperFunc
},
func(r *runtime.NegotiatedSerializer, f fuzz.Continue) {
serializer := &fakeNegotiatedSerializer{}
f.Fuzz(serializer)
*r = serializer
},
func(r *flowcontrol.RateLimiter, f fuzz.Continue) {
limiter := &fakeLimiter{}
f.Fuzz(limiter)
*r = limiter
},
func(r *AuthProviderConfigPersister, f fuzz.Continue) {
*r = fakeAuthProviderConfigPersister{}
},
func(r *func(ctx context.Context, network, addr string) (net.Conn, error), f fuzz.Continue) {
*r = fakeDialFunc
},
)
for i := 0; i < 20; i++ {
original := &Config{}
f.Fuzz(original)
actual := CopyConfig(original)
expected := *original
// this is the list of known risky fields, add to this list if a new field
// is added to Config, update CopyConfig to preserve the field otherwise.
// The DeepEqual cannot handle the func comparison, so we just verify if the
// function return the expected object.
if actual.WrapTransport == nil || !reflect.DeepEqual(expected.WrapTransport(nil), &fakeRoundTripper{}) {
t.Fatalf("CopyConfig dropped the WrapTransport field")
} else {
actual.WrapTransport = nil
expected.WrapTransport = nil
}
if actual.Dial != nil {
_, actualError := actual.Dial(context.Background(), "", "")
_, expectedError := expected.Dial(context.Background(), "", "")
if !reflect.DeepEqual(expectedError, actualError) {
t.Fatalf("CopyConfig dropped the Dial field")
}
}
actual.Dial = nil
expected.Dial = nil
if actual.AuthConfigPersister != nil {
actualError := actual.AuthConfigPersister.Persist(nil)
expectedError := expected.AuthConfigPersister.Persist(nil)
if !reflect.DeepEqual(expectedError, actualError) {
t.Fatalf("CopyConfig dropped the Dial field")
}
}
actual.AuthConfigPersister = nil
expected.AuthConfigPersister = nil
if !reflect.DeepEqual(*actual, expected) {
t.Fatalf("CopyConfig dropped unexpected fields, identify whether they are security related or not: %s", diff.ObjectReflectDiff(expected, *actual))
}
}
}

View File

@@ -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.
*/
// This is made a separate package and should only be imported by tests, because
// it imports testapi
package fake
import (
"net/http"
"net/url"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/util/flowcontrol"
)
func CreateHTTPClient(roundTripper func(*http.Request) (*http.Response, error)) *http.Client {
return &http.Client{
Transport: roundTripperFunc(roundTripper),
}
}
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
// RESTClient provides a fake RESTClient interface.
type RESTClient struct {
Client *http.Client
NegotiatedSerializer runtime.NegotiatedSerializer
GroupVersion schema.GroupVersion
VersionedAPIPath string
Req *http.Request
Resp *http.Response
Err error
}
func (c *RESTClient) Get() *restclient.Request {
return c.request("GET")
}
func (c *RESTClient) Put() *restclient.Request {
return c.request("PUT")
}
func (c *RESTClient) Patch(pt types.PatchType) *restclient.Request {
return c.request("PATCH").SetHeader("Content-Type", string(pt))
}
func (c *RESTClient) Post() *restclient.Request {
return c.request("POST")
}
func (c *RESTClient) Delete() *restclient.Request {
return c.request("DELETE")
}
func (c *RESTClient) Verb(verb string) *restclient.Request {
return c.request(verb)
}
func (c *RESTClient) APIVersion() schema.GroupVersion {
return c.GroupVersion
}
func (c *RESTClient) GetRateLimiter() flowcontrol.RateLimiter {
return nil
}
func (c *RESTClient) request(verb string) *restclient.Request {
config := restclient.ContentConfig{
ContentType: runtime.ContentTypeJSON,
GroupVersion: &c.GroupVersion,
NegotiatedSerializer: c.NegotiatedSerializer,
}
ns := c.NegotiatedSerializer
info, _ := runtime.SerializerInfoForMediaType(ns.SupportedMediaTypes(), runtime.ContentTypeJSON)
serializers := restclient.Serializers{
// TODO this was hardcoded before, but it doesn't look right
Encoder: ns.EncoderForVersion(info.Serializer, c.GroupVersion),
Decoder: ns.DecoderToVersion(info.Serializer, c.GroupVersion),
}
if info.StreamSerializer != nil {
serializers.StreamingSerializer = info.StreamSerializer.Serializer
serializers.Framer = info.StreamSerializer.Framer
}
return restclient.NewRequest(c, verb, &url.URL{Host: "localhost"}, c.VersionedAPIPath, config, serializers, nil, nil, 0)
}
func (c *RESTClient) Do(req *http.Request) (*http.Response, error) {
if c.Err != nil {
return nil, c.Err
}
c.Req = req
if c.Client != nil {
return c.Client.Do(req)
}
return c.Resp, nil
}

View File

@@ -1,311 +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"
"reflect"
"strconv"
"testing"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
func TestAuthPluginWrapTransport(t *testing.T) {
if err := RegisterAuthProviderPlugin("pluginA", pluginAProvider); err != nil {
t.Errorf("Unexpected error: failed to register pluginA: %v", err)
}
if err := RegisterAuthProviderPlugin("pluginB", pluginBProvider); err != nil {
t.Errorf("Unexpected error: failed to register pluginB: %v", err)
}
if err := RegisterAuthProviderPlugin("pluginFail", pluginFailProvider); err != nil {
t.Errorf("Unexpected error: failed to register pluginFail: %v", err)
}
testCases := []struct {
useWrapTransport bool
plugin string
expectErr bool
expectPluginA bool
expectPluginB bool
}{
{false, "", false, false, false},
{false, "pluginA", false, true, false},
{false, "pluginB", false, false, true},
{false, "pluginFail", true, false, false},
{false, "pluginUnknown", true, false, false},
}
for i, tc := range testCases {
c := Config{}
if tc.useWrapTransport {
// Specify an existing WrapTransport in the config to make sure that
// plugins play nicely.
c.WrapTransport = func(rt http.RoundTripper) http.RoundTripper {
return &wrapTransport{rt}
}
}
if len(tc.plugin) != 0 {
c.AuthProvider = &clientcmdapi.AuthProviderConfig{Name: tc.plugin}
}
tConfig, err := c.TransportConfig()
if err != nil {
// Unknown/bad plugins are expected to fail here.
if !tc.expectErr {
t.Errorf("%d. Did not expect errors loading Auth Plugin: %q. Got: %v", i, tc.plugin, err)
}
continue
}
var fullyWrappedTransport http.RoundTripper
fullyWrappedTransport = &emptyTransport{}
if tConfig.WrapTransport != nil {
fullyWrappedTransport = tConfig.WrapTransport(&emptyTransport{})
}
res, err := fullyWrappedTransport.RoundTrip(&http.Request{})
if err != nil {
t.Errorf("%d. Unexpected error in RoundTrip: %v", i, err)
continue
}
hasWrapTransport := res.Header.Get("wrapTransport") == "Y"
hasPluginA := res.Header.Get("pluginA") == "Y"
hasPluginB := res.Header.Get("pluginB") == "Y"
if hasWrapTransport != tc.useWrapTransport {
t.Errorf("%d. Expected Existing config.WrapTransport: %t; Got: %t", i, tc.useWrapTransport, hasWrapTransport)
}
if hasPluginA != tc.expectPluginA {
t.Errorf("%d. Expected Plugin A: %t; Got: %t", i, tc.expectPluginA, hasPluginA)
}
if hasPluginB != tc.expectPluginB {
t.Errorf("%d. Expected Plugin B: %t; Got: %t", i, tc.expectPluginB, hasPluginB)
}
}
}
func TestAuthPluginPersist(t *testing.T) {
// register pluginA by a different name so we don't collide across tests.
if err := RegisterAuthProviderPlugin("pluginA2", pluginAProvider); err != nil {
t.Errorf("Unexpected error: failed to register pluginA: %v", err)
}
if err := RegisterAuthProviderPlugin("pluginPersist", pluginPersistProvider); err != nil {
t.Errorf("Unexpected error: failed to register pluginPersist: %v", err)
}
fooBarConfig := map[string]string{"foo": "bar"}
testCases := []struct {
plugin string
startingConfig map[string]string
expectedConfigAfterLogin map[string]string
expectedConfigAfterRoundTrip map[string]string
}{
// non-persisting plugins should work fine without modifying config.
{"pluginA2", map[string]string{}, map[string]string{}, map[string]string{}},
{"pluginA2", fooBarConfig, fooBarConfig, fooBarConfig},
// plugins that persist config should be able to persist when they want.
{
"pluginPersist",
map[string]string{},
map[string]string{
"login": "Y",
},
map[string]string{
"login": "Y",
"roundTrips": "1",
},
},
{
"pluginPersist",
map[string]string{
"login": "Y",
"roundTrips": "123",
},
map[string]string{
"login": "Y",
"roundTrips": "123",
},
map[string]string{
"login": "Y",
"roundTrips": "124",
},
},
}
for i, tc := range testCases {
cfg := &clientcmdapi.AuthProviderConfig{
Name: tc.plugin,
Config: tc.startingConfig,
}
persister := &inMemoryPersister{make(map[string]string)}
persister.Persist(tc.startingConfig)
plugin, err := GetAuthProvider("127.0.0.1", cfg, persister)
if err != nil {
t.Errorf("%d. Unexpected error: failed to get plugin %q: %v", i, tc.plugin, err)
}
if err := plugin.Login(); err != nil {
t.Errorf("%d. Unexpected error calling Login() w/ plugin %q: %v", i, tc.plugin, err)
}
// Make sure the plugin persisted what we expect after Login().
if !reflect.DeepEqual(persister.savedConfig, tc.expectedConfigAfterLogin) {
t.Errorf("%d. Unexpected persisted config after calling %s.Login(): \nGot:\n%v\nExpected:\n%v",
i, tc.plugin, persister.savedConfig, tc.expectedConfigAfterLogin)
}
if _, err := plugin.WrapTransport(&emptyTransport{}).RoundTrip(&http.Request{}); err != nil {
t.Errorf("%d. Unexpected error round-tripping w/ plugin %q: %v", i, tc.plugin, err)
}
// Make sure the plugin persisted what we expect after RoundTrip().
if !reflect.DeepEqual(persister.savedConfig, tc.expectedConfigAfterRoundTrip) {
t.Errorf("%d. Unexpected persisted config after calling %s.WrapTransport.RoundTrip(): \nGot:\n%v\nExpected:\n%v",
i, tc.plugin, persister.savedConfig, tc.expectedConfigAfterLogin)
}
}
}
// emptyTransport provides an empty http.Response with an initialized header
// to allow wrapping RoundTrippers to set header values.
type emptyTransport struct{}
func (*emptyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
res := &http.Response{
Header: make(map[string][]string),
}
return res, nil
}
// wrapTransport sets "wrapTransport" = "Y" on the response.
type wrapTransport struct {
rt http.RoundTripper
}
func (w *wrapTransport) RoundTrip(req *http.Request) (*http.Response, error) {
res, err := w.rt.RoundTrip(req)
if err != nil {
return nil, err
}
res.Header.Add("wrapTransport", "Y")
return res, nil
}
// wrapTransportA sets "pluginA" = "Y" on the response.
type wrapTransportA struct {
rt http.RoundTripper
}
func (w *wrapTransportA) RoundTrip(req *http.Request) (*http.Response, error) {
res, err := w.rt.RoundTrip(req)
if err != nil {
return nil, err
}
res.Header.Add("pluginA", "Y")
return res, nil
}
type pluginA struct{}
func (*pluginA) WrapTransport(rt http.RoundTripper) http.RoundTripper {
return &wrapTransportA{rt}
}
func (*pluginA) Login() error { return nil }
func pluginAProvider(string, map[string]string, AuthProviderConfigPersister) (AuthProvider, error) {
return &pluginA{}, nil
}
// wrapTransportB sets "pluginB" = "Y" on the response.
type wrapTransportB struct {
rt http.RoundTripper
}
func (w *wrapTransportB) RoundTrip(req *http.Request) (*http.Response, error) {
res, err := w.rt.RoundTrip(req)
if err != nil {
return nil, err
}
res.Header.Add("pluginB", "Y")
return res, nil
}
type pluginB struct{}
func (*pluginB) WrapTransport(rt http.RoundTripper) http.RoundTripper {
return &wrapTransportB{rt}
}
func (*pluginB) Login() error { return nil }
func pluginBProvider(string, map[string]string, AuthProviderConfigPersister) (AuthProvider, error) {
return &pluginB{}, nil
}
// pluginFailProvider simulates a registered AuthPlugin that fails to load.
func pluginFailProvider(string, map[string]string, AuthProviderConfigPersister) (AuthProvider, error) {
return nil, fmt.Errorf("Failed to load AuthProvider")
}
type inMemoryPersister struct {
savedConfig map[string]string
}
func (i *inMemoryPersister) Persist(config map[string]string) error {
i.savedConfig = make(map[string]string)
for k, v := range config {
i.savedConfig[k] = v
}
return nil
}
// wrapTransportPersist increments the "roundTrips" entry from the config when
// roundTrip is called.
type wrapTransportPersist struct {
rt http.RoundTripper
config map[string]string
persister AuthProviderConfigPersister
}
func (w *wrapTransportPersist) RoundTrip(req *http.Request) (*http.Response, error) {
roundTrips := 0
if rtVal, ok := w.config["roundTrips"]; ok {
var err error
roundTrips, err = strconv.Atoi(rtVal)
if err != nil {
return nil, err
}
}
roundTrips++
w.config["roundTrips"] = fmt.Sprintf("%d", roundTrips)
if err := w.persister.Persist(w.config); err != nil {
return nil, err
}
return w.rt.RoundTrip(req)
}
type pluginPersist struct {
config map[string]string
persister AuthProviderConfigPersister
}
func (p *pluginPersist) WrapTransport(rt http.RoundTripper) http.RoundTripper {
return &wrapTransportPersist{rt, p.config, p.persister}
}
// Login sets the config entry "login" to "Y".
func (p *pluginPersist) Login() error {
p.config["login"] = "Y"
p.persister.Persist(p.config)
return nil
}
func pluginPersistProvider(_ string, config map[string]string, persister AuthProviderConfigPersister) (AuthProvider, error) {
return &pluginPersist{config, persister}, nil
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,156 +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 rest
import (
"fmt"
"reflect"
"sync"
"testing"
"time"
"golang.org/x/oauth2"
)
type testTokenSource struct {
calls int
tok *oauth2.Token
err error
}
func (ts *testTokenSource) Token() (*oauth2.Token, error) {
ts.calls++
return ts.tok, ts.err
}
func TestCachingTokenSource(t *testing.T) {
start := time.Now()
tokA := &oauth2.Token{
AccessToken: "a",
Expiry: start.Add(10 * time.Minute),
}
tokB := &oauth2.Token{
AccessToken: "b",
Expiry: start.Add(20 * time.Minute),
}
tests := []struct {
name string
tok *oauth2.Token
tsTok *oauth2.Token
tsErr error
wait time.Duration
wantTok *oauth2.Token
wantErr bool
wantTSCalls int
}{
{
name: "valid token returned from cache",
tok: tokA,
wantTok: tokA,
},
{
name: "valid token returned from cache 1 minute before scheduled refresh",
tok: tokA,
wait: 8 * time.Minute,
wantTok: tokA,
},
{
name: "new token created when cache is empty",
tsTok: tokA,
wantTok: tokA,
wantTSCalls: 1,
},
{
name: "new token created 1 minute after scheduled refresh",
tok: tokA,
tsTok: tokB,
wait: 10 * time.Minute,
wantTok: tokB,
wantTSCalls: 1,
},
{
name: "error on create token returns error",
tsErr: fmt.Errorf("error"),
wantErr: true,
wantTSCalls: 1,
},
}
for _, c := range tests {
t.Run(c.name, func(t *testing.T) {
tts := &testTokenSource{
tok: c.tsTok,
err: c.tsErr,
}
ts := &cachingTokenSource{
base: tts,
tok: c.tok,
leeway: 1 * time.Minute,
now: func() time.Time { return start.Add(c.wait) },
}
gotTok, gotErr := ts.Token()
if got, want := gotTok, c.wantTok; !reflect.DeepEqual(got, want) {
t.Errorf("unexpected token:\n\tgot:\t%#v\n\twant:\t%#v", got, want)
}
if got, want := tts.calls, c.wantTSCalls; got != want {
t.Errorf("unexpected number of Token() calls: got %d, want %d", got, want)
}
if gotErr == nil && c.wantErr {
t.Errorf("wanted error but got none")
}
if gotErr != nil && !c.wantErr {
t.Errorf("unexpected error: %v", gotErr)
}
})
}
}
func TestCachingTokenSourceRace(t *testing.T) {
for i := 0; i < 100; i++ {
tts := &testTokenSource{
tok: &oauth2.Token{
AccessToken: "a",
Expiry: time.Now().Add(1000 * time.Hour),
},
}
ts := &cachingTokenSource{
now: time.Now,
base: tts,
leeway: 1 * time.Minute,
}
var wg sync.WaitGroup
wg.Add(100)
for i := 0; i < 100; i++ {
go func() {
defer wg.Done()
if _, err := ts.Token(); err != nil {
t.Fatalf("err: %v", err)
}
}()
}
wg.Wait()
if tts.calls != 1 {
t.Errorf("expected one call to Token() but saw: %d", tts.calls)
}
}
}

View File

@@ -1,61 +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 (
"path"
"testing"
"k8s.io/api/core/v1"
)
func TestValidatesHostParameter(t *testing.T) {
testCases := []struct {
Host string
APIPath string
URL string
Err bool
}{
{"127.0.0.1", "", "http://127.0.0.1/" + v1.SchemeGroupVersion.Version, false},
{"127.0.0.1:8080", "", "http://127.0.0.1:8080/" + v1.SchemeGroupVersion.Version, false},
{"foo.bar.com", "", "http://foo.bar.com/" + v1.SchemeGroupVersion.Version, false},
{"http://host/prefix", "", "http://host/prefix/" + v1.SchemeGroupVersion.Version, false},
{"http://host", "", "http://host/" + v1.SchemeGroupVersion.Version, false},
{"http://host", "/", "http://host/" + v1.SchemeGroupVersion.Version, false},
{"http://host", "/other", "http://host/other/" + v1.SchemeGroupVersion.Version, false},
{"host/server", "", "", true},
}
for i, testCase := range testCases {
u, versionedAPIPath, err := DefaultServerURL(testCase.Host, testCase.APIPath, v1.SchemeGroupVersion, false)
switch {
case err == nil && testCase.Err:
t.Errorf("expected error but was nil")
continue
case err != nil && !testCase.Err:
t.Errorf("unexpected error %v", err)
continue
case err != nil:
continue
}
u.Path = path.Join(u.Path, versionedAPIPath)
if e, a := testCase.URL, u.String(); e != a {
t.Errorf("%d: expected host %s, got %s", i, e, a)
continue
}
}
}

Some files were not shown because too many files have changed in this diff Show More