From 374967e62902de652588ec3d3f27d60d7895f1f0 Mon Sep 17 00:00:00 2001 From: caryxychen <101852328+caryxychen@users.noreply.github.com> Date: Wed, 10 Aug 2022 16:42:59 +0800 Subject: [PATCH] feat(authz): support multi-cluster role and rolebinding (#2012) Co-authored-by: caryxychen --- api/authz/doc.go | 23 + api/authz/install/doc.go | 19 + api/authz/install/install.go | 37 + api/authz/register.go | 74 + api/authz/types.go | 195 + api/authz/v1/doc.go | 26 + api/authz/v1/generated.pb.go | 3188 +++++++++++++++++ api/authz/v1/generated.proto | 151 + api/authz/v1/register.go | 69 + api/authz/v1/types.go | 184 + api/authz/v1/types_swagger_doc_generated.go | 93 + api/authz/v1/zz_generated.conversion.go | 396 ++ api/authz/v1/zz_generated.deepcopy.go | 337 ++ api/authz/v1/zz_generated.defaults.go | 34 + api/authz/zz_generated.deepcopy.go | 337 ++ .../clientset/internalversion/clientset.go | 14 + .../fake/clientset_generated.go | 7 + .../internalversion/fake/register.go | 2 + .../internalversion/scheme/register.go | 2 + .../authz/internalversion/authz_client.go | 113 + .../typed/authz/internalversion/configmap.go | 170 + .../typed/authz/internalversion/doc.go | 22 + .../typed/authz/internalversion/fake/doc.go | 22 + .../internalversion/fake/fake_authz_client.go | 54 + .../internalversion/fake/fake_configmap.go | 124 + .../fake/fake_multiclusterrolebinding.go | 136 + .../authz/internalversion/fake/fake_policy.go | 124 + .../authz/internalversion/fake/fake_role.go | 124 + .../internalversion/generated_expansion.go | 29 + .../multiclusterrolebinding.go | 180 + .../typed/authz/internalversion/policy.go | 163 + .../typed/authz/internalversion/role.go | 163 + api/client/clientset/versioned/clientset.go | 14 + .../versioned/fake/clientset_generated.go | 7 + .../clientset/versioned/fake/register.go | 2 + .../clientset/versioned/scheme/register.go | 2 + .../versioned/typed/authz/v1/authz_client.go | 106 + .../versioned/typed/authz/v1/configmap.go | 154 + .../clientset/versioned/typed/authz/v1/doc.go | 22 + .../versioned/typed/authz/v1/fake/doc.go | 22 + .../typed/authz/v1/fake/fake_authz_client.go | 54 + .../typed/authz/v1/fake/fake_configmap.go | 116 + .../v1/fake/fake_multiclusterrolebinding.go | 136 + .../typed/authz/v1/fake/fake_policy.go | 124 + .../typed/authz/v1/fake/fake_role.go | 124 + .../typed/authz/v1/generated_expansion.go | 29 + .../typed/authz/v1/multiclusterrolebinding.go | 180 + .../versioned/typed/authz/v1/policy.go | 163 + .../versioned/typed/authz/v1/role.go | 163 + .../externalversions/authz/interface.go | 48 + .../externalversions/authz/v1/configmap.go | 91 + .../externalversions/authz/v1/interface.go | 68 + .../authz/v1/multiclusterrolebinding.go | 92 + .../externalversions/authz/v1/policy.go | 92 + .../externalversions/authz/v1/role.go | 92 + .../informers/externalversions/factory.go | 6 + .../informers/externalversions/generic.go | 11 + .../internalversion/authz/interface.go | 48 + .../authz/internalversion/configmap.go | 91 + .../authz/internalversion/interface.go | 68 + .../multiclusterrolebinding.go | 92 + .../authz/internalversion/policy.go | 92 + .../authz/internalversion/role.go | 92 + .../informers/internalversion/factory.go | 6 + .../informers/internalversion/generic.go | 11 + .../authz/internalversion/configmap.go | 70 + .../internalversion/expansion_generated.go | 49 + .../multiclusterrolebinding.go | 101 + .../listers/authz/internalversion/policy.go | 101 + .../listers/authz/internalversion/role.go | 101 + api/client/listers/authz/v1/configmap.go | 70 + .../listers/authz/v1/expansion_generated.go | 49 + .../authz/v1/multiclusterrolebinding.go | 101 + api/client/listers/authz/v1/policy.go | 101 + api/client/listers/authz/v1/role.go | 101 + api/openapi/zz_generated.openapi.go | 557 +++ build/docker/tke-authz-api/Dockerfile | 23 + build/docker/tke-authz-controller/Dockerfile | 23 + build/lib/gen.mk | 4 +- build/script/openapi.sh | 1 + cmd/tke-authz-api/apiserver.go | 37 + cmd/tke-authz-api/app/app.go | 62 + cmd/tke-authz-api/app/config/config.go | 167 + cmd/tke-authz-api/app/options/authz.go | 61 + cmd/tke-authz-api/app/options/options.go | 121 + cmd/tke-authz-api/app/run.go | 36 + cmd/tke-authz-api/app/server.go | 103 + cmd/tke-authz-controller/app/app.go | 61 + cmd/tke-authz-controller/app/authz.go | 73 + cmd/tke-authz-controller/app/config/config.go | 104 + cmd/tke-authz-controller/app/context.go | 129 + cmd/tke-authz-controller/app/controller.go | 85 + .../app/options/feature.go | 89 + .../app/options/options.go | 85 + cmd/tke-authz-controller/app/run.go | 115 + .../controller-manager.go | 37 + hack/authz/policies.json | 1041 ++++++ hack/authz/roles.json | 74 + pkg/apiserver/authentication/user.go | 16 + pkg/authz/apiserver/apiserver.go | 145 + pkg/authz/apiserver/install.go | 41 + pkg/authz/constant/constant.go | 11 + ...lticlusterrolebinding_resources_deleter.go | 56 + .../multiclusterrolebinding_controller.go | 389 ++ .../controller/policy/policy_controller.go | 272 ++ .../policyrolecache/policy_role_cache.go | 80 + pkg/authz/controller/role/role_controller.go | 325 ++ pkg/authz/provider/interface.go | 97 + pkg/authz/provider/provider.go | 80 + .../registry/configmap/storage/storage.go | 82 + pkg/authz/registry/configmap/strategy.go | 109 + pkg/authz/registry/configmap/validation.go | 45 + .../storage/storage.go | 239 ++ .../multiclusterrolebinding/strategy.go | 261 ++ .../multiclusterrolebinding/validation.go | 86 + pkg/authz/registry/policy/storage/storage.go | 100 + pkg/authz/registry/policy/strategy.go | 189 + pkg/authz/registry/policy/validation.go | 70 + pkg/authz/registry/rest/rest.go | 81 + pkg/authz/registry/role/storage/storage.go | 222 ++ pkg/authz/registry/role/strategy.go | 194 + pkg/authz/registry/role/validation.go | 75 + pkg/util/jwt/parse.go | 19 + .../leaderelection/resourcelock/authz_lock.go | 103 + .../resourcelock/resourcelock.go | 12 + pkg/util/x509/parse.go | 21 + 126 files changed, 16380 insertions(+), 2 deletions(-) create mode 100644 api/authz/doc.go create mode 100644 api/authz/install/doc.go create mode 100644 api/authz/install/install.go create mode 100644 api/authz/register.go create mode 100644 api/authz/types.go create mode 100644 api/authz/v1/doc.go create mode 100644 api/authz/v1/generated.pb.go create mode 100644 api/authz/v1/generated.proto create mode 100644 api/authz/v1/register.go create mode 100644 api/authz/v1/types.go create mode 100644 api/authz/v1/types_swagger_doc_generated.go create mode 100644 api/authz/v1/zz_generated.conversion.go create mode 100644 api/authz/v1/zz_generated.deepcopy.go create mode 100644 api/authz/v1/zz_generated.defaults.go create mode 100644 api/authz/zz_generated.deepcopy.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/authz_client.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/configmap.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/doc.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/fake/doc.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_authz_client.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_configmap.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_multiclusterrolebinding.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_policy.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_role.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/generated_expansion.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/multiclusterrolebinding.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/policy.go create mode 100644 api/client/clientset/internalversion/typed/authz/internalversion/role.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/authz_client.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/configmap.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/doc.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/fake/doc.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/fake/fake_authz_client.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/fake/fake_configmap.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/fake/fake_multiclusterrolebinding.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/fake/fake_policy.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/fake/fake_role.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/generated_expansion.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/multiclusterrolebinding.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/policy.go create mode 100644 api/client/clientset/versioned/typed/authz/v1/role.go create mode 100644 api/client/informers/externalversions/authz/interface.go create mode 100644 api/client/informers/externalversions/authz/v1/configmap.go create mode 100644 api/client/informers/externalversions/authz/v1/interface.go create mode 100644 api/client/informers/externalversions/authz/v1/multiclusterrolebinding.go create mode 100644 api/client/informers/externalversions/authz/v1/policy.go create mode 100644 api/client/informers/externalversions/authz/v1/role.go create mode 100644 api/client/informers/internalversion/authz/interface.go create mode 100644 api/client/informers/internalversion/authz/internalversion/configmap.go create mode 100644 api/client/informers/internalversion/authz/internalversion/interface.go create mode 100644 api/client/informers/internalversion/authz/internalversion/multiclusterrolebinding.go create mode 100644 api/client/informers/internalversion/authz/internalversion/policy.go create mode 100644 api/client/informers/internalversion/authz/internalversion/role.go create mode 100644 api/client/listers/authz/internalversion/configmap.go create mode 100644 api/client/listers/authz/internalversion/expansion_generated.go create mode 100644 api/client/listers/authz/internalversion/multiclusterrolebinding.go create mode 100644 api/client/listers/authz/internalversion/policy.go create mode 100644 api/client/listers/authz/internalversion/role.go create mode 100644 api/client/listers/authz/v1/configmap.go create mode 100644 api/client/listers/authz/v1/expansion_generated.go create mode 100644 api/client/listers/authz/v1/multiclusterrolebinding.go create mode 100644 api/client/listers/authz/v1/policy.go create mode 100644 api/client/listers/authz/v1/role.go create mode 100644 build/docker/tke-authz-api/Dockerfile create mode 100644 build/docker/tke-authz-controller/Dockerfile create mode 100644 cmd/tke-authz-api/apiserver.go create mode 100644 cmd/tke-authz-api/app/app.go create mode 100644 cmd/tke-authz-api/app/config/config.go create mode 100644 cmd/tke-authz-api/app/options/authz.go create mode 100644 cmd/tke-authz-api/app/options/options.go create mode 100644 cmd/tke-authz-api/app/run.go create mode 100644 cmd/tke-authz-api/app/server.go create mode 100644 cmd/tke-authz-controller/app/app.go create mode 100644 cmd/tke-authz-controller/app/authz.go create mode 100644 cmd/tke-authz-controller/app/config/config.go create mode 100644 cmd/tke-authz-controller/app/context.go create mode 100644 cmd/tke-authz-controller/app/controller.go create mode 100644 cmd/tke-authz-controller/app/options/feature.go create mode 100644 cmd/tke-authz-controller/app/options/options.go create mode 100644 cmd/tke-authz-controller/app/run.go create mode 100644 cmd/tke-authz-controller/controller-manager.go create mode 100644 hack/authz/policies.json create mode 100644 hack/authz/roles.json create mode 100644 pkg/authz/apiserver/apiserver.go create mode 100644 pkg/authz/apiserver/install.go create mode 100644 pkg/authz/constant/constant.go create mode 100644 pkg/authz/controller/multiclusterrolebinding/deletion/multiclusterrolebinding_resources_deleter.go create mode 100644 pkg/authz/controller/multiclusterrolebinding/multiclusterrolebinding_controller.go create mode 100644 pkg/authz/controller/policy/policy_controller.go create mode 100644 pkg/authz/controller/policyrolecache/policy_role_cache.go create mode 100644 pkg/authz/controller/role/role_controller.go create mode 100644 pkg/authz/provider/interface.go create mode 100644 pkg/authz/provider/provider.go create mode 100644 pkg/authz/registry/configmap/storage/storage.go create mode 100644 pkg/authz/registry/configmap/strategy.go create mode 100644 pkg/authz/registry/configmap/validation.go create mode 100644 pkg/authz/registry/multiclusterrolebinding/storage/storage.go create mode 100644 pkg/authz/registry/multiclusterrolebinding/strategy.go create mode 100644 pkg/authz/registry/multiclusterrolebinding/validation.go create mode 100644 pkg/authz/registry/policy/storage/storage.go create mode 100644 pkg/authz/registry/policy/strategy.go create mode 100644 pkg/authz/registry/policy/validation.go create mode 100644 pkg/authz/registry/rest/rest.go create mode 100644 pkg/authz/registry/role/storage/storage.go create mode 100644 pkg/authz/registry/role/strategy.go create mode 100644 pkg/authz/registry/role/validation.go create mode 100644 pkg/util/jwt/parse.go create mode 100644 pkg/util/leaderelection/resourcelock/authz_lock.go create mode 100644 pkg/util/x509/parse.go diff --git a/api/authz/doc.go b/api/authz/doc.go new file mode 100644 index 000000000..9182e6080 --- /dev/null +++ b/api/authz/doc.go @@ -0,0 +1,23 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// +k8s:deepcopy-gen=package +// +groupName=authz.tkestack.io + +// Package application is the internal version of the API. +package authz // import "tkestack.io/tke/api/authz" diff --git a/api/authz/install/doc.go b/api/authz/install/doc.go new file mode 100644 index 000000000..43fd7d1dc --- /dev/null +++ b/api/authz/install/doc.go @@ -0,0 +1,19 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package install // import "tkestack.io/tke/api/authz/install" diff --git a/api/authz/install/install.go b/api/authz/install/install.go new file mode 100644 index 000000000..93456faf2 --- /dev/null +++ b/api/authz/install/install.go @@ -0,0 +1,37 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package install + +import ( + "k8s.io/apimachinery/pkg/runtime" + runtimeutil "k8s.io/apimachinery/pkg/util/runtime" + "tkestack.io/tke/api/authz" + v1 "tkestack.io/tke/api/authz/v1" +) + +func init() { + Install(authz.Scheme) +} + +// Install registers the API group and adds types to a scheme +func Install(scheme *runtime.Scheme) { + runtimeutil.Must(authz.AddToScheme(scheme)) + runtimeutil.Must(v1.AddToScheme(scheme)) + runtimeutil.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion)) +} diff --git a/api/authz/register.go b/api/authz/register.go new file mode 100644 index 000000000..1f7f4ec48 --- /dev/null +++ b/api/authz/register.go @@ -0,0 +1,74 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package authz + +import ( + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/runtime/serializer" +) + +var ( + // Scheme is the default instance of runtime.Scheme to which types in the TKE API are already registered. + Scheme = runtime.NewScheme() + // Codecs provides access to encoding and decoding for the scheme + Codecs = serializer.NewCodecFactory(Scheme) + // ParameterCodec handles versioning of objects that are converted to query parameters. + ParameterCodec = runtime.NewParameterCodec(Scheme) +) + +// GroupName is group name used to register these schema +const GroupName = "authz.tkestack.io" + +// SchemeGroupVersion is group version used to register these objects +var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: runtime.APIVersionInternal} + +// Kind takes an unqualified kind and returns back a Group qualified GroupKind +func Kind(kind string) schema.GroupKind { + return SchemeGroupVersion.WithKind(kind).GroupKind() +} + +// Resource takes an unqualified resource and returns back a Group qualified +// GroupResource +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} + +var ( + // SchemeBuilder collects functions that add things to a scheme. + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + // AddToScheme applies all the stored functions to the scheme. + AddToScheme = SchemeBuilder.AddToScheme +) + +// addKnownTypes adds the list of known types to the given scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &Policy{}, + &PolicyList{}, + &Role{}, + &RoleList{}, + &MultiClusterRoleBinding{}, + &MultiClusterRoleBindingList{}, + &ConfigMap{}, + &ConfigMapList{}, + ) + + return nil +} diff --git a/api/authz/types.go b/api/authz/types.go new file mode 100644 index 000000000..788c8c5ec --- /dev/null +++ b/api/authz/types.go @@ -0,0 +1,195 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package authz + +import ( + rbacv1 "k8s.io/api/rbac/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +type Scope string + +const ( + PlatformScope Scope = "Platform" + MultiClusterScope Scope = "MultiCluster" + BusinessScope Scope = "Business" +) + +// +genclient +// +genclient:skipVerbs=deleteCollection +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +type Policy struct { + metav1.TypeMeta + // +optional + metav1.ObjectMeta + + DisplayName string + + // +optional + TenantID string + + // Username is Creator + // +optional + Username string + + // +optional + Description string + + Scope Scope + + Rules []rbacv1.PolicyRule +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// PolicyList is the whole list of all policies. +type PolicyList struct { + metav1.TypeMeta + // +optional + metav1.ListMeta + // List of policies + Items []Policy +} + +// +genclient +// +genclient:skipVerbs=deleteCollection +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Role is a collection with multiple policies. +type Role struct { + metav1.TypeMeta + metav1.ObjectMeta + + DisplayName string + + // +optional + TenantID string + + // Username is Creator + // +optional + Username string + + // +optional + Description string + + Scope Scope + + // policyNamespace/policyName + Policies []string +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// RoleList is the whole list of policy. +type RoleList struct { + metav1.TypeMeta + metav1.ListMeta + // List of rules. + Items []Role +} + +// +genclient +// +genclient:skipVerbs=deleteCollection +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +type MultiClusterRoleBinding struct { + metav1.TypeMeta + metav1.ObjectMeta + Spec MultiClusterRoleBindingSpec + Status MultiClusterRoleBindingStatus +} + +type MultiClusterRoleBindingSpec struct { + // +optional + TenantID string + // +optional + Username string + // roleNamespace/roleName + RoleName string + Clusters []string +} + +type MultiClusterRoleBindingStatus struct { + // +optional + Phase BindingPhase +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +type MultiClusterRoleBindingList struct { + metav1.TypeMeta + metav1.ListMeta + // List of rules. + Items []MultiClusterRoleBinding +} + +type BindingPhase string + +const ( + BindingActive BindingPhase = "Active" + BindingTerminating BindingPhase = "Terminating" +) + +type FinalizerName string + +const ( + PolicyFinalize FinalizerName = "policy" + RoleFinalize FinalizerName = "role" + MultiClusterRoleBindingFinalize FinalizerName = "rolebinding" +) + +// +genclient +// +genclient:nonNamespaced +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ConfigMap holds configuration data for tke to consume. +type ConfigMap struct { + metav1.TypeMeta + // +optional + metav1.ObjectMeta + + // Data contains the configuration data. + // Each key must consist of alphanumeric characters, '-', '_' or '.'. + // Values with non-UTF-8 byte sequences must use the BinaryData field. + // The keys stored in Data must not overlap with the keys in + // the BinaryData field, this is enforced during validation process. + // +optional + Data map[string]string + + // BinaryData contains the binary data. + // Each key must consist of alphanumeric characters, '-', '_' or '.'. + // BinaryData can contain byte sequences that are not in the UTF-8 range. + // The keys stored in BinaryData must not overlap with the ones in + // the Data field, this is enforced during validation process. + // +optional + BinaryData map[string][]byte +} + +// +genclient:nonNamespaced +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ConfigMapList is a resource containing a list of ConfigMap objects. +type ConfigMapList struct { + metav1.TypeMeta + // +optional + metav1.ListMeta + // Items is the list of ConfigMaps. + Items []ConfigMap +} diff --git a/api/authz/v1/doc.go b/api/authz/v1/doc.go new file mode 100644 index 000000000..82aeaa11d --- /dev/null +++ b/api/authz/v1/doc.go @@ -0,0 +1,26 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// +k8s:deepcopy-gen=package +// +k8s:conversion-gen=tkestack.io/tke/api/authz +// +k8s:defaulter-gen=TypeMeta +// +k8s:openapi-gen=true + +// Package v1 is the v1 version of the API. +// +groupName=authz.tkestack.io +package v1 // import "tkestack.io/tke/api/authz/v1" diff --git a/api/authz/v1/generated.pb.go b/api/authz/v1/generated.pb.go new file mode 100644 index 000000000..f5ec8a184 --- /dev/null +++ b/api/authz/v1/generated.pb.go @@ -0,0 +1,3188 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tkestack.io/tke/api/authz/v1/generated.proto + +package v1 + +import ( + fmt "fmt" + + io "io" + + proto "github.com/gogo/protobuf/proto" + github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys" + v11 "k8s.io/api/rbac/v1" + + math "math" + math_bits "math/bits" + reflect "reflect" + strings "strings" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +func (m *ConfigMap) Reset() { *m = ConfigMap{} } +func (*ConfigMap) ProtoMessage() {} +func (*ConfigMap) Descriptor() ([]byte, []int) { + return fileDescriptor_c89ce64fe9f23edd, []int{0} +} +func (m *ConfigMap) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ConfigMap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil +} +func (m *ConfigMap) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigMap.Merge(m, src) +} +func (m *ConfigMap) XXX_Size() int { + return m.Size() +} +func (m *ConfigMap) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigMap.DiscardUnknown(m) +} + +var xxx_messageInfo_ConfigMap proto.InternalMessageInfo + +func (m *ConfigMapList) Reset() { *m = ConfigMapList{} } +func (*ConfigMapList) ProtoMessage() {} +func (*ConfigMapList) Descriptor() ([]byte, []int) { + return fileDescriptor_c89ce64fe9f23edd, []int{1} +} +func (m *ConfigMapList) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ConfigMapList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil +} +func (m *ConfigMapList) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigMapList.Merge(m, src) +} +func (m *ConfigMapList) XXX_Size() int { + return m.Size() +} +func (m *ConfigMapList) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigMapList.DiscardUnknown(m) +} + +var xxx_messageInfo_ConfigMapList proto.InternalMessageInfo + +func (m *MultiClusterRoleBinding) Reset() { *m = MultiClusterRoleBinding{} } +func (*MultiClusterRoleBinding) ProtoMessage() {} +func (*MultiClusterRoleBinding) Descriptor() ([]byte, []int) { + return fileDescriptor_c89ce64fe9f23edd, []int{2} +} +func (m *MultiClusterRoleBinding) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MultiClusterRoleBinding) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil +} +func (m *MultiClusterRoleBinding) XXX_Merge(src proto.Message) { + xxx_messageInfo_MultiClusterRoleBinding.Merge(m, src) +} +func (m *MultiClusterRoleBinding) XXX_Size() int { + return m.Size() +} +func (m *MultiClusterRoleBinding) XXX_DiscardUnknown() { + xxx_messageInfo_MultiClusterRoleBinding.DiscardUnknown(m) +} + +var xxx_messageInfo_MultiClusterRoleBinding proto.InternalMessageInfo + +func (m *MultiClusterRoleBindingList) Reset() { *m = MultiClusterRoleBindingList{} } +func (*MultiClusterRoleBindingList) ProtoMessage() {} +func (*MultiClusterRoleBindingList) Descriptor() ([]byte, []int) { + return fileDescriptor_c89ce64fe9f23edd, []int{3} +} +func (m *MultiClusterRoleBindingList) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MultiClusterRoleBindingList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil +} +func (m *MultiClusterRoleBindingList) XXX_Merge(src proto.Message) { + xxx_messageInfo_MultiClusterRoleBindingList.Merge(m, src) +} +func (m *MultiClusterRoleBindingList) XXX_Size() int { + return m.Size() +} +func (m *MultiClusterRoleBindingList) XXX_DiscardUnknown() { + xxx_messageInfo_MultiClusterRoleBindingList.DiscardUnknown(m) +} + +var xxx_messageInfo_MultiClusterRoleBindingList proto.InternalMessageInfo + +func (m *MultiClusterRoleBindingSpec) Reset() { *m = MultiClusterRoleBindingSpec{} } +func (*MultiClusterRoleBindingSpec) ProtoMessage() {} +func (*MultiClusterRoleBindingSpec) Descriptor() ([]byte, []int) { + return fileDescriptor_c89ce64fe9f23edd, []int{4} +} +func (m *MultiClusterRoleBindingSpec) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MultiClusterRoleBindingSpec) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil +} +func (m *MultiClusterRoleBindingSpec) XXX_Merge(src proto.Message) { + xxx_messageInfo_MultiClusterRoleBindingSpec.Merge(m, src) +} +func (m *MultiClusterRoleBindingSpec) XXX_Size() int { + return m.Size() +} +func (m *MultiClusterRoleBindingSpec) XXX_DiscardUnknown() { + xxx_messageInfo_MultiClusterRoleBindingSpec.DiscardUnknown(m) +} + +var xxx_messageInfo_MultiClusterRoleBindingSpec proto.InternalMessageInfo + +func (m *MultiClusterRoleBindingStatus) Reset() { *m = MultiClusterRoleBindingStatus{} } +func (*MultiClusterRoleBindingStatus) ProtoMessage() {} +func (*MultiClusterRoleBindingStatus) Descriptor() ([]byte, []int) { + return fileDescriptor_c89ce64fe9f23edd, []int{5} +} +func (m *MultiClusterRoleBindingStatus) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MultiClusterRoleBindingStatus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil +} +func (m *MultiClusterRoleBindingStatus) XXX_Merge(src proto.Message) { + xxx_messageInfo_MultiClusterRoleBindingStatus.Merge(m, src) +} +func (m *MultiClusterRoleBindingStatus) XXX_Size() int { + return m.Size() +} +func (m *MultiClusterRoleBindingStatus) XXX_DiscardUnknown() { + xxx_messageInfo_MultiClusterRoleBindingStatus.DiscardUnknown(m) +} + +var xxx_messageInfo_MultiClusterRoleBindingStatus proto.InternalMessageInfo + +func (m *Policy) Reset() { *m = Policy{} } +func (*Policy) ProtoMessage() {} +func (*Policy) Descriptor() ([]byte, []int) { + return fileDescriptor_c89ce64fe9f23edd, []int{6} +} +func (m *Policy) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Policy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil +} +func (m *Policy) XXX_Merge(src proto.Message) { + xxx_messageInfo_Policy.Merge(m, src) +} +func (m *Policy) XXX_Size() int { + return m.Size() +} +func (m *Policy) XXX_DiscardUnknown() { + xxx_messageInfo_Policy.DiscardUnknown(m) +} + +var xxx_messageInfo_Policy proto.InternalMessageInfo + +func (m *PolicyList) Reset() { *m = PolicyList{} } +func (*PolicyList) ProtoMessage() {} +func (*PolicyList) Descriptor() ([]byte, []int) { + return fileDescriptor_c89ce64fe9f23edd, []int{7} +} +func (m *PolicyList) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PolicyList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil +} +func (m *PolicyList) XXX_Merge(src proto.Message) { + xxx_messageInfo_PolicyList.Merge(m, src) +} +func (m *PolicyList) XXX_Size() int { + return m.Size() +} +func (m *PolicyList) XXX_DiscardUnknown() { + xxx_messageInfo_PolicyList.DiscardUnknown(m) +} + +var xxx_messageInfo_PolicyList proto.InternalMessageInfo + +func (m *Role) Reset() { *m = Role{} } +func (*Role) ProtoMessage() {} +func (*Role) Descriptor() ([]byte, []int) { + return fileDescriptor_c89ce64fe9f23edd, []int{8} +} +func (m *Role) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Role) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil +} +func (m *Role) XXX_Merge(src proto.Message) { + xxx_messageInfo_Role.Merge(m, src) +} +func (m *Role) XXX_Size() int { + return m.Size() +} +func (m *Role) XXX_DiscardUnknown() { + xxx_messageInfo_Role.DiscardUnknown(m) +} + +var xxx_messageInfo_Role proto.InternalMessageInfo + +func (m *RoleList) Reset() { *m = RoleList{} } +func (*RoleList) ProtoMessage() {} +func (*RoleList) Descriptor() ([]byte, []int) { + return fileDescriptor_c89ce64fe9f23edd, []int{9} +} +func (m *RoleList) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *RoleList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil +} +func (m *RoleList) XXX_Merge(src proto.Message) { + xxx_messageInfo_RoleList.Merge(m, src) +} +func (m *RoleList) XXX_Size() int { + return m.Size() +} +func (m *RoleList) XXX_DiscardUnknown() { + xxx_messageInfo_RoleList.DiscardUnknown(m) +} + +var xxx_messageInfo_RoleList proto.InternalMessageInfo + +func init() { + proto.RegisterType((*ConfigMap)(nil), "tkestack.io.tke.api.authz.v1.ConfigMap") + proto.RegisterMapType((map[string][]byte)(nil), "tkestack.io.tke.api.authz.v1.ConfigMap.BinaryDataEntry") + proto.RegisterMapType((map[string]string)(nil), "tkestack.io.tke.api.authz.v1.ConfigMap.DataEntry") + proto.RegisterType((*ConfigMapList)(nil), "tkestack.io.tke.api.authz.v1.ConfigMapList") + proto.RegisterType((*MultiClusterRoleBinding)(nil), "tkestack.io.tke.api.authz.v1.MultiClusterRoleBinding") + proto.RegisterType((*MultiClusterRoleBindingList)(nil), "tkestack.io.tke.api.authz.v1.MultiClusterRoleBindingList") + proto.RegisterType((*MultiClusterRoleBindingSpec)(nil), "tkestack.io.tke.api.authz.v1.MultiClusterRoleBindingSpec") + proto.RegisterType((*MultiClusterRoleBindingStatus)(nil), "tkestack.io.tke.api.authz.v1.MultiClusterRoleBindingStatus") + proto.RegisterType((*Policy)(nil), "tkestack.io.tke.api.authz.v1.Policy") + proto.RegisterType((*PolicyList)(nil), "tkestack.io.tke.api.authz.v1.PolicyList") + proto.RegisterType((*Role)(nil), "tkestack.io.tke.api.authz.v1.Role") + proto.RegisterType((*RoleList)(nil), "tkestack.io.tke.api.authz.v1.RoleList") +} + +func init() { + proto.RegisterFile("tkestack.io/tke/api/authz/v1/generated.proto", fileDescriptor_c89ce64fe9f23edd) +} + +var fileDescriptor_c89ce64fe9f23edd = []byte{ + // 865 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x55, 0x41, 0x6f, 0xe3, 0x44, + 0x14, 0x8e, 0xe3, 0xa4, 0x24, 0x93, 0x2c, 0xac, 0x0c, 0x02, 0x2b, 0xb0, 0x6e, 0x65, 0x21, 0x91, + 0x43, 0x19, 0x93, 0xc2, 0xb2, 0x0b, 0x88, 0x8b, 0x5b, 0x84, 0x2a, 0x6d, 0x97, 0x6a, 0xba, 0x5c, + 0x16, 0x0e, 0x4c, 0x9c, 0x59, 0x67, 0xb0, 0x63, 0x5b, 0x9e, 0x71, 0xa4, 0x70, 0xe2, 0xcc, 0x89, + 0x7f, 0xc1, 0x99, 0x03, 0x27, 0xc4, 0xbd, 0xc7, 0xe5, 0xc4, 0x9e, 0x2a, 0x1a, 0xfe, 0xc5, 0x9e, + 0xd0, 0x8c, 0x27, 0xb6, 0xd3, 0x6d, 0xd2, 0x52, 0x89, 0x9c, 0xf6, 0xe6, 0x79, 0xf3, 0x7d, 0xdf, + 0xbc, 0x79, 0xef, 0x7b, 0x63, 0xb0, 0xcb, 0x03, 0xc2, 0x38, 0xf6, 0x02, 0x48, 0x63, 0x87, 0x07, + 0xc4, 0xc1, 0x09, 0x75, 0x70, 0xc6, 0xc7, 0x3f, 0x38, 0xd3, 0x81, 0xe3, 0x93, 0x88, 0xa4, 0x98, + 0x93, 0x11, 0x4c, 0xd2, 0x98, 0xc7, 0xc6, 0x3b, 0x15, 0x34, 0xe4, 0x01, 0x81, 0x38, 0xa1, 0x50, + 0xa2, 0xe1, 0x74, 0xd0, 0x7b, 0xdf, 0xa7, 0x7c, 0x9c, 0x0d, 0xa1, 0x17, 0x4f, 0x1c, 0x3f, 0xf6, + 0x63, 0x47, 0x92, 0x86, 0xd9, 0x13, 0xb9, 0x92, 0x0b, 0xf9, 0x95, 0x8b, 0xf5, 0xec, 0xe0, 0x3e, + 0x13, 0xa7, 0x8a, 0x13, 0xd3, 0x21, 0xf6, 0x2e, 0x39, 0xb0, 0xf7, 0x51, 0x89, 0x99, 0x60, 0x6f, + 0x4c, 0x23, 0x92, 0xce, 0x9c, 0x24, 0xf0, 0x45, 0x80, 0x39, 0x13, 0xc2, 0xf1, 0x65, 0x2c, 0x67, + 0x15, 0x2b, 0xcd, 0x22, 0x4e, 0x27, 0xe4, 0x05, 0xc2, 0xc7, 0x57, 0x11, 0x98, 0x37, 0x26, 0x13, + 0x7c, 0x91, 0x67, 0xff, 0xa2, 0x83, 0xf6, 0x7e, 0x1c, 0x3d, 0xa1, 0xfe, 0x11, 0x4e, 0x8c, 0xef, + 0x40, 0x4b, 0x64, 0x34, 0xc2, 0x1c, 0x9b, 0xda, 0x8e, 0xd6, 0xef, 0xec, 0x7d, 0x00, 0x73, 0x61, + 0x58, 0x15, 0x86, 0x49, 0xe0, 0x8b, 0x00, 0x83, 0x02, 0x0d, 0xa7, 0x03, 0xf8, 0xd5, 0xf0, 0x7b, + 0xe2, 0xf1, 0x23, 0xc2, 0xb1, 0x6b, 0x9c, 0x9e, 0x6d, 0xd7, 0xe6, 0x67, 0xdb, 0xa0, 0x8c, 0xa1, + 0x42, 0xd5, 0x38, 0x01, 0x0d, 0xa9, 0x5e, 0xdf, 0xd1, 0xfb, 0x9d, 0xbd, 0x01, 0x5c, 0xd7, 0x0e, + 0x58, 0x24, 0x06, 0x0f, 0x30, 0xc7, 0x5f, 0x44, 0x3c, 0x9d, 0xb9, 0x5d, 0x25, 0xdf, 0x10, 0x21, + 0x24, 0xc5, 0x8c, 0x00, 0x80, 0x21, 0x8d, 0x70, 0x3a, 0x13, 0x31, 0x53, 0x97, 0xd2, 0xf7, 0xae, + 0x2b, 0xed, 0x16, 0xcc, 0xfc, 0x80, 0x22, 0xff, 0x72, 0x03, 0x55, 0xe4, 0x7b, 0xf7, 0x40, 0xbb, + 0x00, 0x1b, 0xb7, 0x81, 0x1e, 0x90, 0x99, 0xac, 0x55, 0x1b, 0x89, 0x4f, 0xe3, 0x0d, 0xd0, 0x9c, + 0xe2, 0x30, 0x23, 0x66, 0x5d, 0xc6, 0xf2, 0xc5, 0xa7, 0xf5, 0xfb, 0x5a, 0xef, 0x73, 0xf0, 0xda, + 0x85, 0xb3, 0xae, 0xa2, 0x77, 0x2b, 0x74, 0xfb, 0x77, 0x0d, 0xdc, 0x2a, 0xb2, 0x7e, 0x40, 0x19, + 0x37, 0xbe, 0x7d, 0xa1, 0x5b, 0xf0, 0x7a, 0xdd, 0x12, 0x6c, 0xd9, 0xab, 0xdb, 0xea, 0xae, 0xad, + 0x45, 0xa4, 0xd2, 0xa9, 0x07, 0xa0, 0x49, 0x39, 0x99, 0x30, 0xd5, 0xaa, 0xf7, 0xae, 0x59, 0x4f, + 0xf7, 0x96, 0xd2, 0x6c, 0x1e, 0x0a, 0x36, 0xca, 0x45, 0xec, 0x3f, 0xea, 0xe0, 0xad, 0xa3, 0x2c, + 0xe4, 0x74, 0x3f, 0xcc, 0x18, 0x27, 0x29, 0x8a, 0x43, 0xe2, 0xd2, 0x68, 0x44, 0x23, 0x7f, 0x03, + 0xae, 0xfb, 0x06, 0x34, 0x58, 0x42, 0x3c, 0x59, 0xd4, 0xce, 0xde, 0x27, 0xeb, 0xaf, 0xb2, 0x22, + 0xcd, 0x93, 0x84, 0x78, 0xa5, 0xfb, 0xc4, 0x0a, 0x49, 0x51, 0xc3, 0x03, 0x5b, 0x8c, 0x63, 0x9e, + 0x31, 0x53, 0x97, 0xf2, 0x9f, 0xdd, 0x4c, 0x5e, 0x4a, 0xb8, 0xaf, 0xaa, 0x03, 0xb6, 0xf2, 0x35, + 0x52, 0xd2, 0xf6, 0x5f, 0x1a, 0x78, 0x7b, 0x05, 0x73, 0x03, 0x5e, 0x78, 0xbc, 0xec, 0x85, 0xbb, + 0x37, 0xba, 0xe1, 0x0a, 0x67, 0xfc, 0xb9, 0xfa, 0x66, 0xa2, 0xc8, 0xc6, 0x2e, 0x68, 0x71, 0x12, + 0xe1, 0x88, 0x1f, 0x1e, 0xe4, 0x83, 0x52, 0x66, 0xfa, 0x48, 0xc5, 0x51, 0x81, 0x10, 0xe8, 0x8c, + 0x91, 0x34, 0xc2, 0x13, 0x35, 0x81, 0x25, 0xfa, 0x6b, 0x15, 0x47, 0x05, 0x42, 0xa0, 0xd3, 0x38, + 0x24, 0x0f, 0x05, 0x5a, 0x5f, 0x46, 0x23, 0x15, 0x47, 0x05, 0xc2, 0xe8, 0x83, 0x96, 0x97, 0xe7, + 0xc8, 0xcc, 0xc6, 0x8e, 0xde, 0x6f, 0xbb, 0x5d, 0x81, 0x54, 0x79, 0x33, 0x54, 0xec, 0xda, 0x8f, + 0xc0, 0x9d, 0xb5, 0x6d, 0x36, 0x3e, 0x04, 0xcd, 0x64, 0x8c, 0x19, 0x51, 0x37, 0xba, 0xb3, 0xa8, + 0xcc, 0xb1, 0x08, 0x3e, 0x3f, 0xdb, 0xee, 0x2a, 0xb8, 0x5c, 0xa3, 0x1c, 0x2b, 0xde, 0xea, 0xad, + 0xe3, 0x38, 0xa4, 0xde, 0x6c, 0x03, 0x23, 0x73, 0x17, 0x74, 0x46, 0x94, 0x25, 0x21, 0x9e, 0x3d, + 0x2c, 0x6b, 0xf9, 0xba, 0xa2, 0x74, 0x0e, 0xca, 0x2d, 0x54, 0xc5, 0x2d, 0x75, 0x4b, 0xff, 0x4f, + 0xdd, 0x6a, 0x5c, 0xd9, 0x2d, 0x91, 0x12, 0x61, 0x5e, 0x4a, 0x13, 0x4e, 0xe3, 0xc8, 0x6c, 0x5e, + 0x48, 0xa9, 0xdc, 0x42, 0x55, 0x9c, 0xb1, 0x0b, 0x9a, 0xcc, 0x8b, 0x13, 0x62, 0x6e, 0x49, 0xc2, + 0x9b, 0x8b, 0x5a, 0x9f, 0x88, 0xe0, 0xf3, 0xc5, 0x07, 0xca, 0x41, 0xc6, 0x3e, 0x68, 0xa6, 0x59, + 0x48, 0x98, 0xf9, 0x8a, 0xb4, 0xba, 0x55, 0x29, 0x2b, 0x14, 0xff, 0x78, 0x51, 0xc4, 0xbc, 0x09, + 0x28, 0x0b, 0x49, 0xe9, 0x69, 0xb1, 0x62, 0x28, 0xe7, 0xda, 0xbf, 0x69, 0x00, 0xe4, 0xa0, 0x0d, + 0x0c, 0xe7, 0xe1, 0xf2, 0x70, 0xbe, 0xbb, 0x7e, 0x38, 0xf3, 0xb4, 0x56, 0xcc, 0xe2, 0x4f, 0x3a, + 0x68, 0x08, 0xb3, 0xbe, 0xf4, 0xd7, 0xff, 0xe6, 0xaf, 0x3e, 0x68, 0x25, 0xa2, 0x05, 0x54, 0x59, + 0x4c, 0x3d, 0x22, 0xc7, 0x2a, 0x86, 0x8a, 0x5d, 0xfb, 0x57, 0x0d, 0xc8, 0x57, 0x68, 0x03, 0x16, + 0xfa, 0x72, 0xd9, 0x42, 0xf6, 0x7a, 0x0b, 0xc9, 0xe7, 0xec, 0x52, 0x03, 0xb9, 0xfd, 0xd3, 0x73, + 0xab, 0xf6, 0xf4, 0xdc, 0xaa, 0x3d, 0x3b, 0xb7, 0x6a, 0x3f, 0xce, 0x2d, 0xed, 0x74, 0x6e, 0x69, + 0x4f, 0xe7, 0x96, 0xf6, 0x6c, 0x6e, 0x69, 0x7f, 0xcf, 0x2d, 0xed, 0xe7, 0x7f, 0xac, 0xda, 0xe3, + 0xfa, 0x74, 0xf0, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x9d, 0x2c, 0xcd, 0x21, 0xb7, 0x0b, 0x00, + 0x00, +} + +func (m *ConfigMap) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ConfigMap) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ConfigMap) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.BinaryData) > 0 { + keysForBinaryData := make([]string, 0, len(m.BinaryData)) + for k := range m.BinaryData { + keysForBinaryData = append(keysForBinaryData, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForBinaryData) + for iNdEx := len(keysForBinaryData) - 1; iNdEx >= 0; iNdEx-- { + v := m.BinaryData[string(keysForBinaryData[iNdEx])] + baseI := i + if v != nil { + i -= len(v) + copy(dAtA[i:], v) + i = encodeVarintGenerated(dAtA, i, uint64(len(v))) + i-- + dAtA[i] = 0x12 + } + i -= len(keysForBinaryData[iNdEx]) + copy(dAtA[i:], keysForBinaryData[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(keysForBinaryData[iNdEx]))) + i-- + dAtA[i] = 0xa + i = encodeVarintGenerated(dAtA, i, uint64(baseI-i)) + i-- + dAtA[i] = 0x1a + } + } + if len(m.Data) > 0 { + keysForData := make([]string, 0, len(m.Data)) + for k := range m.Data { + keysForData = append(keysForData, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForData) + for iNdEx := len(keysForData) - 1; iNdEx >= 0; iNdEx-- { + v := m.Data[string(keysForData[iNdEx])] + baseI := i + i -= len(v) + copy(dAtA[i:], v) + i = encodeVarintGenerated(dAtA, i, uint64(len(v))) + i-- + dAtA[i] = 0x12 + i -= len(keysForData[iNdEx]) + copy(dAtA[i:], keysForData[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(keysForData[iNdEx]))) + i-- + dAtA[i] = 0xa + i = encodeVarintGenerated(dAtA, i, uint64(baseI-i)) + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *ConfigMapList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ConfigMapList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ConfigMapList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *MultiClusterRoleBinding) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MultiClusterRoleBinding) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MultiClusterRoleBinding) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *MultiClusterRoleBindingList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MultiClusterRoleBindingList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MultiClusterRoleBindingList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *MultiClusterRoleBindingSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MultiClusterRoleBindingSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MultiClusterRoleBindingSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Clusters) > 0 { + for iNdEx := len(m.Clusters) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Clusters[iNdEx]) + copy(dAtA[i:], m.Clusters[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Clusters[iNdEx]))) + i-- + dAtA[i] = 0x22 + } + } + i -= len(m.RoleName) + copy(dAtA[i:], m.RoleName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.RoleName))) + i-- + dAtA[i] = 0x1a + i -= len(m.Username) + copy(dAtA[i:], m.Username) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Username))) + i-- + dAtA[i] = 0x12 + i -= len(m.TenantID) + copy(dAtA[i:], m.TenantID) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.TenantID))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *MultiClusterRoleBindingStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MultiClusterRoleBindingStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MultiClusterRoleBindingStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.Phase) + copy(dAtA[i:], m.Phase) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Phase))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *Policy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Policy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Policy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Rules) > 0 { + for iNdEx := len(m.Rules) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Rules[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + } + } + i -= len(m.Scope) + copy(dAtA[i:], m.Scope) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Scope))) + i-- + dAtA[i] = 0x32 + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x2a + i -= len(m.Username) + copy(dAtA[i:], m.Username) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Username))) + i-- + dAtA[i] = 0x22 + i -= len(m.TenantID) + copy(dAtA[i:], m.TenantID) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.TenantID))) + i-- + dAtA[i] = 0x1a + i -= len(m.DisplayName) + copy(dAtA[i:], m.DisplayName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.DisplayName))) + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PolicyList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PolicyList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PolicyList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *Role) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Role) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Role) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Policies) > 0 { + for iNdEx := len(m.Policies) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Policies[iNdEx]) + copy(dAtA[i:], m.Policies[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Policies[iNdEx]))) + i-- + dAtA[i] = 0x3a + } + } + i -= len(m.Scope) + copy(dAtA[i:], m.Scope) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Scope))) + i-- + dAtA[i] = 0x32 + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x2a + i -= len(m.Username) + copy(dAtA[i:], m.Username) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Username))) + i-- + dAtA[i] = 0x22 + i -= len(m.TenantID) + copy(dAtA[i:], m.TenantID) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.TenantID))) + i-- + dAtA[i] = 0x1a + i -= len(m.DisplayName) + copy(dAtA[i:], m.DisplayName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.DisplayName))) + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *RoleList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RoleList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *RoleList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { + offset -= sovGenerated(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *ConfigMap) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Data) > 0 { + for k, v := range m.Data { + _ = k + _ = v + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + len(v) + sovGenerated(uint64(len(v))) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } + if len(m.BinaryData) > 0 { + for k, v := range m.BinaryData { + _ = k + _ = v + l = 0 + if v != nil { + l = 1 + len(v) + sovGenerated(uint64(len(v))) + } + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + l + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } + return n +} + +func (m *ConfigMapList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *MultiClusterRoleBinding) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Status.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *MultiClusterRoleBindingList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *MultiClusterRoleBindingSpec) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.TenantID) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Username) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.RoleName) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Clusters) > 0 { + for _, s := range m.Clusters { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *MultiClusterRoleBindingStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Phase) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *Policy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.DisplayName) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.TenantID) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Username) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Description) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Scope) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Rules) > 0 { + for _, e := range m.Rules { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *PolicyList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *Role) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.DisplayName) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.TenantID) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Username) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Description) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Scope) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Policies) > 0 { + for _, s := range m.Policies { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *RoleList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func sovGenerated(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenerated(x uint64) (n int) { + return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *ConfigMap) String() string { + if this == nil { + return "nil" + } + keysForData := make([]string, 0, len(this.Data)) + for k := range this.Data { + keysForData = append(keysForData, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForData) + mapStringForData := "map[string]string{" + for _, k := range keysForData { + mapStringForData += fmt.Sprintf("%v: %v,", k, this.Data[k]) + } + mapStringForData += "}" + keysForBinaryData := make([]string, 0, len(this.BinaryData)) + for k := range this.BinaryData { + keysForBinaryData = append(keysForBinaryData, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForBinaryData) + mapStringForBinaryData := "map[string][]byte{" + for _, k := range keysForBinaryData { + mapStringForBinaryData += fmt.Sprintf("%v: %v,", k, this.BinaryData[k]) + } + mapStringForBinaryData += "}" + s := strings.Join([]string{`&ConfigMap{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Data:` + mapStringForData + `,`, + `BinaryData:` + mapStringForBinaryData + `,`, + `}`, + }, "") + return s +} +func (this *ConfigMapList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]ConfigMap{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "ConfigMap", "ConfigMap", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&ConfigMapList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *MultiClusterRoleBinding) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&MultiClusterRoleBinding{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "MultiClusterRoleBindingSpec", "MultiClusterRoleBindingSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "MultiClusterRoleBindingStatus", "MultiClusterRoleBindingStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *MultiClusterRoleBindingList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]MultiClusterRoleBinding{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "MultiClusterRoleBinding", "MultiClusterRoleBinding", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&MultiClusterRoleBindingList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *MultiClusterRoleBindingSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&MultiClusterRoleBindingSpec{`, + `TenantID:` + fmt.Sprintf("%v", this.TenantID) + `,`, + `Username:` + fmt.Sprintf("%v", this.Username) + `,`, + `RoleName:` + fmt.Sprintf("%v", this.RoleName) + `,`, + `Clusters:` + fmt.Sprintf("%v", this.Clusters) + `,`, + `}`, + }, "") + return s +} +func (this *MultiClusterRoleBindingStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&MultiClusterRoleBindingStatus{`, + `Phase:` + fmt.Sprintf("%v", this.Phase) + `,`, + `}`, + }, "") + return s +} +func (this *Policy) String() string { + if this == nil { + return "nil" + } + repeatedStringForRules := "[]PolicyRule{" + for _, f := range this.Rules { + repeatedStringForRules += fmt.Sprintf("%v", f) + "," + } + repeatedStringForRules += "}" + s := strings.Join([]string{`&Policy{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `DisplayName:` + fmt.Sprintf("%v", this.DisplayName) + `,`, + `TenantID:` + fmt.Sprintf("%v", this.TenantID) + `,`, + `Username:` + fmt.Sprintf("%v", this.Username) + `,`, + `Description:` + fmt.Sprintf("%v", this.Description) + `,`, + `Scope:` + fmt.Sprintf("%v", this.Scope) + `,`, + `Rules:` + repeatedStringForRules + `,`, + `}`, + }, "") + return s +} +func (this *PolicyList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]Policy{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "Policy", "Policy", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&PolicyList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *Role) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Role{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `DisplayName:` + fmt.Sprintf("%v", this.DisplayName) + `,`, + `TenantID:` + fmt.Sprintf("%v", this.TenantID) + `,`, + `Username:` + fmt.Sprintf("%v", this.Username) + `,`, + `Description:` + fmt.Sprintf("%v", this.Description) + `,`, + `Scope:` + fmt.Sprintf("%v", this.Scope) + `,`, + `Policies:` + fmt.Sprintf("%v", this.Policies) + `,`, + `}`, + }, "") + return s +} +func (this *RoleList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]Role{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "Role", "Role", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&RoleList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *ConfigMap) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ConfigMap: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ConfigMap: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Data == nil { + m.Data = make(map[string]string) + } + var mapkey string + var mapvalue string + for iNdEx < postIndex { + entryPreIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + if fieldNum == 1 { + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLenmapkey |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey < 0 { + return ErrInvalidLengthGenerated + } + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + } else if fieldNum == 2 { + var stringLenmapvalue uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLenmapvalue |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapvalue := int(stringLenmapvalue) + if intStringLenmapvalue < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapvalue := iNdEx + intStringLenmapvalue + if postStringIndexmapvalue < 0 { + return ErrInvalidLengthGenerated + } + if postStringIndexmapvalue > l { + return io.ErrUnexpectedEOF + } + mapvalue = string(dAtA[iNdEx:postStringIndexmapvalue]) + iNdEx = postStringIndexmapvalue + } else { + iNdEx = entryPreIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > postIndex { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + m.Data[mapkey] = mapvalue + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BinaryData", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.BinaryData == nil { + m.BinaryData = make(map[string][]byte) + } + var mapkey string + mapvalue := []byte{} + for iNdEx < postIndex { + entryPreIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + if fieldNum == 1 { + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLenmapkey |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey < 0 { + return ErrInvalidLengthGenerated + } + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + } else if fieldNum == 2 { + var mapbyteLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + mapbyteLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intMapbyteLen := int(mapbyteLen) + if intMapbyteLen < 0 { + return ErrInvalidLengthGenerated + } + postbytesIndex := iNdEx + intMapbyteLen + if postbytesIndex < 0 { + return ErrInvalidLengthGenerated + } + if postbytesIndex > l { + return io.ErrUnexpectedEOF + } + mapvalue = make([]byte, mapbyteLen) + copy(mapvalue, dAtA[iNdEx:postbytesIndex]) + iNdEx = postbytesIndex + } else { + iNdEx = entryPreIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > postIndex { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + m.BinaryData[mapkey] = mapvalue + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ConfigMapList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ConfigMapList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ConfigMapList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, ConfigMap{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MultiClusterRoleBinding) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MultiClusterRoleBinding: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MultiClusterRoleBinding: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MultiClusterRoleBindingList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MultiClusterRoleBindingList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MultiClusterRoleBindingList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, MultiClusterRoleBinding{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MultiClusterRoleBindingSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MultiClusterRoleBindingSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MultiClusterRoleBindingSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TenantID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TenantID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Username", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Username = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RoleName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RoleName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Clusters", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Clusters = append(m.Clusters, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MultiClusterRoleBindingStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MultiClusterRoleBindingStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MultiClusterRoleBindingStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Phase", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Phase = BindingPhase(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Policy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Policy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Policy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisplayName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DisplayName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TenantID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TenantID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Username", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Username = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Scope", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Scope = Scope(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Rules", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Rules = append(m.Rules, v11.PolicyRule{}) + if err := m.Rules[len(m.Rules)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PolicyList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PolicyList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PolicyList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, Policy{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Role) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Role: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Role: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisplayName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DisplayName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TenantID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TenantID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Username", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Username = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Scope", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Scope = Scope(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Policies", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Policies = append(m.Policies, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RoleList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RoleList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RoleList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, Role{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenerated(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthGenerated + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenerated + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenerated + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenerated = fmt.Errorf("proto: unexpected end of group") +) diff --git a/api/authz/v1/generated.proto b/api/authz/v1/generated.proto new file mode 100644 index 000000000..2e13515c3 --- /dev/null +++ b/api/authz/v1/generated.proto @@ -0,0 +1,151 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// This file was autogenerated by go-to-protobuf. Do not edit it manually! + +syntax = "proto2"; + +package tkestack.io.tke.api.authz.v1; + +import "k8s.io/api/rbac/v1/generated.proto"; +import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; +import "k8s.io/apimachinery/pkg/runtime/generated.proto"; +import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; + +// Package-wide variables from generator "generated". +option go_package = "v1"; + +// ConfigMap holds configuration data for tke to consume. +message ConfigMap { + // +optional + optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // Data contains the configuration data. + // Each key must consist of alphanumeric characters, '-', '_' or '.'. + // Values with non-UTF-8 byte sequences must use the BinaryData field. + // The keys stored in Data must not overlap with the keys in + // the BinaryData field, this is enforced during validation process. + // +optional + map data = 2; + + // BinaryData contains the binary data. + // Each key must consist of alphanumeric characters, '-', '_' or '.'. + // BinaryData can contain byte sequences that are not in the UTF-8 range. + // The keys stored in BinaryData must not overlap with the ones in + // the Data field, this is enforced during validation process. + // +optional + map binaryData = 3; +} + +// ConfigMapList is a resource containing a list of ConfigMap objects. +message ConfigMapList { + // +optional + optional k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // Items is the list of ConfigMaps. + repeated ConfigMap items = 2; +} + +message MultiClusterRoleBinding { + optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + optional MultiClusterRoleBindingSpec spec = 2; + + optional MultiClusterRoleBindingStatus status = 3; +} + +message MultiClusterRoleBindingList { + optional k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // List of rules. + repeated MultiClusterRoleBinding items = 2; +} + +message MultiClusterRoleBindingSpec { + optional string tenantID = 1; + + optional string username = 2; + + optional string roleName = 3; + + repeated string clusters = 4; +} + +message MultiClusterRoleBindingStatus { + // +optional + optional string phase = 1; +} + +// Policy is a rbac template in TKE. +message Policy { + // +optional + optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + optional string displayName = 2; + + // +optional + optional string tenantID = 3; + + // +optional + optional string username = 4; + + // +optional + optional string description = 5; + + optional string scope = 6; + + repeated k8s.io.api.rbac.v1.PolicyRule rules = 7; +} + +// PolicyList is the whole list of all rbac templates. +message PolicyList { + // +optional + optional k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // List of policies + repeated Policy items = 2; +} + +// Role is a collection with multiple policies. +message Role { + optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + optional string displayName = 2; + + // +optional + optional string tenantID = 3; + + // +optional + optional string username = 4; + + // +optional + optional string description = 5; + + optional string scope = 6; + + repeated string policies = 7; +} + +// RoleList is the whole list of policy. +message RoleList { + optional k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // List of rules. + repeated Role items = 2; +} + diff --git a/api/authz/v1/register.go b/api/authz/v1/register.go new file mode 100644 index 000000000..abd40a482 --- /dev/null +++ b/api/authz/v1/register.go @@ -0,0 +1,69 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// GroupName is the group name use in this package. +const GroupName = "authz.tkestack.io" + +// Version is the version name use in this package. +const Version = "v1" + +// SchemeGroupVersion is group version used to register these objects. +var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: Version} + +var ( + // SchemeBuilder collects functions that add things to a scheme. + SchemeBuilder runtime.SchemeBuilder + localSchemeBuilder = &SchemeBuilder + // AddToScheme applies all the stored functions to the scheme. + AddToScheme = localSchemeBuilder.AddToScheme +) + +func init() { + localSchemeBuilder.Register(addKnownTypes) +} + +// addKnownTypes adds the list of known types to the given scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &Policy{}, + &PolicyList{}, + &Role{}, + &RoleList{}, + &MultiClusterRoleBinding{}, + &MultiClusterRoleBindingList{}, + &ConfigMap{}, + &ConfigMapList{}, + ) + + metav1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} + +// Resource takes an unqualified resource and returns a Group qualified +// GroupResource +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} diff --git a/api/authz/v1/types.go b/api/authz/v1/types.go new file mode 100644 index 000000000..2b3f46c15 --- /dev/null +++ b/api/authz/v1/types.go @@ -0,0 +1,184 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package v1 + +import ( + rbacv1 "k8s.io/api/rbac/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +type Scope string + +const ( + PlatformScope Scope = "Platform" + MultiClusterScope Scope = "MultiCluster" + BusinessScope Scope = "Business" +) + +// +genclient +// +genclient:skipVerbs=deleteCollection +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Policy is a rbac template in TKE. +type Policy struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + DisplayName string `json:"displayName" protobuf:"bytes,2,opt,name=displayName"` + // +optional + TenantID string `json:"tenantID" protobuf:"bytes,3,opt,name=tenantID"` + // +optional + Username string `json:"username" protobuf:"bytes,4,opt,name=username"` + // +optional + Description string `json:"description" protobuf:"bytes,5,opt,name=description"` + Scope Scope `json:"scope" protobuf:"bytes,6,opt,name=scope"` + Rules []rbacv1.PolicyRule `json:"rules" protobuf:"bytes,7,rep,name=rules"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// PolicyList is the whole list of all rbac templates. +type PolicyList struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // List of policies + Items []Policy `json:"items" protobuf:"bytes,2,rep,name=items"` +} + +// +genclient +// +genclient:skipVerbs=deleteCollection +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Role is a collection with multiple policies. +type Role struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + DisplayName string `json:"displayName" protobuf:"bytes,2,opt,name=displayName"` + // +optional + TenantID string `json:"tenantID" protobuf:"bytes,3,opt,name=tenantID"` + // +optional + Username string `json:"username" protobuf:"bytes,4,opt,name=username"` + // +optional + Description string `json:"description" protobuf:"bytes,5,opt,name=description"` + Scope Scope `json:"scope" protobuf:"bytes,6,opt,name=scope"` + Policies []string `json:"policies" protobuf:"bytes,7,rep,name=policies"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// RoleList is the whole list of policy. +type RoleList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + // List of rules. + Items []Role `json:"items" protobuf:"bytes,2,rep,name=items"` +} + +// +genclient +// +genclient:skipVerbs=deleteCollection +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +type MultiClusterRoleBinding struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + Spec MultiClusterRoleBindingSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` + Status MultiClusterRoleBindingStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` +} + +type MultiClusterRoleBindingSpec struct { + TenantID string `json:"tenantID" protobuf:"bytes,1,name=tenantID"` + Username string `json:"username" protobuf:"bytes,2,name=username"` + RoleName string `json:"roleName" protobuf:"bytes,3,name=roleName"` + Clusters []string `json:"clusters" protobuf:"bytes,4,rep,name=clusters"` +} + +type MultiClusterRoleBindingStatus struct { + // +optional + Phase BindingPhase `json:"phase" protobuf:"bytes,1,opt,name=phase"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +type MultiClusterRoleBindingList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + // List of rules. + Items []MultiClusterRoleBinding `json:"items" protobuf:"bytes,2,rep,name=items"` +} + +type BindingPhase string + +const ( + BindingActive BindingPhase = "Active" + BindingTerminating BindingPhase = "Terminating" +) + +type FinalizerName string + +const ( + PolicyFinalize FinalizerName = "policy" + RoleFinalize FinalizerName = "role" + MultiClusterRoleBindingFinalize FinalizerName = "rolebinding" +) + +// +genclient +// +genclient:nonNamespaced +// +genclient:skipVerbs=deleteCollection +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ConfigMap holds configuration data for tke to consume. +type ConfigMap struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // Data contains the configuration data. + // Each key must consist of alphanumeric characters, '-', '_' or '.'. + // Values with non-UTF-8 byte sequences must use the BinaryData field. + // The keys stored in Data must not overlap with the keys in + // the BinaryData field, this is enforced during validation process. + // +optional + Data map[string]string `json:"data,omitempty" protobuf:"bytes,2,rep,name=data"` + + // BinaryData contains the binary data. + // Each key must consist of alphanumeric characters, '-', '_' or '.'. + // BinaryData can contain byte sequences that are not in the UTF-8 range. + // The keys stored in BinaryData must not overlap with the ones in + // the Data field, this is enforced during validation process. + // +optional + BinaryData map[string][]byte `json:"binaryData,omitempty" protobuf:"bytes,3,rep,name=binaryData"` +} + +// +genclient:nonNamespaced +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ConfigMapList is a resource containing a list of ConfigMap objects. +type ConfigMapList struct { + metav1.TypeMeta `json:",inline"` + + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // Items is the list of ConfigMaps. + Items []ConfigMap `json:"items" protobuf:"bytes,2,rep,name=items"` +} diff --git a/api/authz/v1/types_swagger_doc_generated.go b/api/authz/v1/types_swagger_doc_generated.go new file mode 100644 index 000000000..6481fa675 --- /dev/null +++ b/api/authz/v1/types_swagger_doc_generated.go @@ -0,0 +1,93 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package v1 + +// This file contains a collection of methods that can be used from go-restful to +// generate Swagger API documentation for its models. Please read this PR for more +// information on the implementation: https://github.com/emicklei/go-restful/pull/215 +// +// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if +// they are on one line! For multiple line or blocks that you want to ignore use ---. +// Any context after a --- is ignored. +// +// Those methods can be generated by using hack/update-generated-swagger-docs.sh + +// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. +var map_ConfigMap = map[string]string{ + "": "ConfigMap holds configuration data for tke to consume.", + "data": "Data contains the configuration data. Each key must consist of alphanumeric characters, '-', '_' or '.'. Values with non-UTF-8 byte sequences must use the BinaryData field. The keys stored in Data must not overlap with the keys in the BinaryData field, this is enforced during validation process.", + "binaryData": "BinaryData contains the binary data. Each key must consist of alphanumeric characters, '-', '_' or '.'. BinaryData can contain byte sequences that are not in the UTF-8 range. The keys stored in BinaryData must not overlap with the ones in the Data field, this is enforced during validation process.", +} + +func (ConfigMap) SwaggerDoc() map[string]string { + return map_ConfigMap +} + +var map_ConfigMapList = map[string]string{ + "": "ConfigMapList is a resource containing a list of ConfigMap objects.", + "items": "Items is the list of ConfigMaps.", +} + +func (ConfigMapList) SwaggerDoc() map[string]string { + return map_ConfigMapList +} + +var map_MultiClusterRoleBindingList = map[string]string{ + "items": "List of rules.", +} + +func (MultiClusterRoleBindingList) SwaggerDoc() map[string]string { + return map_MultiClusterRoleBindingList +} + +var map_Policy = map[string]string{ + "": "Policy is a rbac template in TKE.", +} + +func (Policy) SwaggerDoc() map[string]string { + return map_Policy +} + +var map_PolicyList = map[string]string{ + "": "PolicyList is the whole list of all rbac templates.", + "items": "List of policies", +} + +func (PolicyList) SwaggerDoc() map[string]string { + return map_PolicyList +} + +var map_Role = map[string]string{ + "": "Role is a collection with multiple policies.", +} + +func (Role) SwaggerDoc() map[string]string { + return map_Role +} + +var map_RoleList = map[string]string{ + "": "RoleList is the whole list of policy.", + "items": "List of rules.", +} + +func (RoleList) SwaggerDoc() map[string]string { + return map_RoleList +} + +// AUTO-GENERATED FUNCTIONS END HERE diff --git a/api/authz/v1/zz_generated.conversion.go b/api/authz/v1/zz_generated.conversion.go new file mode 100644 index 000000000..b1666c804 --- /dev/null +++ b/api/authz/v1/zz_generated.conversion.go @@ -0,0 +1,396 @@ +// +build !ignore_autogenerated + +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by conversion-gen. DO NOT EDIT. + +package v1 + +import ( + unsafe "unsafe" + + rbacv1 "k8s.io/api/rbac/v1" + conversion "k8s.io/apimachinery/pkg/conversion" + runtime "k8s.io/apimachinery/pkg/runtime" + authz "tkestack.io/tke/api/authz" +) + +func init() { + localSchemeBuilder.Register(RegisterConversions) +} + +// RegisterConversions adds conversion functions to the given scheme. +// Public to allow building arbitrary schemes. +func RegisterConversions(s *runtime.Scheme) error { + if err := s.AddGeneratedConversionFunc((*ConfigMap)(nil), (*authz.ConfigMap)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_ConfigMap_To_authz_ConfigMap(a.(*ConfigMap), b.(*authz.ConfigMap), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*authz.ConfigMap)(nil), (*ConfigMap)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_authz_ConfigMap_To_v1_ConfigMap(a.(*authz.ConfigMap), b.(*ConfigMap), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ConfigMapList)(nil), (*authz.ConfigMapList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_ConfigMapList_To_authz_ConfigMapList(a.(*ConfigMapList), b.(*authz.ConfigMapList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*authz.ConfigMapList)(nil), (*ConfigMapList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_authz_ConfigMapList_To_v1_ConfigMapList(a.(*authz.ConfigMapList), b.(*ConfigMapList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MultiClusterRoleBinding)(nil), (*authz.MultiClusterRoleBinding)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_MultiClusterRoleBinding_To_authz_MultiClusterRoleBinding(a.(*MultiClusterRoleBinding), b.(*authz.MultiClusterRoleBinding), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*authz.MultiClusterRoleBinding)(nil), (*MultiClusterRoleBinding)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_authz_MultiClusterRoleBinding_To_v1_MultiClusterRoleBinding(a.(*authz.MultiClusterRoleBinding), b.(*MultiClusterRoleBinding), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MultiClusterRoleBindingList)(nil), (*authz.MultiClusterRoleBindingList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_MultiClusterRoleBindingList_To_authz_MultiClusterRoleBindingList(a.(*MultiClusterRoleBindingList), b.(*authz.MultiClusterRoleBindingList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*authz.MultiClusterRoleBindingList)(nil), (*MultiClusterRoleBindingList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_authz_MultiClusterRoleBindingList_To_v1_MultiClusterRoleBindingList(a.(*authz.MultiClusterRoleBindingList), b.(*MultiClusterRoleBindingList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MultiClusterRoleBindingSpec)(nil), (*authz.MultiClusterRoleBindingSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_MultiClusterRoleBindingSpec_To_authz_MultiClusterRoleBindingSpec(a.(*MultiClusterRoleBindingSpec), b.(*authz.MultiClusterRoleBindingSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*authz.MultiClusterRoleBindingSpec)(nil), (*MultiClusterRoleBindingSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_authz_MultiClusterRoleBindingSpec_To_v1_MultiClusterRoleBindingSpec(a.(*authz.MultiClusterRoleBindingSpec), b.(*MultiClusterRoleBindingSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MultiClusterRoleBindingStatus)(nil), (*authz.MultiClusterRoleBindingStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_MultiClusterRoleBindingStatus_To_authz_MultiClusterRoleBindingStatus(a.(*MultiClusterRoleBindingStatus), b.(*authz.MultiClusterRoleBindingStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*authz.MultiClusterRoleBindingStatus)(nil), (*MultiClusterRoleBindingStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_authz_MultiClusterRoleBindingStatus_To_v1_MultiClusterRoleBindingStatus(a.(*authz.MultiClusterRoleBindingStatus), b.(*MultiClusterRoleBindingStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Policy)(nil), (*authz.Policy)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_Policy_To_authz_Policy(a.(*Policy), b.(*authz.Policy), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*authz.Policy)(nil), (*Policy)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_authz_Policy_To_v1_Policy(a.(*authz.Policy), b.(*Policy), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*PolicyList)(nil), (*authz.PolicyList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_PolicyList_To_authz_PolicyList(a.(*PolicyList), b.(*authz.PolicyList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*authz.PolicyList)(nil), (*PolicyList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_authz_PolicyList_To_v1_PolicyList(a.(*authz.PolicyList), b.(*PolicyList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Role)(nil), (*authz.Role)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_Role_To_authz_Role(a.(*Role), b.(*authz.Role), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*authz.Role)(nil), (*Role)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_authz_Role_To_v1_Role(a.(*authz.Role), b.(*Role), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*RoleList)(nil), (*authz.RoleList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_RoleList_To_authz_RoleList(a.(*RoleList), b.(*authz.RoleList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*authz.RoleList)(nil), (*RoleList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_authz_RoleList_To_v1_RoleList(a.(*authz.RoleList), b.(*RoleList), scope) + }); err != nil { + return err + } + return nil +} + +func autoConvert_v1_ConfigMap_To_authz_ConfigMap(in *ConfigMap, out *authz.ConfigMap, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.Data = *(*map[string]string)(unsafe.Pointer(&in.Data)) + out.BinaryData = *(*map[string][]byte)(unsafe.Pointer(&in.BinaryData)) + return nil +} + +// Convert_v1_ConfigMap_To_authz_ConfigMap is an autogenerated conversion function. +func Convert_v1_ConfigMap_To_authz_ConfigMap(in *ConfigMap, out *authz.ConfigMap, s conversion.Scope) error { + return autoConvert_v1_ConfigMap_To_authz_ConfigMap(in, out, s) +} + +func autoConvert_authz_ConfigMap_To_v1_ConfigMap(in *authz.ConfigMap, out *ConfigMap, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.Data = *(*map[string]string)(unsafe.Pointer(&in.Data)) + out.BinaryData = *(*map[string][]byte)(unsafe.Pointer(&in.BinaryData)) + return nil +} + +// Convert_authz_ConfigMap_To_v1_ConfigMap is an autogenerated conversion function. +func Convert_authz_ConfigMap_To_v1_ConfigMap(in *authz.ConfigMap, out *ConfigMap, s conversion.Scope) error { + return autoConvert_authz_ConfigMap_To_v1_ConfigMap(in, out, s) +} + +func autoConvert_v1_ConfigMapList_To_authz_ConfigMapList(in *ConfigMapList, out *authz.ConfigMapList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]authz.ConfigMap)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_v1_ConfigMapList_To_authz_ConfigMapList is an autogenerated conversion function. +func Convert_v1_ConfigMapList_To_authz_ConfigMapList(in *ConfigMapList, out *authz.ConfigMapList, s conversion.Scope) error { + return autoConvert_v1_ConfigMapList_To_authz_ConfigMapList(in, out, s) +} + +func autoConvert_authz_ConfigMapList_To_v1_ConfigMapList(in *authz.ConfigMapList, out *ConfigMapList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]ConfigMap)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_authz_ConfigMapList_To_v1_ConfigMapList is an autogenerated conversion function. +func Convert_authz_ConfigMapList_To_v1_ConfigMapList(in *authz.ConfigMapList, out *ConfigMapList, s conversion.Scope) error { + return autoConvert_authz_ConfigMapList_To_v1_ConfigMapList(in, out, s) +} + +func autoConvert_v1_MultiClusterRoleBinding_To_authz_MultiClusterRoleBinding(in *MultiClusterRoleBinding, out *authz.MultiClusterRoleBinding, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1_MultiClusterRoleBindingSpec_To_authz_MultiClusterRoleBindingSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1_MultiClusterRoleBindingStatus_To_authz_MultiClusterRoleBindingStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1_MultiClusterRoleBinding_To_authz_MultiClusterRoleBinding is an autogenerated conversion function. +func Convert_v1_MultiClusterRoleBinding_To_authz_MultiClusterRoleBinding(in *MultiClusterRoleBinding, out *authz.MultiClusterRoleBinding, s conversion.Scope) error { + return autoConvert_v1_MultiClusterRoleBinding_To_authz_MultiClusterRoleBinding(in, out, s) +} + +func autoConvert_authz_MultiClusterRoleBinding_To_v1_MultiClusterRoleBinding(in *authz.MultiClusterRoleBinding, out *MultiClusterRoleBinding, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_authz_MultiClusterRoleBindingSpec_To_v1_MultiClusterRoleBindingSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_authz_MultiClusterRoleBindingStatus_To_v1_MultiClusterRoleBindingStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_authz_MultiClusterRoleBinding_To_v1_MultiClusterRoleBinding is an autogenerated conversion function. +func Convert_authz_MultiClusterRoleBinding_To_v1_MultiClusterRoleBinding(in *authz.MultiClusterRoleBinding, out *MultiClusterRoleBinding, s conversion.Scope) error { + return autoConvert_authz_MultiClusterRoleBinding_To_v1_MultiClusterRoleBinding(in, out, s) +} + +func autoConvert_v1_MultiClusterRoleBindingList_To_authz_MultiClusterRoleBindingList(in *MultiClusterRoleBindingList, out *authz.MultiClusterRoleBindingList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]authz.MultiClusterRoleBinding)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_v1_MultiClusterRoleBindingList_To_authz_MultiClusterRoleBindingList is an autogenerated conversion function. +func Convert_v1_MultiClusterRoleBindingList_To_authz_MultiClusterRoleBindingList(in *MultiClusterRoleBindingList, out *authz.MultiClusterRoleBindingList, s conversion.Scope) error { + return autoConvert_v1_MultiClusterRoleBindingList_To_authz_MultiClusterRoleBindingList(in, out, s) +} + +func autoConvert_authz_MultiClusterRoleBindingList_To_v1_MultiClusterRoleBindingList(in *authz.MultiClusterRoleBindingList, out *MultiClusterRoleBindingList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]MultiClusterRoleBinding)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_authz_MultiClusterRoleBindingList_To_v1_MultiClusterRoleBindingList is an autogenerated conversion function. +func Convert_authz_MultiClusterRoleBindingList_To_v1_MultiClusterRoleBindingList(in *authz.MultiClusterRoleBindingList, out *MultiClusterRoleBindingList, s conversion.Scope) error { + return autoConvert_authz_MultiClusterRoleBindingList_To_v1_MultiClusterRoleBindingList(in, out, s) +} + +func autoConvert_v1_MultiClusterRoleBindingSpec_To_authz_MultiClusterRoleBindingSpec(in *MultiClusterRoleBindingSpec, out *authz.MultiClusterRoleBindingSpec, s conversion.Scope) error { + out.TenantID = in.TenantID + out.Username = in.Username + out.RoleName = in.RoleName + out.Clusters = *(*[]string)(unsafe.Pointer(&in.Clusters)) + return nil +} + +// Convert_v1_MultiClusterRoleBindingSpec_To_authz_MultiClusterRoleBindingSpec is an autogenerated conversion function. +func Convert_v1_MultiClusterRoleBindingSpec_To_authz_MultiClusterRoleBindingSpec(in *MultiClusterRoleBindingSpec, out *authz.MultiClusterRoleBindingSpec, s conversion.Scope) error { + return autoConvert_v1_MultiClusterRoleBindingSpec_To_authz_MultiClusterRoleBindingSpec(in, out, s) +} + +func autoConvert_authz_MultiClusterRoleBindingSpec_To_v1_MultiClusterRoleBindingSpec(in *authz.MultiClusterRoleBindingSpec, out *MultiClusterRoleBindingSpec, s conversion.Scope) error { + out.TenantID = in.TenantID + out.Username = in.Username + out.RoleName = in.RoleName + out.Clusters = *(*[]string)(unsafe.Pointer(&in.Clusters)) + return nil +} + +// Convert_authz_MultiClusterRoleBindingSpec_To_v1_MultiClusterRoleBindingSpec is an autogenerated conversion function. +func Convert_authz_MultiClusterRoleBindingSpec_To_v1_MultiClusterRoleBindingSpec(in *authz.MultiClusterRoleBindingSpec, out *MultiClusterRoleBindingSpec, s conversion.Scope) error { + return autoConvert_authz_MultiClusterRoleBindingSpec_To_v1_MultiClusterRoleBindingSpec(in, out, s) +} + +func autoConvert_v1_MultiClusterRoleBindingStatus_To_authz_MultiClusterRoleBindingStatus(in *MultiClusterRoleBindingStatus, out *authz.MultiClusterRoleBindingStatus, s conversion.Scope) error { + out.Phase = authz.BindingPhase(in.Phase) + return nil +} + +// Convert_v1_MultiClusterRoleBindingStatus_To_authz_MultiClusterRoleBindingStatus is an autogenerated conversion function. +func Convert_v1_MultiClusterRoleBindingStatus_To_authz_MultiClusterRoleBindingStatus(in *MultiClusterRoleBindingStatus, out *authz.MultiClusterRoleBindingStatus, s conversion.Scope) error { + return autoConvert_v1_MultiClusterRoleBindingStatus_To_authz_MultiClusterRoleBindingStatus(in, out, s) +} + +func autoConvert_authz_MultiClusterRoleBindingStatus_To_v1_MultiClusterRoleBindingStatus(in *authz.MultiClusterRoleBindingStatus, out *MultiClusterRoleBindingStatus, s conversion.Scope) error { + out.Phase = BindingPhase(in.Phase) + return nil +} + +// Convert_authz_MultiClusterRoleBindingStatus_To_v1_MultiClusterRoleBindingStatus is an autogenerated conversion function. +func Convert_authz_MultiClusterRoleBindingStatus_To_v1_MultiClusterRoleBindingStatus(in *authz.MultiClusterRoleBindingStatus, out *MultiClusterRoleBindingStatus, s conversion.Scope) error { + return autoConvert_authz_MultiClusterRoleBindingStatus_To_v1_MultiClusterRoleBindingStatus(in, out, s) +} + +func autoConvert_v1_Policy_To_authz_Policy(in *Policy, out *authz.Policy, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.DisplayName = in.DisplayName + out.TenantID = in.TenantID + out.Username = in.Username + out.Description = in.Description + out.Scope = authz.Scope(in.Scope) + out.Rules = *(*[]rbacv1.PolicyRule)(unsafe.Pointer(&in.Rules)) + return nil +} + +// Convert_v1_Policy_To_authz_Policy is an autogenerated conversion function. +func Convert_v1_Policy_To_authz_Policy(in *Policy, out *authz.Policy, s conversion.Scope) error { + return autoConvert_v1_Policy_To_authz_Policy(in, out, s) +} + +func autoConvert_authz_Policy_To_v1_Policy(in *authz.Policy, out *Policy, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.DisplayName = in.DisplayName + out.TenantID = in.TenantID + out.Username = in.Username + out.Description = in.Description + out.Scope = Scope(in.Scope) + out.Rules = *(*[]rbacv1.PolicyRule)(unsafe.Pointer(&in.Rules)) + return nil +} + +// Convert_authz_Policy_To_v1_Policy is an autogenerated conversion function. +func Convert_authz_Policy_To_v1_Policy(in *authz.Policy, out *Policy, s conversion.Scope) error { + return autoConvert_authz_Policy_To_v1_Policy(in, out, s) +} + +func autoConvert_v1_PolicyList_To_authz_PolicyList(in *PolicyList, out *authz.PolicyList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]authz.Policy)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_v1_PolicyList_To_authz_PolicyList is an autogenerated conversion function. +func Convert_v1_PolicyList_To_authz_PolicyList(in *PolicyList, out *authz.PolicyList, s conversion.Scope) error { + return autoConvert_v1_PolicyList_To_authz_PolicyList(in, out, s) +} + +func autoConvert_authz_PolicyList_To_v1_PolicyList(in *authz.PolicyList, out *PolicyList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]Policy)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_authz_PolicyList_To_v1_PolicyList is an autogenerated conversion function. +func Convert_authz_PolicyList_To_v1_PolicyList(in *authz.PolicyList, out *PolicyList, s conversion.Scope) error { + return autoConvert_authz_PolicyList_To_v1_PolicyList(in, out, s) +} + +func autoConvert_v1_Role_To_authz_Role(in *Role, out *authz.Role, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.DisplayName = in.DisplayName + out.TenantID = in.TenantID + out.Username = in.Username + out.Description = in.Description + out.Scope = authz.Scope(in.Scope) + out.Policies = *(*[]string)(unsafe.Pointer(&in.Policies)) + return nil +} + +// Convert_v1_Role_To_authz_Role is an autogenerated conversion function. +func Convert_v1_Role_To_authz_Role(in *Role, out *authz.Role, s conversion.Scope) error { + return autoConvert_v1_Role_To_authz_Role(in, out, s) +} + +func autoConvert_authz_Role_To_v1_Role(in *authz.Role, out *Role, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.DisplayName = in.DisplayName + out.TenantID = in.TenantID + out.Username = in.Username + out.Description = in.Description + out.Scope = Scope(in.Scope) + out.Policies = *(*[]string)(unsafe.Pointer(&in.Policies)) + return nil +} + +// Convert_authz_Role_To_v1_Role is an autogenerated conversion function. +func Convert_authz_Role_To_v1_Role(in *authz.Role, out *Role, s conversion.Scope) error { + return autoConvert_authz_Role_To_v1_Role(in, out, s) +} + +func autoConvert_v1_RoleList_To_authz_RoleList(in *RoleList, out *authz.RoleList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]authz.Role)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_v1_RoleList_To_authz_RoleList is an autogenerated conversion function. +func Convert_v1_RoleList_To_authz_RoleList(in *RoleList, out *authz.RoleList, s conversion.Scope) error { + return autoConvert_v1_RoleList_To_authz_RoleList(in, out, s) +} + +func autoConvert_authz_RoleList_To_v1_RoleList(in *authz.RoleList, out *RoleList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]Role)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_authz_RoleList_To_v1_RoleList is an autogenerated conversion function. +func Convert_authz_RoleList_To_v1_RoleList(in *authz.RoleList, out *RoleList, s conversion.Scope) error { + return autoConvert_authz_RoleList_To_v1_RoleList(in, out, s) +} diff --git a/api/authz/v1/zz_generated.deepcopy.go b/api/authz/v1/zz_generated.deepcopy.go new file mode 100644 index 000000000..088fbde6e --- /dev/null +++ b/api/authz/v1/zz_generated.deepcopy.go @@ -0,0 +1,337 @@ +// +build !ignore_autogenerated + +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by deepcopy-gen. DO NOT EDIT. + +package v1 + +import ( + rbacv1 "k8s.io/api/rbac/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConfigMap) DeepCopyInto(out *ConfigMap) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + if in.Data != nil { + in, out := &in.Data, &out.Data + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.BinaryData != nil { + in, out := &in.BinaryData, &out.BinaryData + *out = make(map[string][]byte, len(*in)) + for key, val := range *in { + var outVal []byte + if val == nil { + (*out)[key] = nil + } else { + in, out := &val, &outVal + *out = make([]byte, len(*in)) + copy(*out, *in) + } + (*out)[key] = outVal + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigMap. +func (in *ConfigMap) DeepCopy() *ConfigMap { + if in == nil { + return nil + } + out := new(ConfigMap) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ConfigMap) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConfigMapList) DeepCopyInto(out *ConfigMapList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ConfigMap, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigMapList. +func (in *ConfigMapList) DeepCopy() *ConfigMapList { + if in == nil { + return nil + } + out := new(ConfigMapList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ConfigMapList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MultiClusterRoleBinding) DeepCopyInto(out *MultiClusterRoleBinding) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + out.Status = in.Status + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MultiClusterRoleBinding. +func (in *MultiClusterRoleBinding) DeepCopy() *MultiClusterRoleBinding { + if in == nil { + return nil + } + out := new(MultiClusterRoleBinding) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MultiClusterRoleBinding) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MultiClusterRoleBindingList) DeepCopyInto(out *MultiClusterRoleBindingList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MultiClusterRoleBinding, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MultiClusterRoleBindingList. +func (in *MultiClusterRoleBindingList) DeepCopy() *MultiClusterRoleBindingList { + if in == nil { + return nil + } + out := new(MultiClusterRoleBindingList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MultiClusterRoleBindingList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MultiClusterRoleBindingSpec) DeepCopyInto(out *MultiClusterRoleBindingSpec) { + *out = *in + if in.Clusters != nil { + in, out := &in.Clusters, &out.Clusters + *out = make([]string, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MultiClusterRoleBindingSpec. +func (in *MultiClusterRoleBindingSpec) DeepCopy() *MultiClusterRoleBindingSpec { + if in == nil { + return nil + } + out := new(MultiClusterRoleBindingSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MultiClusterRoleBindingStatus) DeepCopyInto(out *MultiClusterRoleBindingStatus) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MultiClusterRoleBindingStatus. +func (in *MultiClusterRoleBindingStatus) DeepCopy() *MultiClusterRoleBindingStatus { + if in == nil { + return nil + } + out := new(MultiClusterRoleBindingStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Policy) DeepCopyInto(out *Policy) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + if in.Rules != nil { + in, out := &in.Rules, &out.Rules + *out = make([]rbacv1.PolicyRule, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Policy. +func (in *Policy) DeepCopy() *Policy { + if in == nil { + return nil + } + out := new(Policy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Policy) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PolicyList) DeepCopyInto(out *PolicyList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Policy, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PolicyList. +func (in *PolicyList) DeepCopy() *PolicyList { + if in == nil { + return nil + } + out := new(PolicyList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PolicyList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Role) DeepCopyInto(out *Role) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + if in.Policies != nil { + in, out := &in.Policies, &out.Policies + *out = make([]string, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Role. +func (in *Role) DeepCopy() *Role { + if in == nil { + return nil + } + out := new(Role) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Role) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RoleList) DeepCopyInto(out *RoleList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Role, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RoleList. +func (in *RoleList) DeepCopy() *RoleList { + if in == nil { + return nil + } + out := new(RoleList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *RoleList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} diff --git a/api/authz/v1/zz_generated.defaults.go b/api/authz/v1/zz_generated.defaults.go new file mode 100644 index 000000000..814adfc20 --- /dev/null +++ b/api/authz/v1/zz_generated.defaults.go @@ -0,0 +1,34 @@ +// +build !ignore_autogenerated + +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by defaulter-gen. DO NOT EDIT. + +package v1 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// RegisterDefaults adds defaulters functions to the given scheme. +// Public to allow building arbitrary schemes. +// All generated defaulters are covering - they call all nested defaulters. +func RegisterDefaults(scheme *runtime.Scheme) error { + return nil +} diff --git a/api/authz/zz_generated.deepcopy.go b/api/authz/zz_generated.deepcopy.go new file mode 100644 index 000000000..6c1cf9644 --- /dev/null +++ b/api/authz/zz_generated.deepcopy.go @@ -0,0 +1,337 @@ +// +build !ignore_autogenerated + +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by deepcopy-gen. DO NOT EDIT. + +package authz + +import ( + v1 "k8s.io/api/rbac/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConfigMap) DeepCopyInto(out *ConfigMap) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + if in.Data != nil { + in, out := &in.Data, &out.Data + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.BinaryData != nil { + in, out := &in.BinaryData, &out.BinaryData + *out = make(map[string][]byte, len(*in)) + for key, val := range *in { + var outVal []byte + if val == nil { + (*out)[key] = nil + } else { + in, out := &val, &outVal + *out = make([]byte, len(*in)) + copy(*out, *in) + } + (*out)[key] = outVal + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigMap. +func (in *ConfigMap) DeepCopy() *ConfigMap { + if in == nil { + return nil + } + out := new(ConfigMap) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ConfigMap) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConfigMapList) DeepCopyInto(out *ConfigMapList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ConfigMap, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigMapList. +func (in *ConfigMapList) DeepCopy() *ConfigMapList { + if in == nil { + return nil + } + out := new(ConfigMapList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ConfigMapList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MultiClusterRoleBinding) DeepCopyInto(out *MultiClusterRoleBinding) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + out.Status = in.Status + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MultiClusterRoleBinding. +func (in *MultiClusterRoleBinding) DeepCopy() *MultiClusterRoleBinding { + if in == nil { + return nil + } + out := new(MultiClusterRoleBinding) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MultiClusterRoleBinding) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MultiClusterRoleBindingList) DeepCopyInto(out *MultiClusterRoleBindingList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MultiClusterRoleBinding, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MultiClusterRoleBindingList. +func (in *MultiClusterRoleBindingList) DeepCopy() *MultiClusterRoleBindingList { + if in == nil { + return nil + } + out := new(MultiClusterRoleBindingList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MultiClusterRoleBindingList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MultiClusterRoleBindingSpec) DeepCopyInto(out *MultiClusterRoleBindingSpec) { + *out = *in + if in.Clusters != nil { + in, out := &in.Clusters, &out.Clusters + *out = make([]string, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MultiClusterRoleBindingSpec. +func (in *MultiClusterRoleBindingSpec) DeepCopy() *MultiClusterRoleBindingSpec { + if in == nil { + return nil + } + out := new(MultiClusterRoleBindingSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MultiClusterRoleBindingStatus) DeepCopyInto(out *MultiClusterRoleBindingStatus) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MultiClusterRoleBindingStatus. +func (in *MultiClusterRoleBindingStatus) DeepCopy() *MultiClusterRoleBindingStatus { + if in == nil { + return nil + } + out := new(MultiClusterRoleBindingStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Policy) DeepCopyInto(out *Policy) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + if in.Rules != nil { + in, out := &in.Rules, &out.Rules + *out = make([]v1.PolicyRule, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Policy. +func (in *Policy) DeepCopy() *Policy { + if in == nil { + return nil + } + out := new(Policy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Policy) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PolicyList) DeepCopyInto(out *PolicyList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Policy, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PolicyList. +func (in *PolicyList) DeepCopy() *PolicyList { + if in == nil { + return nil + } + out := new(PolicyList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PolicyList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Role) DeepCopyInto(out *Role) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + if in.Policies != nil { + in, out := &in.Policies, &out.Policies + *out = make([]string, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Role. +func (in *Role) DeepCopy() *Role { + if in == nil { + return nil + } + out := new(Role) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Role) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RoleList) DeepCopyInto(out *RoleList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Role, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RoleList. +func (in *RoleList) DeepCopy() *RoleList { + if in == nil { + return nil + } + out := new(RoleList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *RoleList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} diff --git a/api/client/clientset/internalversion/clientset.go b/api/client/clientset/internalversion/clientset.go index 5d37e07a5..ba7367bf9 100644 --- a/api/client/clientset/internalversion/clientset.go +++ b/api/client/clientset/internalversion/clientset.go @@ -28,6 +28,7 @@ import ( flowcontrol "k8s.io/client-go/util/flowcontrol" applicationinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/application/internalversion" authinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/auth/internalversion" + authzinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/authz/internalversion" businessinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/business/internalversion" logagentinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/logagent/internalversion" meshinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/mesh/internalversion" @@ -41,6 +42,7 @@ type Interface interface { Discovery() discovery.DiscoveryInterface Application() applicationinternalversion.ApplicationInterface Auth() authinternalversion.AuthInterface + Authz() authzinternalversion.AuthzInterface Business() businessinternalversion.BusinessInterface Logagent() logagentinternalversion.LogagentInterface Mesh() meshinternalversion.MeshInterface @@ -56,6 +58,7 @@ type Clientset struct { *discovery.DiscoveryClient application *applicationinternalversion.ApplicationClient auth *authinternalversion.AuthClient + authz *authzinternalversion.AuthzClient business *businessinternalversion.BusinessClient logagent *logagentinternalversion.LogagentClient mesh *meshinternalversion.MeshClient @@ -75,6 +78,11 @@ func (c *Clientset) Auth() authinternalversion.AuthInterface { return c.auth } +// Authz retrieves the AuthzClient +func (c *Clientset) Authz() authzinternalversion.AuthzInterface { + return c.authz +} + // Business retrieves the BusinessClient func (c *Clientset) Business() businessinternalversion.BusinessInterface { return c.business @@ -139,6 +147,10 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { if err != nil { return nil, err } + cs.authz, err = authzinternalversion.NewForConfig(&configShallowCopy) + if err != nil { + return nil, err + } cs.business, err = businessinternalversion.NewForConfig(&configShallowCopy) if err != nil { return nil, err @@ -181,6 +193,7 @@ func NewForConfigOrDie(c *rest.Config) *Clientset { var cs Clientset cs.application = applicationinternalversion.NewForConfigOrDie(c) cs.auth = authinternalversion.NewForConfigOrDie(c) + cs.authz = authzinternalversion.NewForConfigOrDie(c) cs.business = businessinternalversion.NewForConfigOrDie(c) cs.logagent = logagentinternalversion.NewForConfigOrDie(c) cs.mesh = meshinternalversion.NewForConfigOrDie(c) @@ -198,6 +211,7 @@ func New(c rest.Interface) *Clientset { var cs Clientset cs.application = applicationinternalversion.New(c) cs.auth = authinternalversion.New(c) + cs.authz = authzinternalversion.New(c) cs.business = businessinternalversion.New(c) cs.logagent = logagentinternalversion.New(c) cs.mesh = meshinternalversion.New(c) diff --git a/api/client/clientset/internalversion/fake/clientset_generated.go b/api/client/clientset/internalversion/fake/clientset_generated.go index 9a2f1cbc2..2470a14bc 100644 --- a/api/client/clientset/internalversion/fake/clientset_generated.go +++ b/api/client/clientset/internalversion/fake/clientset_generated.go @@ -31,6 +31,8 @@ import ( fakeapplicationinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/application/internalversion/fake" authinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/auth/internalversion" fakeauthinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/auth/internalversion/fake" + authzinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/authz/internalversion" + fakeauthzinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/authz/internalversion/fake" businessinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/business/internalversion" fakebusinessinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/business/internalversion/fake" logagentinternalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/logagent/internalversion" @@ -107,6 +109,11 @@ func (c *Clientset) Auth() authinternalversion.AuthInterface { return &fakeauthinternalversion.FakeAuth{Fake: &c.Fake} } +// Authz retrieves the AuthzClient +func (c *Clientset) Authz() authzinternalversion.AuthzInterface { + return &fakeauthzinternalversion.FakeAuthz{Fake: &c.Fake} +} + // Business retrieves the BusinessClient func (c *Clientset) Business() businessinternalversion.BusinessInterface { return &fakebusinessinternalversion.FakeBusiness{Fake: &c.Fake} diff --git a/api/client/clientset/internalversion/fake/register.go b/api/client/clientset/internalversion/fake/register.go index a031e9755..870e81835 100644 --- a/api/client/clientset/internalversion/fake/register.go +++ b/api/client/clientset/internalversion/fake/register.go @@ -28,6 +28,7 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" applicationinternalversion "tkestack.io/tke/api/application" authinternalversion "tkestack.io/tke/api/auth" + authzinternalversion "tkestack.io/tke/api/authz" businessinternalversion "tkestack.io/tke/api/business" logagentinternalversion "tkestack.io/tke/api/logagent" meshinternalversion "tkestack.io/tke/api/mesh" @@ -43,6 +44,7 @@ var codecs = serializer.NewCodecFactory(scheme) var localSchemeBuilder = runtime.SchemeBuilder{ applicationinternalversion.AddToScheme, authinternalversion.AddToScheme, + authzinternalversion.AddToScheme, businessinternalversion.AddToScheme, logagentinternalversion.AddToScheme, meshinternalversion.AddToScheme, diff --git a/api/client/clientset/internalversion/scheme/register.go b/api/client/clientset/internalversion/scheme/register.go index 99af56593..a3a29a7b8 100644 --- a/api/client/clientset/internalversion/scheme/register.go +++ b/api/client/clientset/internalversion/scheme/register.go @@ -27,6 +27,7 @@ import ( serializer "k8s.io/apimachinery/pkg/runtime/serializer" application "tkestack.io/tke/api/application/install" auth "tkestack.io/tke/api/auth/install" + authz "tkestack.io/tke/api/authz/install" business "tkestack.io/tke/api/business/install" logagent "tkestack.io/tke/api/logagent/install" mesh "tkestack.io/tke/api/mesh/install" @@ -49,6 +50,7 @@ func init() { func Install(scheme *runtime.Scheme) { application.Install(scheme) auth.Install(scheme) + authz.Install(scheme) business.Install(scheme) logagent.Install(scheme) mesh.Install(scheme) diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/authz_client.go b/api/client/clientset/internalversion/typed/authz/internalversion/authz_client.go new file mode 100644 index 000000000..e0fe7a463 --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/authz_client.go @@ -0,0 +1,113 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package internalversion + +import ( + rest "k8s.io/client-go/rest" + "tkestack.io/tke/api/client/clientset/internalversion/scheme" +) + +type AuthzInterface interface { + RESTClient() rest.Interface + ConfigMapsGetter + MultiClusterRoleBindingsGetter + PoliciesGetter + RolesGetter +} + +// AuthzClient is used to interact with features provided by the authz.tkestack.io group. +type AuthzClient struct { + restClient rest.Interface +} + +func (c *AuthzClient) ConfigMaps() ConfigMapInterface { + return newConfigMaps(c) +} + +func (c *AuthzClient) MultiClusterRoleBindings(namespace string) MultiClusterRoleBindingInterface { + return newMultiClusterRoleBindings(c, namespace) +} + +func (c *AuthzClient) Policies(namespace string) PolicyInterface { + return newPolicies(c, namespace) +} + +func (c *AuthzClient) Roles(namespace string) RoleInterface { + return newRoles(c, namespace) +} + +// NewForConfig creates a new AuthzClient for the given config. +func NewForConfig(c *rest.Config) (*AuthzClient, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientFor(&config) + if err != nil { + return nil, err + } + return &AuthzClient{client}, nil +} + +// NewForConfigOrDie creates a new AuthzClient for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *AuthzClient { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new AuthzClient for the given RESTClient. +func New(c rest.Interface) *AuthzClient { + return &AuthzClient{c} +} + +func setConfigDefaults(config *rest.Config) error { + config.APIPath = "/apis" + if config.UserAgent == "" { + config.UserAgent = rest.DefaultKubernetesUserAgent() + } + if config.GroupVersion == nil || config.GroupVersion.Group != scheme.Scheme.PrioritizedVersionsForGroup("authz.tkestack.io")[0].Group { + gv := scheme.Scheme.PrioritizedVersionsForGroup("authz.tkestack.io")[0] + config.GroupVersion = &gv + } + config.NegotiatedSerializer = scheme.Codecs + + if config.QPS == 0 { + config.QPS = 5 + } + if config.Burst == 0 { + config.Burst = 10 + } + + return nil +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *AuthzClient) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/configmap.go b/api/client/clientset/internalversion/typed/authz/internalversion/configmap.go new file mode 100644 index 000000000..f07d8f646 --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/configmap.go @@ -0,0 +1,170 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package internalversion + +import ( + "context" + "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" + authz "tkestack.io/tke/api/authz" + scheme "tkestack.io/tke/api/client/clientset/internalversion/scheme" +) + +// ConfigMapsGetter has a method to return a ConfigMapInterface. +// A group's client should implement this interface. +type ConfigMapsGetter interface { + ConfigMaps() ConfigMapInterface +} + +// ConfigMapInterface has methods to work with ConfigMap resources. +type ConfigMapInterface interface { + Create(ctx context.Context, configMap *authz.ConfigMap, opts v1.CreateOptions) (*authz.ConfigMap, error) + Update(ctx context.Context, configMap *authz.ConfigMap, opts v1.UpdateOptions) (*authz.ConfigMap, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*authz.ConfigMap, error) + List(ctx context.Context, opts v1.ListOptions) (*authz.ConfigMapList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.ConfigMap, err error) + ConfigMapExpansion +} + +// configMaps implements ConfigMapInterface +type configMaps struct { + client rest.Interface +} + +// newConfigMaps returns a ConfigMaps +func newConfigMaps(c *AuthzClient) *configMaps { + return &configMaps{ + client: c.RESTClient(), + } +} + +// Get takes name of the configMap, and returns the corresponding configMap object, and an error if there is any. +func (c *configMaps) Get(ctx context.Context, name string, options v1.GetOptions) (result *authz.ConfigMap, err error) { + result = &authz.ConfigMap{} + err = c.client.Get(). + Resource("configmaps"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of ConfigMaps that match those selectors. +func (c *configMaps) List(ctx context.Context, opts v1.ListOptions) (result *authz.ConfigMapList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &authz.ConfigMapList{} + err = c.client.Get(). + Resource("configmaps"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested configMaps. +func (c *configMaps) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Resource("configmaps"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a configMap and creates it. Returns the server's representation of the configMap, and an error, if there is any. +func (c *configMaps) Create(ctx context.Context, configMap *authz.ConfigMap, opts v1.CreateOptions) (result *authz.ConfigMap, err error) { + result = &authz.ConfigMap{} + err = c.client.Post(). + Resource("configmaps"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(configMap). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a configMap and updates it. Returns the server's representation of the configMap, and an error, if there is any. +func (c *configMaps) Update(ctx context.Context, configMap *authz.ConfigMap, opts v1.UpdateOptions) (result *authz.ConfigMap, err error) { + result = &authz.ConfigMap{} + err = c.client.Put(). + Resource("configmaps"). + Name(configMap.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(configMap). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the configMap and deletes it. Returns an error if one occurs. +func (c *configMaps) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return c.client.Delete(). + Resource("configmaps"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *configMaps) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Resource("configmaps"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched configMap. +func (c *configMaps) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.ConfigMap, err error) { + result = &authz.ConfigMap{} + err = c.client.Patch(pt). + Resource("configmaps"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/doc.go b/api/client/clientset/internalversion/typed/authz/internalversion/doc.go new file mode 100644 index 000000000..5ae9066bf --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/doc.go @@ -0,0 +1,22 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +// This package has the automatically generated typed clients. +package internalversion diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/fake/doc.go b/api/client/clientset/internalversion/typed/authz/internalversion/fake/doc.go new file mode 100644 index 000000000..d4bb4b09f --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/fake/doc.go @@ -0,0 +1,22 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +// Package fake has the automatically generated clients. +package fake diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_authz_client.go b/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_authz_client.go new file mode 100644 index 000000000..698cd7691 --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_authz_client.go @@ -0,0 +1,54 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + rest "k8s.io/client-go/rest" + testing "k8s.io/client-go/testing" + internalversion "tkestack.io/tke/api/client/clientset/internalversion/typed/authz/internalversion" +) + +type FakeAuthz struct { + *testing.Fake +} + +func (c *FakeAuthz) ConfigMaps() internalversion.ConfigMapInterface { + return &FakeConfigMaps{c} +} + +func (c *FakeAuthz) MultiClusterRoleBindings(namespace string) internalversion.MultiClusterRoleBindingInterface { + return &FakeMultiClusterRoleBindings{c, namespace} +} + +func (c *FakeAuthz) Policies(namespace string) internalversion.PolicyInterface { + return &FakePolicies{c, namespace} +} + +func (c *FakeAuthz) Roles(namespace string) internalversion.RoleInterface { + return &FakeRoles{c, namespace} +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *FakeAuthz) RESTClient() rest.Interface { + var ret *rest.RESTClient + return ret +} diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_configmap.go b/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_configmap.go new file mode 100644 index 000000000..36a564d25 --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_configmap.go @@ -0,0 +1,124 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" + authz "tkestack.io/tke/api/authz" +) + +// FakeConfigMaps implements ConfigMapInterface +type FakeConfigMaps struct { + Fake *FakeAuthz +} + +var configmapsResource = schema.GroupVersionResource{Group: "authz.tkestack.io", Version: "", Resource: "configmaps"} + +var configmapsKind = schema.GroupVersionKind{Group: "authz.tkestack.io", Version: "", Kind: "ConfigMap"} + +// Get takes name of the configMap, and returns the corresponding configMap object, and an error if there is any. +func (c *FakeConfigMaps) Get(ctx context.Context, name string, options v1.GetOptions) (result *authz.ConfigMap, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootGetAction(configmapsResource, name), &authz.ConfigMap{}) + if obj == nil { + return nil, err + } + return obj.(*authz.ConfigMap), err +} + +// List takes label and field selectors, and returns the list of ConfigMaps that match those selectors. +func (c *FakeConfigMaps) List(ctx context.Context, opts v1.ListOptions) (result *authz.ConfigMapList, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootListAction(configmapsResource, configmapsKind, opts), &authz.ConfigMapList{}) + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &authz.ConfigMapList{ListMeta: obj.(*authz.ConfigMapList).ListMeta} + for _, item := range obj.(*authz.ConfigMapList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested configMaps. +func (c *FakeConfigMaps) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewRootWatchAction(configmapsResource, opts)) +} + +// Create takes the representation of a configMap and creates it. Returns the server's representation of the configMap, and an error, if there is any. +func (c *FakeConfigMaps) Create(ctx context.Context, configMap *authz.ConfigMap, opts v1.CreateOptions) (result *authz.ConfigMap, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootCreateAction(configmapsResource, configMap), &authz.ConfigMap{}) + if obj == nil { + return nil, err + } + return obj.(*authz.ConfigMap), err +} + +// Update takes the representation of a configMap and updates it. Returns the server's representation of the configMap, and an error, if there is any. +func (c *FakeConfigMaps) Update(ctx context.Context, configMap *authz.ConfigMap, opts v1.UpdateOptions) (result *authz.ConfigMap, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootUpdateAction(configmapsResource, configMap), &authz.ConfigMap{}) + if obj == nil { + return nil, err + } + return obj.(*authz.ConfigMap), err +} + +// Delete takes name of the configMap and deletes it. Returns an error if one occurs. +func (c *FakeConfigMaps) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewRootDeleteAction(configmapsResource, name), &authz.ConfigMap{}) + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeConfigMaps) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + action := testing.NewRootDeleteCollectionAction(configmapsResource, listOpts) + + _, err := c.Fake.Invokes(action, &authz.ConfigMapList{}) + return err +} + +// Patch applies the patch and returns the patched configMap. +func (c *FakeConfigMaps) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.ConfigMap, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootPatchSubresourceAction(configmapsResource, name, pt, data, subresources...), &authz.ConfigMap{}) + if obj == nil { + return nil, err + } + return obj.(*authz.ConfigMap), err +} diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_multiclusterrolebinding.go b/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_multiclusterrolebinding.go new file mode 100644 index 000000000..2af16adc8 --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_multiclusterrolebinding.go @@ -0,0 +1,136 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" + authz "tkestack.io/tke/api/authz" +) + +// FakeMultiClusterRoleBindings implements MultiClusterRoleBindingInterface +type FakeMultiClusterRoleBindings struct { + Fake *FakeAuthz + ns string +} + +var multiclusterrolebindingsResource = schema.GroupVersionResource{Group: "authz.tkestack.io", Version: "", Resource: "multiclusterrolebindings"} + +var multiclusterrolebindingsKind = schema.GroupVersionKind{Group: "authz.tkestack.io", Version: "", Kind: "MultiClusterRoleBinding"} + +// Get takes name of the multiClusterRoleBinding, and returns the corresponding multiClusterRoleBinding object, and an error if there is any. +func (c *FakeMultiClusterRoleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *authz.MultiClusterRoleBinding, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(multiclusterrolebindingsResource, c.ns, name), &authz.MultiClusterRoleBinding{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.MultiClusterRoleBinding), err +} + +// List takes label and field selectors, and returns the list of MultiClusterRoleBindings that match those selectors. +func (c *FakeMultiClusterRoleBindings) List(ctx context.Context, opts v1.ListOptions) (result *authz.MultiClusterRoleBindingList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(multiclusterrolebindingsResource, multiclusterrolebindingsKind, c.ns, opts), &authz.MultiClusterRoleBindingList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &authz.MultiClusterRoleBindingList{ListMeta: obj.(*authz.MultiClusterRoleBindingList).ListMeta} + for _, item := range obj.(*authz.MultiClusterRoleBindingList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested multiClusterRoleBindings. +func (c *FakeMultiClusterRoleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(multiclusterrolebindingsResource, c.ns, opts)) + +} + +// Create takes the representation of a multiClusterRoleBinding and creates it. Returns the server's representation of the multiClusterRoleBinding, and an error, if there is any. +func (c *FakeMultiClusterRoleBindings) Create(ctx context.Context, multiClusterRoleBinding *authz.MultiClusterRoleBinding, opts v1.CreateOptions) (result *authz.MultiClusterRoleBinding, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(multiclusterrolebindingsResource, c.ns, multiClusterRoleBinding), &authz.MultiClusterRoleBinding{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.MultiClusterRoleBinding), err +} + +// Update takes the representation of a multiClusterRoleBinding and updates it. Returns the server's representation of the multiClusterRoleBinding, and an error, if there is any. +func (c *FakeMultiClusterRoleBindings) Update(ctx context.Context, multiClusterRoleBinding *authz.MultiClusterRoleBinding, opts v1.UpdateOptions) (result *authz.MultiClusterRoleBinding, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(multiclusterrolebindingsResource, c.ns, multiClusterRoleBinding), &authz.MultiClusterRoleBinding{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.MultiClusterRoleBinding), err +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *FakeMultiClusterRoleBindings) UpdateStatus(ctx context.Context, multiClusterRoleBinding *authz.MultiClusterRoleBinding, opts v1.UpdateOptions) (*authz.MultiClusterRoleBinding, error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateSubresourceAction(multiclusterrolebindingsResource, "status", c.ns, multiClusterRoleBinding), &authz.MultiClusterRoleBinding{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.MultiClusterRoleBinding), err +} + +// Delete takes name of the multiClusterRoleBinding and deletes it. Returns an error if one occurs. +func (c *FakeMultiClusterRoleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(multiclusterrolebindingsResource, c.ns, name), &authz.MultiClusterRoleBinding{}) + + return err +} + +// Patch applies the patch and returns the patched multiClusterRoleBinding. +func (c *FakeMultiClusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.MultiClusterRoleBinding, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(multiclusterrolebindingsResource, c.ns, name, pt, data, subresources...), &authz.MultiClusterRoleBinding{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.MultiClusterRoleBinding), err +} diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_policy.go b/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_policy.go new file mode 100644 index 000000000..fc59239b9 --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_policy.go @@ -0,0 +1,124 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" + authz "tkestack.io/tke/api/authz" +) + +// FakePolicies implements PolicyInterface +type FakePolicies struct { + Fake *FakeAuthz + ns string +} + +var policiesResource = schema.GroupVersionResource{Group: "authz.tkestack.io", Version: "", Resource: "policies"} + +var policiesKind = schema.GroupVersionKind{Group: "authz.tkestack.io", Version: "", Kind: "Policy"} + +// Get takes name of the policy, and returns the corresponding policy object, and an error if there is any. +func (c *FakePolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *authz.Policy, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(policiesResource, c.ns, name), &authz.Policy{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.Policy), err +} + +// List takes label and field selectors, and returns the list of Policies that match those selectors. +func (c *FakePolicies) List(ctx context.Context, opts v1.ListOptions) (result *authz.PolicyList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(policiesResource, policiesKind, c.ns, opts), &authz.PolicyList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &authz.PolicyList{ListMeta: obj.(*authz.PolicyList).ListMeta} + for _, item := range obj.(*authz.PolicyList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested policies. +func (c *FakePolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(policiesResource, c.ns, opts)) + +} + +// Create takes the representation of a policy and creates it. Returns the server's representation of the policy, and an error, if there is any. +func (c *FakePolicies) Create(ctx context.Context, policy *authz.Policy, opts v1.CreateOptions) (result *authz.Policy, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(policiesResource, c.ns, policy), &authz.Policy{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.Policy), err +} + +// Update takes the representation of a policy and updates it. Returns the server's representation of the policy, and an error, if there is any. +func (c *FakePolicies) Update(ctx context.Context, policy *authz.Policy, opts v1.UpdateOptions) (result *authz.Policy, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(policiesResource, c.ns, policy), &authz.Policy{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.Policy), err +} + +// Delete takes name of the policy and deletes it. Returns an error if one occurs. +func (c *FakePolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(policiesResource, c.ns, name), &authz.Policy{}) + + return err +} + +// Patch applies the patch and returns the patched policy. +func (c *FakePolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.Policy, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(policiesResource, c.ns, name, pt, data, subresources...), &authz.Policy{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.Policy), err +} diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_role.go b/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_role.go new file mode 100644 index 000000000..31be48435 --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/fake/fake_role.go @@ -0,0 +1,124 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" + authz "tkestack.io/tke/api/authz" +) + +// FakeRoles implements RoleInterface +type FakeRoles struct { + Fake *FakeAuthz + ns string +} + +var rolesResource = schema.GroupVersionResource{Group: "authz.tkestack.io", Version: "", Resource: "roles"} + +var rolesKind = schema.GroupVersionKind{Group: "authz.tkestack.io", Version: "", Kind: "Role"} + +// Get takes name of the role, and returns the corresponding role object, and an error if there is any. +func (c *FakeRoles) Get(ctx context.Context, name string, options v1.GetOptions) (result *authz.Role, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(rolesResource, c.ns, name), &authz.Role{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.Role), err +} + +// List takes label and field selectors, and returns the list of Roles that match those selectors. +func (c *FakeRoles) List(ctx context.Context, opts v1.ListOptions) (result *authz.RoleList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(rolesResource, rolesKind, c.ns, opts), &authz.RoleList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &authz.RoleList{ListMeta: obj.(*authz.RoleList).ListMeta} + for _, item := range obj.(*authz.RoleList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested roles. +func (c *FakeRoles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(rolesResource, c.ns, opts)) + +} + +// Create takes the representation of a role and creates it. Returns the server's representation of the role, and an error, if there is any. +func (c *FakeRoles) Create(ctx context.Context, role *authz.Role, opts v1.CreateOptions) (result *authz.Role, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(rolesResource, c.ns, role), &authz.Role{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.Role), err +} + +// Update takes the representation of a role and updates it. Returns the server's representation of the role, and an error, if there is any. +func (c *FakeRoles) Update(ctx context.Context, role *authz.Role, opts v1.UpdateOptions) (result *authz.Role, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(rolesResource, c.ns, role), &authz.Role{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.Role), err +} + +// Delete takes name of the role and deletes it. Returns an error if one occurs. +func (c *FakeRoles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(rolesResource, c.ns, name), &authz.Role{}) + + return err +} + +// Patch applies the patch and returns the patched role. +func (c *FakeRoles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.Role, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(rolesResource, c.ns, name, pt, data, subresources...), &authz.Role{}) + + if obj == nil { + return nil, err + } + return obj.(*authz.Role), err +} diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/generated_expansion.go b/api/client/clientset/internalversion/typed/authz/internalversion/generated_expansion.go new file mode 100644 index 000000000..40a3bb7a8 --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/generated_expansion.go @@ -0,0 +1,29 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package internalversion + +type ConfigMapExpansion interface{} + +type MultiClusterRoleBindingExpansion interface{} + +type PolicyExpansion interface{} + +type RoleExpansion interface{} diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/multiclusterrolebinding.go b/api/client/clientset/internalversion/typed/authz/internalversion/multiclusterrolebinding.go new file mode 100644 index 000000000..6c4ffab3a --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/multiclusterrolebinding.go @@ -0,0 +1,180 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package internalversion + +import ( + "context" + "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" + authz "tkestack.io/tke/api/authz" + scheme "tkestack.io/tke/api/client/clientset/internalversion/scheme" +) + +// MultiClusterRoleBindingsGetter has a method to return a MultiClusterRoleBindingInterface. +// A group's client should implement this interface. +type MultiClusterRoleBindingsGetter interface { + MultiClusterRoleBindings(namespace string) MultiClusterRoleBindingInterface +} + +// MultiClusterRoleBindingInterface has methods to work with MultiClusterRoleBinding resources. +type MultiClusterRoleBindingInterface interface { + Create(ctx context.Context, multiClusterRoleBinding *authz.MultiClusterRoleBinding, opts v1.CreateOptions) (*authz.MultiClusterRoleBinding, error) + Update(ctx context.Context, multiClusterRoleBinding *authz.MultiClusterRoleBinding, opts v1.UpdateOptions) (*authz.MultiClusterRoleBinding, error) + UpdateStatus(ctx context.Context, multiClusterRoleBinding *authz.MultiClusterRoleBinding, opts v1.UpdateOptions) (*authz.MultiClusterRoleBinding, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*authz.MultiClusterRoleBinding, error) + List(ctx context.Context, opts v1.ListOptions) (*authz.MultiClusterRoleBindingList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.MultiClusterRoleBinding, err error) + MultiClusterRoleBindingExpansion +} + +// multiClusterRoleBindings implements MultiClusterRoleBindingInterface +type multiClusterRoleBindings struct { + client rest.Interface + ns string +} + +// newMultiClusterRoleBindings returns a MultiClusterRoleBindings +func newMultiClusterRoleBindings(c *AuthzClient, namespace string) *multiClusterRoleBindings { + return &multiClusterRoleBindings{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the multiClusterRoleBinding, and returns the corresponding multiClusterRoleBinding object, and an error if there is any. +func (c *multiClusterRoleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *authz.MultiClusterRoleBinding, err error) { + result = &authz.MultiClusterRoleBinding{} + err = c.client.Get(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of MultiClusterRoleBindings that match those selectors. +func (c *multiClusterRoleBindings) List(ctx context.Context, opts v1.ListOptions) (result *authz.MultiClusterRoleBindingList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &authz.MultiClusterRoleBindingList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested multiClusterRoleBindings. +func (c *multiClusterRoleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a multiClusterRoleBinding and creates it. Returns the server's representation of the multiClusterRoleBinding, and an error, if there is any. +func (c *multiClusterRoleBindings) Create(ctx context.Context, multiClusterRoleBinding *authz.MultiClusterRoleBinding, opts v1.CreateOptions) (result *authz.MultiClusterRoleBinding, err error) { + result = &authz.MultiClusterRoleBinding{} + err = c.client.Post(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(multiClusterRoleBinding). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a multiClusterRoleBinding and updates it. Returns the server's representation of the multiClusterRoleBinding, and an error, if there is any. +func (c *multiClusterRoleBindings) Update(ctx context.Context, multiClusterRoleBinding *authz.MultiClusterRoleBinding, opts v1.UpdateOptions) (result *authz.MultiClusterRoleBinding, err error) { + result = &authz.MultiClusterRoleBinding{} + err = c.client.Put(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + Name(multiClusterRoleBinding.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(multiClusterRoleBinding). + Do(ctx). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *multiClusterRoleBindings) UpdateStatus(ctx context.Context, multiClusterRoleBinding *authz.MultiClusterRoleBinding, opts v1.UpdateOptions) (result *authz.MultiClusterRoleBinding, err error) { + result = &authz.MultiClusterRoleBinding{} + err = c.client.Put(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + Name(multiClusterRoleBinding.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(multiClusterRoleBinding). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the multiClusterRoleBinding and deletes it. Returns an error if one occurs. +func (c *multiClusterRoleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched multiClusterRoleBinding. +func (c *multiClusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.MultiClusterRoleBinding, err error) { + result = &authz.MultiClusterRoleBinding{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/policy.go b/api/client/clientset/internalversion/typed/authz/internalversion/policy.go new file mode 100644 index 000000000..ba325cef7 --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/policy.go @@ -0,0 +1,163 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package internalversion + +import ( + "context" + "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" + authz "tkestack.io/tke/api/authz" + scheme "tkestack.io/tke/api/client/clientset/internalversion/scheme" +) + +// PoliciesGetter has a method to return a PolicyInterface. +// A group's client should implement this interface. +type PoliciesGetter interface { + Policies(namespace string) PolicyInterface +} + +// PolicyInterface has methods to work with Policy resources. +type PolicyInterface interface { + Create(ctx context.Context, policy *authz.Policy, opts v1.CreateOptions) (*authz.Policy, error) + Update(ctx context.Context, policy *authz.Policy, opts v1.UpdateOptions) (*authz.Policy, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*authz.Policy, error) + List(ctx context.Context, opts v1.ListOptions) (*authz.PolicyList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.Policy, err error) + PolicyExpansion +} + +// policies implements PolicyInterface +type policies struct { + client rest.Interface + ns string +} + +// newPolicies returns a Policies +func newPolicies(c *AuthzClient, namespace string) *policies { + return &policies{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the policy, and returns the corresponding policy object, and an error if there is any. +func (c *policies) Get(ctx context.Context, name string, options v1.GetOptions) (result *authz.Policy, err error) { + result = &authz.Policy{} + err = c.client.Get(). + Namespace(c.ns). + Resource("policies"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of Policies that match those selectors. +func (c *policies) List(ctx context.Context, opts v1.ListOptions) (result *authz.PolicyList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &authz.PolicyList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("policies"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested policies. +func (c *policies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("policies"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a policy and creates it. Returns the server's representation of the policy, and an error, if there is any. +func (c *policies) Create(ctx context.Context, policy *authz.Policy, opts v1.CreateOptions) (result *authz.Policy, err error) { + result = &authz.Policy{} + err = c.client.Post(). + Namespace(c.ns). + Resource("policies"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(policy). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a policy and updates it. Returns the server's representation of the policy, and an error, if there is any. +func (c *policies) Update(ctx context.Context, policy *authz.Policy, opts v1.UpdateOptions) (result *authz.Policy, err error) { + result = &authz.Policy{} + err = c.client.Put(). + Namespace(c.ns). + Resource("policies"). + Name(policy.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(policy). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the policy and deletes it. Returns an error if one occurs. +func (c *policies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("policies"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched policy. +func (c *policies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.Policy, err error) { + result = &authz.Policy{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("policies"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/api/client/clientset/internalversion/typed/authz/internalversion/role.go b/api/client/clientset/internalversion/typed/authz/internalversion/role.go new file mode 100644 index 000000000..cc40acd8a --- /dev/null +++ b/api/client/clientset/internalversion/typed/authz/internalversion/role.go @@ -0,0 +1,163 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package internalversion + +import ( + "context" + "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" + authz "tkestack.io/tke/api/authz" + scheme "tkestack.io/tke/api/client/clientset/internalversion/scheme" +) + +// RolesGetter has a method to return a RoleInterface. +// A group's client should implement this interface. +type RolesGetter interface { + Roles(namespace string) RoleInterface +} + +// RoleInterface has methods to work with Role resources. +type RoleInterface interface { + Create(ctx context.Context, role *authz.Role, opts v1.CreateOptions) (*authz.Role, error) + Update(ctx context.Context, role *authz.Role, opts v1.UpdateOptions) (*authz.Role, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*authz.Role, error) + List(ctx context.Context, opts v1.ListOptions) (*authz.RoleList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.Role, err error) + RoleExpansion +} + +// roles implements RoleInterface +type roles struct { + client rest.Interface + ns string +} + +// newRoles returns a Roles +func newRoles(c *AuthzClient, namespace string) *roles { + return &roles{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the role, and returns the corresponding role object, and an error if there is any. +func (c *roles) Get(ctx context.Context, name string, options v1.GetOptions) (result *authz.Role, err error) { + result = &authz.Role{} + err = c.client.Get(). + Namespace(c.ns). + Resource("roles"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of Roles that match those selectors. +func (c *roles) List(ctx context.Context, opts v1.ListOptions) (result *authz.RoleList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &authz.RoleList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("roles"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested roles. +func (c *roles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("roles"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a role and creates it. Returns the server's representation of the role, and an error, if there is any. +func (c *roles) Create(ctx context.Context, role *authz.Role, opts v1.CreateOptions) (result *authz.Role, err error) { + result = &authz.Role{} + err = c.client.Post(). + Namespace(c.ns). + Resource("roles"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(role). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a role and updates it. Returns the server's representation of the role, and an error, if there is any. +func (c *roles) Update(ctx context.Context, role *authz.Role, opts v1.UpdateOptions) (result *authz.Role, err error) { + result = &authz.Role{} + err = c.client.Put(). + Namespace(c.ns). + Resource("roles"). + Name(role.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(role). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the role and deletes it. Returns an error if one occurs. +func (c *roles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("roles"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched role. +func (c *roles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authz.Role, err error) { + result = &authz.Role{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("roles"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/api/client/clientset/versioned/clientset.go b/api/client/clientset/versioned/clientset.go index 260a4cd66..c5eb4acdf 100644 --- a/api/client/clientset/versioned/clientset.go +++ b/api/client/clientset/versioned/clientset.go @@ -28,6 +28,7 @@ import ( flowcontrol "k8s.io/client-go/util/flowcontrol" applicationv1 "tkestack.io/tke/api/client/clientset/versioned/typed/application/v1" authv1 "tkestack.io/tke/api/client/clientset/versioned/typed/auth/v1" + authzv1 "tkestack.io/tke/api/client/clientset/versioned/typed/authz/v1" businessv1 "tkestack.io/tke/api/client/clientset/versioned/typed/business/v1" logagentv1 "tkestack.io/tke/api/client/clientset/versioned/typed/logagent/v1" meshv1 "tkestack.io/tke/api/client/clientset/versioned/typed/mesh/v1" @@ -41,6 +42,7 @@ type Interface interface { Discovery() discovery.DiscoveryInterface ApplicationV1() applicationv1.ApplicationV1Interface AuthV1() authv1.AuthV1Interface + AuthzV1() authzv1.AuthzV1Interface BusinessV1() businessv1.BusinessV1Interface LogagentV1() logagentv1.LogagentV1Interface MeshV1() meshv1.MeshV1Interface @@ -56,6 +58,7 @@ type Clientset struct { *discovery.DiscoveryClient applicationV1 *applicationv1.ApplicationV1Client authV1 *authv1.AuthV1Client + authzV1 *authzv1.AuthzV1Client businessV1 *businessv1.BusinessV1Client logagentV1 *logagentv1.LogagentV1Client meshV1 *meshv1.MeshV1Client @@ -75,6 +78,11 @@ func (c *Clientset) AuthV1() authv1.AuthV1Interface { return c.authV1 } +// AuthzV1 retrieves the AuthzV1Client +func (c *Clientset) AuthzV1() authzv1.AuthzV1Interface { + return c.authzV1 +} + // BusinessV1 retrieves the BusinessV1Client func (c *Clientset) BusinessV1() businessv1.BusinessV1Interface { return c.businessV1 @@ -139,6 +147,10 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { if err != nil { return nil, err } + cs.authzV1, err = authzv1.NewForConfig(&configShallowCopy) + if err != nil { + return nil, err + } cs.businessV1, err = businessv1.NewForConfig(&configShallowCopy) if err != nil { return nil, err @@ -181,6 +193,7 @@ func NewForConfigOrDie(c *rest.Config) *Clientset { var cs Clientset cs.applicationV1 = applicationv1.NewForConfigOrDie(c) cs.authV1 = authv1.NewForConfigOrDie(c) + cs.authzV1 = authzv1.NewForConfigOrDie(c) cs.businessV1 = businessv1.NewForConfigOrDie(c) cs.logagentV1 = logagentv1.NewForConfigOrDie(c) cs.meshV1 = meshv1.NewForConfigOrDie(c) @@ -198,6 +211,7 @@ func New(c rest.Interface) *Clientset { var cs Clientset cs.applicationV1 = applicationv1.New(c) cs.authV1 = authv1.New(c) + cs.authzV1 = authzv1.New(c) cs.businessV1 = businessv1.New(c) cs.logagentV1 = logagentv1.New(c) cs.meshV1 = meshv1.New(c) diff --git a/api/client/clientset/versioned/fake/clientset_generated.go b/api/client/clientset/versioned/fake/clientset_generated.go index e7f11ec9e..4169f11df 100644 --- a/api/client/clientset/versioned/fake/clientset_generated.go +++ b/api/client/clientset/versioned/fake/clientset_generated.go @@ -31,6 +31,8 @@ import ( fakeapplicationv1 "tkestack.io/tke/api/client/clientset/versioned/typed/application/v1/fake" authv1 "tkestack.io/tke/api/client/clientset/versioned/typed/auth/v1" fakeauthv1 "tkestack.io/tke/api/client/clientset/versioned/typed/auth/v1/fake" + authzv1 "tkestack.io/tke/api/client/clientset/versioned/typed/authz/v1" + fakeauthzv1 "tkestack.io/tke/api/client/clientset/versioned/typed/authz/v1/fake" businessv1 "tkestack.io/tke/api/client/clientset/versioned/typed/business/v1" fakebusinessv1 "tkestack.io/tke/api/client/clientset/versioned/typed/business/v1/fake" logagentv1 "tkestack.io/tke/api/client/clientset/versioned/typed/logagent/v1" @@ -107,6 +109,11 @@ func (c *Clientset) AuthV1() authv1.AuthV1Interface { return &fakeauthv1.FakeAuthV1{Fake: &c.Fake} } +// AuthzV1 retrieves the AuthzV1Client +func (c *Clientset) AuthzV1() authzv1.AuthzV1Interface { + return &fakeauthzv1.FakeAuthzV1{Fake: &c.Fake} +} + // BusinessV1 retrieves the BusinessV1Client func (c *Clientset) BusinessV1() businessv1.BusinessV1Interface { return &fakebusinessv1.FakeBusinessV1{Fake: &c.Fake} diff --git a/api/client/clientset/versioned/fake/register.go b/api/client/clientset/versioned/fake/register.go index 160d094e3..ca91b7e7a 100644 --- a/api/client/clientset/versioned/fake/register.go +++ b/api/client/clientset/versioned/fake/register.go @@ -28,6 +28,7 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" applicationv1 "tkestack.io/tke/api/application/v1" authv1 "tkestack.io/tke/api/auth/v1" + authzv1 "tkestack.io/tke/api/authz/v1" businessv1 "tkestack.io/tke/api/business/v1" logagentv1 "tkestack.io/tke/api/logagent/v1" meshv1 "tkestack.io/tke/api/mesh/v1" @@ -43,6 +44,7 @@ var codecs = serializer.NewCodecFactory(scheme) var localSchemeBuilder = runtime.SchemeBuilder{ applicationv1.AddToScheme, authv1.AddToScheme, + authzv1.AddToScheme, businessv1.AddToScheme, logagentv1.AddToScheme, meshv1.AddToScheme, diff --git a/api/client/clientset/versioned/scheme/register.go b/api/client/clientset/versioned/scheme/register.go index 37e760793..a973a09ac 100644 --- a/api/client/clientset/versioned/scheme/register.go +++ b/api/client/clientset/versioned/scheme/register.go @@ -28,6 +28,7 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" applicationv1 "tkestack.io/tke/api/application/v1" authv1 "tkestack.io/tke/api/auth/v1" + authzv1 "tkestack.io/tke/api/authz/v1" businessv1 "tkestack.io/tke/api/business/v1" logagentv1 "tkestack.io/tke/api/logagent/v1" meshv1 "tkestack.io/tke/api/mesh/v1" @@ -43,6 +44,7 @@ var ParameterCodec = runtime.NewParameterCodec(Scheme) var localSchemeBuilder = runtime.SchemeBuilder{ applicationv1.AddToScheme, authv1.AddToScheme, + authzv1.AddToScheme, businessv1.AddToScheme, logagentv1.AddToScheme, meshv1.AddToScheme, diff --git a/api/client/clientset/versioned/typed/authz/v1/authz_client.go b/api/client/clientset/versioned/typed/authz/v1/authz_client.go new file mode 100644 index 000000000..c7edde21b --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/authz_client.go @@ -0,0 +1,106 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + rest "k8s.io/client-go/rest" + v1 "tkestack.io/tke/api/authz/v1" + "tkestack.io/tke/api/client/clientset/versioned/scheme" +) + +type AuthzV1Interface interface { + RESTClient() rest.Interface + ConfigMapsGetter + MultiClusterRoleBindingsGetter + PoliciesGetter + RolesGetter +} + +// AuthzV1Client is used to interact with features provided by the authz.tkestack.io group. +type AuthzV1Client struct { + restClient rest.Interface +} + +func (c *AuthzV1Client) ConfigMaps() ConfigMapInterface { + return newConfigMaps(c) +} + +func (c *AuthzV1Client) MultiClusterRoleBindings(namespace string) MultiClusterRoleBindingInterface { + return newMultiClusterRoleBindings(c, namespace) +} + +func (c *AuthzV1Client) Policies(namespace string) PolicyInterface { + return newPolicies(c, namespace) +} + +func (c *AuthzV1Client) Roles(namespace string) RoleInterface { + return newRoles(c, namespace) +} + +// NewForConfig creates a new AuthzV1Client for the given config. +func NewForConfig(c *rest.Config) (*AuthzV1Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientFor(&config) + if err != nil { + return nil, err + } + return &AuthzV1Client{client}, nil +} + +// NewForConfigOrDie creates a new AuthzV1Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *AuthzV1Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new AuthzV1Client for the given RESTClient. +func New(c rest.Interface) *AuthzV1Client { + return &AuthzV1Client{c} +} + +func setConfigDefaults(config *rest.Config) error { + gv := v1.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + + if config.UserAgent == "" { + config.UserAgent = rest.DefaultKubernetesUserAgent() + } + + return nil +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *AuthzV1Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/api/client/clientset/versioned/typed/authz/v1/configmap.go b/api/client/clientset/versioned/typed/authz/v1/configmap.go new file mode 100644 index 000000000..93ea0fc57 --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/configmap.go @@ -0,0 +1,154 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" + v1 "tkestack.io/tke/api/authz/v1" + scheme "tkestack.io/tke/api/client/clientset/versioned/scheme" +) + +// ConfigMapsGetter has a method to return a ConfigMapInterface. +// A group's client should implement this interface. +type ConfigMapsGetter interface { + ConfigMaps() ConfigMapInterface +} + +// ConfigMapInterface has methods to work with ConfigMap resources. +type ConfigMapInterface interface { + Create(ctx context.Context, configMap *v1.ConfigMap, opts metav1.CreateOptions) (*v1.ConfigMap, error) + Update(ctx context.Context, configMap *v1.ConfigMap, opts metav1.UpdateOptions) (*v1.ConfigMap, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.ConfigMap, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.ConfigMapList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ConfigMap, err error) + ConfigMapExpansion +} + +// configMaps implements ConfigMapInterface +type configMaps struct { + client rest.Interface +} + +// newConfigMaps returns a ConfigMaps +func newConfigMaps(c *AuthzV1Client) *configMaps { + return &configMaps{ + client: c.RESTClient(), + } +} + +// Get takes name of the configMap, and returns the corresponding configMap object, and an error if there is any. +func (c *configMaps) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ConfigMap, err error) { + result = &v1.ConfigMap{} + err = c.client.Get(). + Resource("configmaps"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of ConfigMaps that match those selectors. +func (c *configMaps) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ConfigMapList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.ConfigMapList{} + err = c.client.Get(). + Resource("configmaps"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested configMaps. +func (c *configMaps) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Resource("configmaps"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a configMap and creates it. Returns the server's representation of the configMap, and an error, if there is any. +func (c *configMaps) Create(ctx context.Context, configMap *v1.ConfigMap, opts metav1.CreateOptions) (result *v1.ConfigMap, err error) { + result = &v1.ConfigMap{} + err = c.client.Post(). + Resource("configmaps"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(configMap). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a configMap and updates it. Returns the server's representation of the configMap, and an error, if there is any. +func (c *configMaps) Update(ctx context.Context, configMap *v1.ConfigMap, opts metav1.UpdateOptions) (result *v1.ConfigMap, err error) { + result = &v1.ConfigMap{} + err = c.client.Put(). + Resource("configmaps"). + Name(configMap.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(configMap). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the configMap and deletes it. Returns an error if one occurs. +func (c *configMaps) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Resource("configmaps"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched configMap. +func (c *configMaps) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ConfigMap, err error) { + result = &v1.ConfigMap{} + err = c.client.Patch(pt). + Resource("configmaps"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/api/client/clientset/versioned/typed/authz/v1/doc.go b/api/client/clientset/versioned/typed/authz/v1/doc.go new file mode 100644 index 000000000..8bdb888fc --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/doc.go @@ -0,0 +1,22 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +// This package has the automatically generated typed clients. +package v1 diff --git a/api/client/clientset/versioned/typed/authz/v1/fake/doc.go b/api/client/clientset/versioned/typed/authz/v1/fake/doc.go new file mode 100644 index 000000000..d4bb4b09f --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/fake/doc.go @@ -0,0 +1,22 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +// Package fake has the automatically generated clients. +package fake diff --git a/api/client/clientset/versioned/typed/authz/v1/fake/fake_authz_client.go b/api/client/clientset/versioned/typed/authz/v1/fake/fake_authz_client.go new file mode 100644 index 000000000..e72b75626 --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/fake/fake_authz_client.go @@ -0,0 +1,54 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + rest "k8s.io/client-go/rest" + testing "k8s.io/client-go/testing" + v1 "tkestack.io/tke/api/client/clientset/versioned/typed/authz/v1" +) + +type FakeAuthzV1 struct { + *testing.Fake +} + +func (c *FakeAuthzV1) ConfigMaps() v1.ConfigMapInterface { + return &FakeConfigMaps{c} +} + +func (c *FakeAuthzV1) MultiClusterRoleBindings(namespace string) v1.MultiClusterRoleBindingInterface { + return &FakeMultiClusterRoleBindings{c, namespace} +} + +func (c *FakeAuthzV1) Policies(namespace string) v1.PolicyInterface { + return &FakePolicies{c, namespace} +} + +func (c *FakeAuthzV1) Roles(namespace string) v1.RoleInterface { + return &FakeRoles{c, namespace} +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *FakeAuthzV1) RESTClient() rest.Interface { + var ret *rest.RESTClient + return ret +} diff --git a/api/client/clientset/versioned/typed/authz/v1/fake/fake_configmap.go b/api/client/clientset/versioned/typed/authz/v1/fake/fake_configmap.go new file mode 100644 index 000000000..44f2c902e --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/fake/fake_configmap.go @@ -0,0 +1,116 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" + authzv1 "tkestack.io/tke/api/authz/v1" +) + +// FakeConfigMaps implements ConfigMapInterface +type FakeConfigMaps struct { + Fake *FakeAuthzV1 +} + +var configmapsResource = schema.GroupVersionResource{Group: "authz.tkestack.io", Version: "v1", Resource: "configmaps"} + +var configmapsKind = schema.GroupVersionKind{Group: "authz.tkestack.io", Version: "v1", Kind: "ConfigMap"} + +// Get takes name of the configMap, and returns the corresponding configMap object, and an error if there is any. +func (c *FakeConfigMaps) Get(ctx context.Context, name string, options v1.GetOptions) (result *authzv1.ConfigMap, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootGetAction(configmapsResource, name), &authzv1.ConfigMap{}) + if obj == nil { + return nil, err + } + return obj.(*authzv1.ConfigMap), err +} + +// List takes label and field selectors, and returns the list of ConfigMaps that match those selectors. +func (c *FakeConfigMaps) List(ctx context.Context, opts v1.ListOptions) (result *authzv1.ConfigMapList, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootListAction(configmapsResource, configmapsKind, opts), &authzv1.ConfigMapList{}) + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &authzv1.ConfigMapList{ListMeta: obj.(*authzv1.ConfigMapList).ListMeta} + for _, item := range obj.(*authzv1.ConfigMapList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested configMaps. +func (c *FakeConfigMaps) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewRootWatchAction(configmapsResource, opts)) +} + +// Create takes the representation of a configMap and creates it. Returns the server's representation of the configMap, and an error, if there is any. +func (c *FakeConfigMaps) Create(ctx context.Context, configMap *authzv1.ConfigMap, opts v1.CreateOptions) (result *authzv1.ConfigMap, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootCreateAction(configmapsResource, configMap), &authzv1.ConfigMap{}) + if obj == nil { + return nil, err + } + return obj.(*authzv1.ConfigMap), err +} + +// Update takes the representation of a configMap and updates it. Returns the server's representation of the configMap, and an error, if there is any. +func (c *FakeConfigMaps) Update(ctx context.Context, configMap *authzv1.ConfigMap, opts v1.UpdateOptions) (result *authzv1.ConfigMap, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootUpdateAction(configmapsResource, configMap), &authzv1.ConfigMap{}) + if obj == nil { + return nil, err + } + return obj.(*authzv1.ConfigMap), err +} + +// Delete takes name of the configMap and deletes it. Returns an error if one occurs. +func (c *FakeConfigMaps) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewRootDeleteAction(configmapsResource, name), &authzv1.ConfigMap{}) + return err +} + +// Patch applies the patch and returns the patched configMap. +func (c *FakeConfigMaps) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authzv1.ConfigMap, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootPatchSubresourceAction(configmapsResource, name, pt, data, subresources...), &authzv1.ConfigMap{}) + if obj == nil { + return nil, err + } + return obj.(*authzv1.ConfigMap), err +} diff --git a/api/client/clientset/versioned/typed/authz/v1/fake/fake_multiclusterrolebinding.go b/api/client/clientset/versioned/typed/authz/v1/fake/fake_multiclusterrolebinding.go new file mode 100644 index 000000000..da733602a --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/fake/fake_multiclusterrolebinding.go @@ -0,0 +1,136 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" + authzv1 "tkestack.io/tke/api/authz/v1" +) + +// FakeMultiClusterRoleBindings implements MultiClusterRoleBindingInterface +type FakeMultiClusterRoleBindings struct { + Fake *FakeAuthzV1 + ns string +} + +var multiclusterrolebindingsResource = schema.GroupVersionResource{Group: "authz.tkestack.io", Version: "v1", Resource: "multiclusterrolebindings"} + +var multiclusterrolebindingsKind = schema.GroupVersionKind{Group: "authz.tkestack.io", Version: "v1", Kind: "MultiClusterRoleBinding"} + +// Get takes name of the multiClusterRoleBinding, and returns the corresponding multiClusterRoleBinding object, and an error if there is any. +func (c *FakeMultiClusterRoleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *authzv1.MultiClusterRoleBinding, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(multiclusterrolebindingsResource, c.ns, name), &authzv1.MultiClusterRoleBinding{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.MultiClusterRoleBinding), err +} + +// List takes label and field selectors, and returns the list of MultiClusterRoleBindings that match those selectors. +func (c *FakeMultiClusterRoleBindings) List(ctx context.Context, opts v1.ListOptions) (result *authzv1.MultiClusterRoleBindingList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(multiclusterrolebindingsResource, multiclusterrolebindingsKind, c.ns, opts), &authzv1.MultiClusterRoleBindingList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &authzv1.MultiClusterRoleBindingList{ListMeta: obj.(*authzv1.MultiClusterRoleBindingList).ListMeta} + for _, item := range obj.(*authzv1.MultiClusterRoleBindingList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested multiClusterRoleBindings. +func (c *FakeMultiClusterRoleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(multiclusterrolebindingsResource, c.ns, opts)) + +} + +// Create takes the representation of a multiClusterRoleBinding and creates it. Returns the server's representation of the multiClusterRoleBinding, and an error, if there is any. +func (c *FakeMultiClusterRoleBindings) Create(ctx context.Context, multiClusterRoleBinding *authzv1.MultiClusterRoleBinding, opts v1.CreateOptions) (result *authzv1.MultiClusterRoleBinding, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(multiclusterrolebindingsResource, c.ns, multiClusterRoleBinding), &authzv1.MultiClusterRoleBinding{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.MultiClusterRoleBinding), err +} + +// Update takes the representation of a multiClusterRoleBinding and updates it. Returns the server's representation of the multiClusterRoleBinding, and an error, if there is any. +func (c *FakeMultiClusterRoleBindings) Update(ctx context.Context, multiClusterRoleBinding *authzv1.MultiClusterRoleBinding, opts v1.UpdateOptions) (result *authzv1.MultiClusterRoleBinding, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(multiclusterrolebindingsResource, c.ns, multiClusterRoleBinding), &authzv1.MultiClusterRoleBinding{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.MultiClusterRoleBinding), err +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *FakeMultiClusterRoleBindings) UpdateStatus(ctx context.Context, multiClusterRoleBinding *authzv1.MultiClusterRoleBinding, opts v1.UpdateOptions) (*authzv1.MultiClusterRoleBinding, error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateSubresourceAction(multiclusterrolebindingsResource, "status", c.ns, multiClusterRoleBinding), &authzv1.MultiClusterRoleBinding{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.MultiClusterRoleBinding), err +} + +// Delete takes name of the multiClusterRoleBinding and deletes it. Returns an error if one occurs. +func (c *FakeMultiClusterRoleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(multiclusterrolebindingsResource, c.ns, name), &authzv1.MultiClusterRoleBinding{}) + + return err +} + +// Patch applies the patch and returns the patched multiClusterRoleBinding. +func (c *FakeMultiClusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authzv1.MultiClusterRoleBinding, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(multiclusterrolebindingsResource, c.ns, name, pt, data, subresources...), &authzv1.MultiClusterRoleBinding{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.MultiClusterRoleBinding), err +} diff --git a/api/client/clientset/versioned/typed/authz/v1/fake/fake_policy.go b/api/client/clientset/versioned/typed/authz/v1/fake/fake_policy.go new file mode 100644 index 000000000..8fdadbc72 --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/fake/fake_policy.go @@ -0,0 +1,124 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" + authzv1 "tkestack.io/tke/api/authz/v1" +) + +// FakePolicies implements PolicyInterface +type FakePolicies struct { + Fake *FakeAuthzV1 + ns string +} + +var policiesResource = schema.GroupVersionResource{Group: "authz.tkestack.io", Version: "v1", Resource: "policies"} + +var policiesKind = schema.GroupVersionKind{Group: "authz.tkestack.io", Version: "v1", Kind: "Policy"} + +// Get takes name of the policy, and returns the corresponding policy object, and an error if there is any. +func (c *FakePolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *authzv1.Policy, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(policiesResource, c.ns, name), &authzv1.Policy{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.Policy), err +} + +// List takes label and field selectors, and returns the list of Policies that match those selectors. +func (c *FakePolicies) List(ctx context.Context, opts v1.ListOptions) (result *authzv1.PolicyList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(policiesResource, policiesKind, c.ns, opts), &authzv1.PolicyList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &authzv1.PolicyList{ListMeta: obj.(*authzv1.PolicyList).ListMeta} + for _, item := range obj.(*authzv1.PolicyList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested policies. +func (c *FakePolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(policiesResource, c.ns, opts)) + +} + +// Create takes the representation of a policy and creates it. Returns the server's representation of the policy, and an error, if there is any. +func (c *FakePolicies) Create(ctx context.Context, policy *authzv1.Policy, opts v1.CreateOptions) (result *authzv1.Policy, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(policiesResource, c.ns, policy), &authzv1.Policy{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.Policy), err +} + +// Update takes the representation of a policy and updates it. Returns the server's representation of the policy, and an error, if there is any. +func (c *FakePolicies) Update(ctx context.Context, policy *authzv1.Policy, opts v1.UpdateOptions) (result *authzv1.Policy, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(policiesResource, c.ns, policy), &authzv1.Policy{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.Policy), err +} + +// Delete takes name of the policy and deletes it. Returns an error if one occurs. +func (c *FakePolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(policiesResource, c.ns, name), &authzv1.Policy{}) + + return err +} + +// Patch applies the patch and returns the patched policy. +func (c *FakePolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authzv1.Policy, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(policiesResource, c.ns, name, pt, data, subresources...), &authzv1.Policy{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.Policy), err +} diff --git a/api/client/clientset/versioned/typed/authz/v1/fake/fake_role.go b/api/client/clientset/versioned/typed/authz/v1/fake/fake_role.go new file mode 100644 index 000000000..2c2fc2b6a --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/fake/fake_role.go @@ -0,0 +1,124 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" + authzv1 "tkestack.io/tke/api/authz/v1" +) + +// FakeRoles implements RoleInterface +type FakeRoles struct { + Fake *FakeAuthzV1 + ns string +} + +var rolesResource = schema.GroupVersionResource{Group: "authz.tkestack.io", Version: "v1", Resource: "roles"} + +var rolesKind = schema.GroupVersionKind{Group: "authz.tkestack.io", Version: "v1", Kind: "Role"} + +// Get takes name of the role, and returns the corresponding role object, and an error if there is any. +func (c *FakeRoles) Get(ctx context.Context, name string, options v1.GetOptions) (result *authzv1.Role, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(rolesResource, c.ns, name), &authzv1.Role{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.Role), err +} + +// List takes label and field selectors, and returns the list of Roles that match those selectors. +func (c *FakeRoles) List(ctx context.Context, opts v1.ListOptions) (result *authzv1.RoleList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(rolesResource, rolesKind, c.ns, opts), &authzv1.RoleList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &authzv1.RoleList{ListMeta: obj.(*authzv1.RoleList).ListMeta} + for _, item := range obj.(*authzv1.RoleList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested roles. +func (c *FakeRoles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(rolesResource, c.ns, opts)) + +} + +// Create takes the representation of a role and creates it. Returns the server's representation of the role, and an error, if there is any. +func (c *FakeRoles) Create(ctx context.Context, role *authzv1.Role, opts v1.CreateOptions) (result *authzv1.Role, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(rolesResource, c.ns, role), &authzv1.Role{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.Role), err +} + +// Update takes the representation of a role and updates it. Returns the server's representation of the role, and an error, if there is any. +func (c *FakeRoles) Update(ctx context.Context, role *authzv1.Role, opts v1.UpdateOptions) (result *authzv1.Role, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(rolesResource, c.ns, role), &authzv1.Role{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.Role), err +} + +// Delete takes name of the role and deletes it. Returns an error if one occurs. +func (c *FakeRoles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(rolesResource, c.ns, name), &authzv1.Role{}) + + return err +} + +// Patch applies the patch and returns the patched role. +func (c *FakeRoles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *authzv1.Role, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(rolesResource, c.ns, name, pt, data, subresources...), &authzv1.Role{}) + + if obj == nil { + return nil, err + } + return obj.(*authzv1.Role), err +} diff --git a/api/client/clientset/versioned/typed/authz/v1/generated_expansion.go b/api/client/clientset/versioned/typed/authz/v1/generated_expansion.go new file mode 100644 index 000000000..d73c12a14 --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/generated_expansion.go @@ -0,0 +1,29 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +type ConfigMapExpansion interface{} + +type MultiClusterRoleBindingExpansion interface{} + +type PolicyExpansion interface{} + +type RoleExpansion interface{} diff --git a/api/client/clientset/versioned/typed/authz/v1/multiclusterrolebinding.go b/api/client/clientset/versioned/typed/authz/v1/multiclusterrolebinding.go new file mode 100644 index 000000000..4dd6b451f --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/multiclusterrolebinding.go @@ -0,0 +1,180 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" + v1 "tkestack.io/tke/api/authz/v1" + scheme "tkestack.io/tke/api/client/clientset/versioned/scheme" +) + +// MultiClusterRoleBindingsGetter has a method to return a MultiClusterRoleBindingInterface. +// A group's client should implement this interface. +type MultiClusterRoleBindingsGetter interface { + MultiClusterRoleBindings(namespace string) MultiClusterRoleBindingInterface +} + +// MultiClusterRoleBindingInterface has methods to work with MultiClusterRoleBinding resources. +type MultiClusterRoleBindingInterface interface { + Create(ctx context.Context, multiClusterRoleBinding *v1.MultiClusterRoleBinding, opts metav1.CreateOptions) (*v1.MultiClusterRoleBinding, error) + Update(ctx context.Context, multiClusterRoleBinding *v1.MultiClusterRoleBinding, opts metav1.UpdateOptions) (*v1.MultiClusterRoleBinding, error) + UpdateStatus(ctx context.Context, multiClusterRoleBinding *v1.MultiClusterRoleBinding, opts metav1.UpdateOptions) (*v1.MultiClusterRoleBinding, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.MultiClusterRoleBinding, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.MultiClusterRoleBindingList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.MultiClusterRoleBinding, err error) + MultiClusterRoleBindingExpansion +} + +// multiClusterRoleBindings implements MultiClusterRoleBindingInterface +type multiClusterRoleBindings struct { + client rest.Interface + ns string +} + +// newMultiClusterRoleBindings returns a MultiClusterRoleBindings +func newMultiClusterRoleBindings(c *AuthzV1Client, namespace string) *multiClusterRoleBindings { + return &multiClusterRoleBindings{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the multiClusterRoleBinding, and returns the corresponding multiClusterRoleBinding object, and an error if there is any. +func (c *multiClusterRoleBindings) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.MultiClusterRoleBinding, err error) { + result = &v1.MultiClusterRoleBinding{} + err = c.client.Get(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of MultiClusterRoleBindings that match those selectors. +func (c *multiClusterRoleBindings) List(ctx context.Context, opts metav1.ListOptions) (result *v1.MultiClusterRoleBindingList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.MultiClusterRoleBindingList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested multiClusterRoleBindings. +func (c *multiClusterRoleBindings) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a multiClusterRoleBinding and creates it. Returns the server's representation of the multiClusterRoleBinding, and an error, if there is any. +func (c *multiClusterRoleBindings) Create(ctx context.Context, multiClusterRoleBinding *v1.MultiClusterRoleBinding, opts metav1.CreateOptions) (result *v1.MultiClusterRoleBinding, err error) { + result = &v1.MultiClusterRoleBinding{} + err = c.client.Post(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(multiClusterRoleBinding). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a multiClusterRoleBinding and updates it. Returns the server's representation of the multiClusterRoleBinding, and an error, if there is any. +func (c *multiClusterRoleBindings) Update(ctx context.Context, multiClusterRoleBinding *v1.MultiClusterRoleBinding, opts metav1.UpdateOptions) (result *v1.MultiClusterRoleBinding, err error) { + result = &v1.MultiClusterRoleBinding{} + err = c.client.Put(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + Name(multiClusterRoleBinding.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(multiClusterRoleBinding). + Do(ctx). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *multiClusterRoleBindings) UpdateStatus(ctx context.Context, multiClusterRoleBinding *v1.MultiClusterRoleBinding, opts metav1.UpdateOptions) (result *v1.MultiClusterRoleBinding, err error) { + result = &v1.MultiClusterRoleBinding{} + err = c.client.Put(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + Name(multiClusterRoleBinding.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(multiClusterRoleBinding). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the multiClusterRoleBinding and deletes it. Returns an error if one occurs. +func (c *multiClusterRoleBindings) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched multiClusterRoleBinding. +func (c *multiClusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.MultiClusterRoleBinding, err error) { + result = &v1.MultiClusterRoleBinding{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("multiclusterrolebindings"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/api/client/clientset/versioned/typed/authz/v1/policy.go b/api/client/clientset/versioned/typed/authz/v1/policy.go new file mode 100644 index 000000000..9f963d565 --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/policy.go @@ -0,0 +1,163 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" + v1 "tkestack.io/tke/api/authz/v1" + scheme "tkestack.io/tke/api/client/clientset/versioned/scheme" +) + +// PoliciesGetter has a method to return a PolicyInterface. +// A group's client should implement this interface. +type PoliciesGetter interface { + Policies(namespace string) PolicyInterface +} + +// PolicyInterface has methods to work with Policy resources. +type PolicyInterface interface { + Create(ctx context.Context, policy *v1.Policy, opts metav1.CreateOptions) (*v1.Policy, error) + Update(ctx context.Context, policy *v1.Policy, opts metav1.UpdateOptions) (*v1.Policy, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Policy, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.PolicyList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Policy, err error) + PolicyExpansion +} + +// policies implements PolicyInterface +type policies struct { + client rest.Interface + ns string +} + +// newPolicies returns a Policies +func newPolicies(c *AuthzV1Client, namespace string) *policies { + return &policies{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the policy, and returns the corresponding policy object, and an error if there is any. +func (c *policies) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Policy, err error) { + result = &v1.Policy{} + err = c.client.Get(). + Namespace(c.ns). + Resource("policies"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of Policies that match those selectors. +func (c *policies) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PolicyList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.PolicyList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("policies"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested policies. +func (c *policies) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("policies"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a policy and creates it. Returns the server's representation of the policy, and an error, if there is any. +func (c *policies) Create(ctx context.Context, policy *v1.Policy, opts metav1.CreateOptions) (result *v1.Policy, err error) { + result = &v1.Policy{} + err = c.client.Post(). + Namespace(c.ns). + Resource("policies"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(policy). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a policy and updates it. Returns the server's representation of the policy, and an error, if there is any. +func (c *policies) Update(ctx context.Context, policy *v1.Policy, opts metav1.UpdateOptions) (result *v1.Policy, err error) { + result = &v1.Policy{} + err = c.client.Put(). + Namespace(c.ns). + Resource("policies"). + Name(policy.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(policy). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the policy and deletes it. Returns an error if one occurs. +func (c *policies) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("policies"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched policy. +func (c *policies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Policy, err error) { + result = &v1.Policy{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("policies"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/api/client/clientset/versioned/typed/authz/v1/role.go b/api/client/clientset/versioned/typed/authz/v1/role.go new file mode 100644 index 000000000..cd771afe7 --- /dev/null +++ b/api/client/clientset/versioned/typed/authz/v1/role.go @@ -0,0 +1,163 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" + v1 "tkestack.io/tke/api/authz/v1" + scheme "tkestack.io/tke/api/client/clientset/versioned/scheme" +) + +// RolesGetter has a method to return a RoleInterface. +// A group's client should implement this interface. +type RolesGetter interface { + Roles(namespace string) RoleInterface +} + +// RoleInterface has methods to work with Role resources. +type RoleInterface interface { + Create(ctx context.Context, role *v1.Role, opts metav1.CreateOptions) (*v1.Role, error) + Update(ctx context.Context, role *v1.Role, opts metav1.UpdateOptions) (*v1.Role, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Role, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.RoleList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Role, err error) + RoleExpansion +} + +// roles implements RoleInterface +type roles struct { + client rest.Interface + ns string +} + +// newRoles returns a Roles +func newRoles(c *AuthzV1Client, namespace string) *roles { + return &roles{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the role, and returns the corresponding role object, and an error if there is any. +func (c *roles) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Role, err error) { + result = &v1.Role{} + err = c.client.Get(). + Namespace(c.ns). + Resource("roles"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of Roles that match those selectors. +func (c *roles) List(ctx context.Context, opts metav1.ListOptions) (result *v1.RoleList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.RoleList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("roles"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested roles. +func (c *roles) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("roles"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a role and creates it. Returns the server's representation of the role, and an error, if there is any. +func (c *roles) Create(ctx context.Context, role *v1.Role, opts metav1.CreateOptions) (result *v1.Role, err error) { + result = &v1.Role{} + err = c.client.Post(). + Namespace(c.ns). + Resource("roles"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(role). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a role and updates it. Returns the server's representation of the role, and an error, if there is any. +func (c *roles) Update(ctx context.Context, role *v1.Role, opts metav1.UpdateOptions) (result *v1.Role, err error) { + result = &v1.Role{} + err = c.client.Put(). + Namespace(c.ns). + Resource("roles"). + Name(role.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(role). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the role and deletes it. Returns an error if one occurs. +func (c *roles) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("roles"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched role. +func (c *roles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Role, err error) { + result = &v1.Role{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("roles"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/api/client/informers/externalversions/authz/interface.go b/api/client/informers/externalversions/authz/interface.go new file mode 100644 index 000000000..65b339372 --- /dev/null +++ b/api/client/informers/externalversions/authz/interface.go @@ -0,0 +1,48 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package authz + +import ( + v1 "tkestack.io/tke/api/client/informers/externalversions/authz/v1" + internalinterfaces "tkestack.io/tke/api/client/informers/externalversions/internalinterfaces" +) + +// Interface provides access to each of this group's versions. +type Interface interface { + // V1 provides access to shared informers for resources in V1. + V1() v1.Interface +} + +type group struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// V1 returns a new v1.Interface. +func (g *group) V1() v1.Interface { + return v1.New(g.factory, g.namespace, g.tweakListOptions) +} diff --git a/api/client/informers/externalversions/authz/v1/configmap.go b/api/client/informers/externalversions/authz/v1/configmap.go new file mode 100644 index 000000000..5c9182439 --- /dev/null +++ b/api/client/informers/externalversions/authz/v1/configmap.go @@ -0,0 +1,91 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + time "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" + authzv1 "tkestack.io/tke/api/authz/v1" + versioned "tkestack.io/tke/api/client/clientset/versioned" + internalinterfaces "tkestack.io/tke/api/client/informers/externalversions/internalinterfaces" + v1 "tkestack.io/tke/api/client/listers/authz/v1" +) + +// ConfigMapInformer provides access to a shared informer and lister for +// ConfigMaps. +type ConfigMapInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.ConfigMapLister +} + +type configMapInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewConfigMapInformer constructs a new informer for ConfigMap type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewConfigMapInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredConfigMapInformer(client, resyncPeriod, indexers, nil) +} + +// NewFilteredConfigMapInformer constructs a new informer for ConfigMap type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredConfigMapInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AuthzV1().ConfigMaps().List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AuthzV1().ConfigMaps().Watch(context.TODO(), options) + }, + }, + &authzv1.ConfigMap{}, + resyncPeriod, + indexers, + ) +} + +func (f *configMapInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredConfigMapInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *configMapInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&authzv1.ConfigMap{}, f.defaultInformer) +} + +func (f *configMapInformer) Lister() v1.ConfigMapLister { + return v1.NewConfigMapLister(f.Informer().GetIndexer()) +} diff --git a/api/client/informers/externalversions/authz/v1/interface.go b/api/client/informers/externalversions/authz/v1/interface.go new file mode 100644 index 000000000..7f9eef1eb --- /dev/null +++ b/api/client/informers/externalversions/authz/v1/interface.go @@ -0,0 +1,68 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1 + +import ( + internalinterfaces "tkestack.io/tke/api/client/informers/externalversions/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // ConfigMaps returns a ConfigMapInformer. + ConfigMaps() ConfigMapInformer + // MultiClusterRoleBindings returns a MultiClusterRoleBindingInformer. + MultiClusterRoleBindings() MultiClusterRoleBindingInformer + // Policies returns a PolicyInformer. + Policies() PolicyInformer + // Roles returns a RoleInformer. + Roles() RoleInformer +} + +type version struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// ConfigMaps returns a ConfigMapInformer. +func (v *version) ConfigMaps() ConfigMapInformer { + return &configMapInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} + +// MultiClusterRoleBindings returns a MultiClusterRoleBindingInformer. +func (v *version) MultiClusterRoleBindings() MultiClusterRoleBindingInformer { + return &multiClusterRoleBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// Policies returns a PolicyInformer. +func (v *version) Policies() PolicyInformer { + return &policyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// Roles returns a RoleInformer. +func (v *version) Roles() RoleInformer { + return &roleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/api/client/informers/externalversions/authz/v1/multiclusterrolebinding.go b/api/client/informers/externalversions/authz/v1/multiclusterrolebinding.go new file mode 100644 index 000000000..c3304ce80 --- /dev/null +++ b/api/client/informers/externalversions/authz/v1/multiclusterrolebinding.go @@ -0,0 +1,92 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + time "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" + authzv1 "tkestack.io/tke/api/authz/v1" + versioned "tkestack.io/tke/api/client/clientset/versioned" + internalinterfaces "tkestack.io/tke/api/client/informers/externalversions/internalinterfaces" + v1 "tkestack.io/tke/api/client/listers/authz/v1" +) + +// MultiClusterRoleBindingInformer provides access to a shared informer and lister for +// MultiClusterRoleBindings. +type MultiClusterRoleBindingInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.MultiClusterRoleBindingLister +} + +type multiClusterRoleBindingInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewMultiClusterRoleBindingInformer constructs a new informer for MultiClusterRoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewMultiClusterRoleBindingInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredMultiClusterRoleBindingInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredMultiClusterRoleBindingInformer constructs a new informer for MultiClusterRoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredMultiClusterRoleBindingInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AuthzV1().MultiClusterRoleBindings(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AuthzV1().MultiClusterRoleBindings(namespace).Watch(context.TODO(), options) + }, + }, + &authzv1.MultiClusterRoleBinding{}, + resyncPeriod, + indexers, + ) +} + +func (f *multiClusterRoleBindingInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredMultiClusterRoleBindingInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *multiClusterRoleBindingInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&authzv1.MultiClusterRoleBinding{}, f.defaultInformer) +} + +func (f *multiClusterRoleBindingInformer) Lister() v1.MultiClusterRoleBindingLister { + return v1.NewMultiClusterRoleBindingLister(f.Informer().GetIndexer()) +} diff --git a/api/client/informers/externalversions/authz/v1/policy.go b/api/client/informers/externalversions/authz/v1/policy.go new file mode 100644 index 000000000..097f9ccde --- /dev/null +++ b/api/client/informers/externalversions/authz/v1/policy.go @@ -0,0 +1,92 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + time "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" + authzv1 "tkestack.io/tke/api/authz/v1" + versioned "tkestack.io/tke/api/client/clientset/versioned" + internalinterfaces "tkestack.io/tke/api/client/informers/externalversions/internalinterfaces" + v1 "tkestack.io/tke/api/client/listers/authz/v1" +) + +// PolicyInformer provides access to a shared informer and lister for +// Policies. +type PolicyInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.PolicyLister +} + +type policyInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewPolicyInformer constructs a new informer for Policy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewPolicyInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredPolicyInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredPolicyInformer constructs a new informer for Policy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredPolicyInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AuthzV1().Policies(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AuthzV1().Policies(namespace).Watch(context.TODO(), options) + }, + }, + &authzv1.Policy{}, + resyncPeriod, + indexers, + ) +} + +func (f *policyInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredPolicyInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *policyInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&authzv1.Policy{}, f.defaultInformer) +} + +func (f *policyInformer) Lister() v1.PolicyLister { + return v1.NewPolicyLister(f.Informer().GetIndexer()) +} diff --git a/api/client/informers/externalversions/authz/v1/role.go b/api/client/informers/externalversions/authz/v1/role.go new file mode 100644 index 000000000..e2684f986 --- /dev/null +++ b/api/client/informers/externalversions/authz/v1/role.go @@ -0,0 +1,92 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + time "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" + authzv1 "tkestack.io/tke/api/authz/v1" + versioned "tkestack.io/tke/api/client/clientset/versioned" + internalinterfaces "tkestack.io/tke/api/client/informers/externalversions/internalinterfaces" + v1 "tkestack.io/tke/api/client/listers/authz/v1" +) + +// RoleInformer provides access to a shared informer and lister for +// Roles. +type RoleInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.RoleLister +} + +type roleInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewRoleInformer constructs a new informer for Role type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewRoleInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredRoleInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredRoleInformer constructs a new informer for Role type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredRoleInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AuthzV1().Roles(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AuthzV1().Roles(namespace).Watch(context.TODO(), options) + }, + }, + &authzv1.Role{}, + resyncPeriod, + indexers, + ) +} + +func (f *roleInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredRoleInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *roleInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&authzv1.Role{}, f.defaultInformer) +} + +func (f *roleInformer) Lister() v1.RoleLister { + return v1.NewRoleLister(f.Informer().GetIndexer()) +} diff --git a/api/client/informers/externalversions/factory.go b/api/client/informers/externalversions/factory.go index 690924df3..2c54a037d 100644 --- a/api/client/informers/externalversions/factory.go +++ b/api/client/informers/externalversions/factory.go @@ -32,6 +32,7 @@ import ( versioned "tkestack.io/tke/api/client/clientset/versioned" application "tkestack.io/tke/api/client/informers/externalversions/application" auth "tkestack.io/tke/api/client/informers/externalversions/auth" + authz "tkestack.io/tke/api/client/informers/externalversions/authz" business "tkestack.io/tke/api/client/informers/externalversions/business" internalinterfaces "tkestack.io/tke/api/client/informers/externalversions/internalinterfaces" logagent "tkestack.io/tke/api/client/informers/externalversions/logagent" @@ -184,6 +185,7 @@ type SharedInformerFactory interface { Application() application.Interface Auth() auth.Interface + Authz() authz.Interface Business() business.Interface Logagent() logagent.Interface Mesh() mesh.Interface @@ -201,6 +203,10 @@ func (f *sharedInformerFactory) Auth() auth.Interface { return auth.New(f, f.namespace, f.tweakListOptions) } +func (f *sharedInformerFactory) Authz() authz.Interface { + return authz.New(f, f.namespace, f.tweakListOptions) +} + func (f *sharedInformerFactory) Business() business.Interface { return business.New(f, f.namespace, f.tweakListOptions) } diff --git a/api/client/informers/externalversions/generic.go b/api/client/informers/externalversions/generic.go index 082ccbc25..58dd69f25 100644 --- a/api/client/informers/externalversions/generic.go +++ b/api/client/informers/externalversions/generic.go @@ -27,6 +27,7 @@ import ( cache "k8s.io/client-go/tools/cache" v1 "tkestack.io/tke/api/application/v1" authv1 "tkestack.io/tke/api/auth/v1" + authzv1 "tkestack.io/tke/api/authz/v1" businessv1 "tkestack.io/tke/api/business/v1" logagentv1 "tkestack.io/tke/api/logagent/v1" meshv1 "tkestack.io/tke/api/mesh/v1" @@ -100,6 +101,16 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource case authv1.SchemeGroupVersion.WithResource("users"): return &genericInformer{resource: resource.GroupResource(), informer: f.Auth().V1().Users().Informer()}, nil + // Group=authz.tkestack.io, Version=v1 + case authzv1.SchemeGroupVersion.WithResource("configmaps"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Authz().V1().ConfigMaps().Informer()}, nil + case authzv1.SchemeGroupVersion.WithResource("multiclusterrolebindings"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Authz().V1().MultiClusterRoleBindings().Informer()}, nil + case authzv1.SchemeGroupVersion.WithResource("policies"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Authz().V1().Policies().Informer()}, nil + case authzv1.SchemeGroupVersion.WithResource("roles"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Authz().V1().Roles().Informer()}, nil + // Group=business.tkestack.io, Version=v1 case businessv1.SchemeGroupVersion.WithResource("chartgroups"): return &genericInformer{resource: resource.GroupResource(), informer: f.Business().V1().ChartGroups().Informer()}, nil diff --git a/api/client/informers/internalversion/authz/interface.go b/api/client/informers/internalversion/authz/interface.go new file mode 100644 index 000000000..c56b22cbd --- /dev/null +++ b/api/client/informers/internalversion/authz/interface.go @@ -0,0 +1,48 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package authz + +import ( + internalversion "tkestack.io/tke/api/client/informers/internalversion/authz/internalversion" + internalinterfaces "tkestack.io/tke/api/client/informers/internalversion/internalinterfaces" +) + +// Interface provides access to each of this group's versions. +type Interface interface { + // InternalVersion provides access to shared informers for resources in InternalVersion. + InternalVersion() internalversion.Interface +} + +type group struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// InternalVersion returns a new internalversion.Interface. +func (g *group) InternalVersion() internalversion.Interface { + return internalversion.New(g.factory, g.namespace, g.tweakListOptions) +} diff --git a/api/client/informers/internalversion/authz/internalversion/configmap.go b/api/client/informers/internalversion/authz/internalversion/configmap.go new file mode 100644 index 000000000..e04b53c34 --- /dev/null +++ b/api/client/informers/internalversion/authz/internalversion/configmap.go @@ -0,0 +1,91 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package internalversion + +import ( + "context" + time "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" + authz "tkestack.io/tke/api/authz" + clientsetinternalversion "tkestack.io/tke/api/client/clientset/internalversion" + internalinterfaces "tkestack.io/tke/api/client/informers/internalversion/internalinterfaces" + internalversion "tkestack.io/tke/api/client/listers/authz/internalversion" +) + +// ConfigMapInformer provides access to a shared informer and lister for +// ConfigMaps. +type ConfigMapInformer interface { + Informer() cache.SharedIndexInformer + Lister() internalversion.ConfigMapLister +} + +type configMapInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewConfigMapInformer constructs a new informer for ConfigMap type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewConfigMapInformer(client clientsetinternalversion.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredConfigMapInformer(client, resyncPeriod, indexers, nil) +} + +// NewFilteredConfigMapInformer constructs a new informer for ConfigMap type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredConfigMapInformer(client clientsetinternalversion.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Authz().ConfigMaps().List(context.TODO(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Authz().ConfigMaps().Watch(context.TODO(), options) + }, + }, + &authz.ConfigMap{}, + resyncPeriod, + indexers, + ) +} + +func (f *configMapInformer) defaultInformer(client clientsetinternalversion.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredConfigMapInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *configMapInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&authz.ConfigMap{}, f.defaultInformer) +} + +func (f *configMapInformer) Lister() internalversion.ConfigMapLister { + return internalversion.NewConfigMapLister(f.Informer().GetIndexer()) +} diff --git a/api/client/informers/internalversion/authz/internalversion/interface.go b/api/client/informers/internalversion/authz/internalversion/interface.go new file mode 100644 index 000000000..45a4a2a88 --- /dev/null +++ b/api/client/informers/internalversion/authz/internalversion/interface.go @@ -0,0 +1,68 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package internalversion + +import ( + internalinterfaces "tkestack.io/tke/api/client/informers/internalversion/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // ConfigMaps returns a ConfigMapInformer. + ConfigMaps() ConfigMapInformer + // MultiClusterRoleBindings returns a MultiClusterRoleBindingInformer. + MultiClusterRoleBindings() MultiClusterRoleBindingInformer + // Policies returns a PolicyInformer. + Policies() PolicyInformer + // Roles returns a RoleInformer. + Roles() RoleInformer +} + +type version struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// ConfigMaps returns a ConfigMapInformer. +func (v *version) ConfigMaps() ConfigMapInformer { + return &configMapInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} + +// MultiClusterRoleBindings returns a MultiClusterRoleBindingInformer. +func (v *version) MultiClusterRoleBindings() MultiClusterRoleBindingInformer { + return &multiClusterRoleBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// Policies returns a PolicyInformer. +func (v *version) Policies() PolicyInformer { + return &policyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// Roles returns a RoleInformer. +func (v *version) Roles() RoleInformer { + return &roleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/api/client/informers/internalversion/authz/internalversion/multiclusterrolebinding.go b/api/client/informers/internalversion/authz/internalversion/multiclusterrolebinding.go new file mode 100644 index 000000000..9ae918f33 --- /dev/null +++ b/api/client/informers/internalversion/authz/internalversion/multiclusterrolebinding.go @@ -0,0 +1,92 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package internalversion + +import ( + "context" + time "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" + authz "tkestack.io/tke/api/authz" + clientsetinternalversion "tkestack.io/tke/api/client/clientset/internalversion" + internalinterfaces "tkestack.io/tke/api/client/informers/internalversion/internalinterfaces" + internalversion "tkestack.io/tke/api/client/listers/authz/internalversion" +) + +// MultiClusterRoleBindingInformer provides access to a shared informer and lister for +// MultiClusterRoleBindings. +type MultiClusterRoleBindingInformer interface { + Informer() cache.SharedIndexInformer + Lister() internalversion.MultiClusterRoleBindingLister +} + +type multiClusterRoleBindingInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewMultiClusterRoleBindingInformer constructs a new informer for MultiClusterRoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewMultiClusterRoleBindingInformer(client clientsetinternalversion.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredMultiClusterRoleBindingInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredMultiClusterRoleBindingInformer constructs a new informer for MultiClusterRoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredMultiClusterRoleBindingInformer(client clientsetinternalversion.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Authz().MultiClusterRoleBindings(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Authz().MultiClusterRoleBindings(namespace).Watch(context.TODO(), options) + }, + }, + &authz.MultiClusterRoleBinding{}, + resyncPeriod, + indexers, + ) +} + +func (f *multiClusterRoleBindingInformer) defaultInformer(client clientsetinternalversion.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredMultiClusterRoleBindingInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *multiClusterRoleBindingInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&authz.MultiClusterRoleBinding{}, f.defaultInformer) +} + +func (f *multiClusterRoleBindingInformer) Lister() internalversion.MultiClusterRoleBindingLister { + return internalversion.NewMultiClusterRoleBindingLister(f.Informer().GetIndexer()) +} diff --git a/api/client/informers/internalversion/authz/internalversion/policy.go b/api/client/informers/internalversion/authz/internalversion/policy.go new file mode 100644 index 000000000..5acfda5f2 --- /dev/null +++ b/api/client/informers/internalversion/authz/internalversion/policy.go @@ -0,0 +1,92 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package internalversion + +import ( + "context" + time "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" + authz "tkestack.io/tke/api/authz" + clientsetinternalversion "tkestack.io/tke/api/client/clientset/internalversion" + internalinterfaces "tkestack.io/tke/api/client/informers/internalversion/internalinterfaces" + internalversion "tkestack.io/tke/api/client/listers/authz/internalversion" +) + +// PolicyInformer provides access to a shared informer and lister for +// Policies. +type PolicyInformer interface { + Informer() cache.SharedIndexInformer + Lister() internalversion.PolicyLister +} + +type policyInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewPolicyInformer constructs a new informer for Policy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewPolicyInformer(client clientsetinternalversion.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredPolicyInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredPolicyInformer constructs a new informer for Policy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredPolicyInformer(client clientsetinternalversion.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Authz().Policies(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Authz().Policies(namespace).Watch(context.TODO(), options) + }, + }, + &authz.Policy{}, + resyncPeriod, + indexers, + ) +} + +func (f *policyInformer) defaultInformer(client clientsetinternalversion.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredPolicyInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *policyInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&authz.Policy{}, f.defaultInformer) +} + +func (f *policyInformer) Lister() internalversion.PolicyLister { + return internalversion.NewPolicyLister(f.Informer().GetIndexer()) +} diff --git a/api/client/informers/internalversion/authz/internalversion/role.go b/api/client/informers/internalversion/authz/internalversion/role.go new file mode 100644 index 000000000..2e9e9691a --- /dev/null +++ b/api/client/informers/internalversion/authz/internalversion/role.go @@ -0,0 +1,92 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +// Code generated by informer-gen. DO NOT EDIT. + +package internalversion + +import ( + "context" + time "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" + authz "tkestack.io/tke/api/authz" + clientsetinternalversion "tkestack.io/tke/api/client/clientset/internalversion" + internalinterfaces "tkestack.io/tke/api/client/informers/internalversion/internalinterfaces" + internalversion "tkestack.io/tke/api/client/listers/authz/internalversion" +) + +// RoleInformer provides access to a shared informer and lister for +// Roles. +type RoleInformer interface { + Informer() cache.SharedIndexInformer + Lister() internalversion.RoleLister +} + +type roleInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewRoleInformer constructs a new informer for Role type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewRoleInformer(client clientsetinternalversion.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredRoleInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredRoleInformer constructs a new informer for Role type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredRoleInformer(client clientsetinternalversion.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Authz().Roles(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Authz().Roles(namespace).Watch(context.TODO(), options) + }, + }, + &authz.Role{}, + resyncPeriod, + indexers, + ) +} + +func (f *roleInformer) defaultInformer(client clientsetinternalversion.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredRoleInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *roleInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&authz.Role{}, f.defaultInformer) +} + +func (f *roleInformer) Lister() internalversion.RoleLister { + return internalversion.NewRoleLister(f.Informer().GetIndexer()) +} diff --git a/api/client/informers/internalversion/factory.go b/api/client/informers/internalversion/factory.go index bdbfb60f4..22bb2a6bb 100644 --- a/api/client/informers/internalversion/factory.go +++ b/api/client/informers/internalversion/factory.go @@ -32,6 +32,7 @@ import ( internalversion "tkestack.io/tke/api/client/clientset/internalversion" application "tkestack.io/tke/api/client/informers/internalversion/application" auth "tkestack.io/tke/api/client/informers/internalversion/auth" + authz "tkestack.io/tke/api/client/informers/internalversion/authz" business "tkestack.io/tke/api/client/informers/internalversion/business" internalinterfaces "tkestack.io/tke/api/client/informers/internalversion/internalinterfaces" logagent "tkestack.io/tke/api/client/informers/internalversion/logagent" @@ -184,6 +185,7 @@ type SharedInformerFactory interface { Application() application.Interface Auth() auth.Interface + Authz() authz.Interface Business() business.Interface Logagent() logagent.Interface Mesh() mesh.Interface @@ -201,6 +203,10 @@ func (f *sharedInformerFactory) Auth() auth.Interface { return auth.New(f, f.namespace, f.tweakListOptions) } +func (f *sharedInformerFactory) Authz() authz.Interface { + return authz.New(f, f.namespace, f.tweakListOptions) +} + func (f *sharedInformerFactory) Business() business.Interface { return business.New(f, f.namespace, f.tweakListOptions) } diff --git a/api/client/informers/internalversion/generic.go b/api/client/informers/internalversion/generic.go index 084077ded..10044b721 100644 --- a/api/client/informers/internalversion/generic.go +++ b/api/client/informers/internalversion/generic.go @@ -27,6 +27,7 @@ import ( cache "k8s.io/client-go/tools/cache" application "tkestack.io/tke/api/application" auth "tkestack.io/tke/api/auth" + authz "tkestack.io/tke/api/authz" business "tkestack.io/tke/api/business" logagent "tkestack.io/tke/api/logagent" mesh "tkestack.io/tke/api/mesh" @@ -102,6 +103,16 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource case auth.SchemeGroupVersion.WithResource("users"): return &genericInformer{resource: resource.GroupResource(), informer: f.Auth().InternalVersion().Users().Informer()}, nil + // Group=authz.tkestack.io, Version=internalVersion + case authz.SchemeGroupVersion.WithResource("configmaps"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Authz().InternalVersion().ConfigMaps().Informer()}, nil + case authz.SchemeGroupVersion.WithResource("multiclusterrolebindings"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Authz().InternalVersion().MultiClusterRoleBindings().Informer()}, nil + case authz.SchemeGroupVersion.WithResource("policies"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Authz().InternalVersion().Policies().Informer()}, nil + case authz.SchemeGroupVersion.WithResource("roles"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Authz().InternalVersion().Roles().Informer()}, nil + // Group=business.tkestack.io, Version=internalVersion case business.SchemeGroupVersion.WithResource("chartgroups"): return &genericInformer{resource: resource.GroupResource(), informer: f.Business().InternalVersion().ChartGroups().Informer()}, nil diff --git a/api/client/listers/authz/internalversion/configmap.go b/api/client/listers/authz/internalversion/configmap.go new file mode 100644 index 000000000..06312bae3 --- /dev/null +++ b/api/client/listers/authz/internalversion/configmap.go @@ -0,0 +1,70 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES 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 internalversion + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + authz "tkestack.io/tke/api/authz" +) + +// ConfigMapLister helps list ConfigMaps. +// All objects returned here must be treated as read-only. +type ConfigMapLister interface { + // List lists all ConfigMaps in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*authz.ConfigMap, err error) + // Get retrieves the ConfigMap from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*authz.ConfigMap, error) + ConfigMapListerExpansion +} + +// configMapLister implements the ConfigMapLister interface. +type configMapLister struct { + indexer cache.Indexer +} + +// NewConfigMapLister returns a new ConfigMapLister. +func NewConfigMapLister(indexer cache.Indexer) ConfigMapLister { + return &configMapLister{indexer: indexer} +} + +// List lists all ConfigMaps in the indexer. +func (s *configMapLister) List(selector labels.Selector) (ret []*authz.ConfigMap, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*authz.ConfigMap)) + }) + return ret, err +} + +// Get retrieves the ConfigMap from the index for a given name. +func (s *configMapLister) Get(name string) (*authz.ConfigMap, error) { + obj, exists, err := s.indexer.GetByKey(name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(authz.Resource("configmap"), name) + } + return obj.(*authz.ConfigMap), nil +} diff --git a/api/client/listers/authz/internalversion/expansion_generated.go b/api/client/listers/authz/internalversion/expansion_generated.go new file mode 100644 index 000000000..204598dd1 --- /dev/null +++ b/api/client/listers/authz/internalversion/expansion_generated.go @@ -0,0 +1,49 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES 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 internalversion + +// ConfigMapListerExpansion allows custom methods to be added to +// ConfigMapLister. +type ConfigMapListerExpansion interface{} + +// MultiClusterRoleBindingListerExpansion allows custom methods to be added to +// MultiClusterRoleBindingLister. +type MultiClusterRoleBindingListerExpansion interface{} + +// MultiClusterRoleBindingNamespaceListerExpansion allows custom methods to be added to +// MultiClusterRoleBindingNamespaceLister. +type MultiClusterRoleBindingNamespaceListerExpansion interface{} + +// PolicyListerExpansion allows custom methods to be added to +// PolicyLister. +type PolicyListerExpansion interface{} + +// PolicyNamespaceListerExpansion allows custom methods to be added to +// PolicyNamespaceLister. +type PolicyNamespaceListerExpansion interface{} + +// RoleListerExpansion allows custom methods to be added to +// RoleLister. +type RoleListerExpansion interface{} + +// RoleNamespaceListerExpansion allows custom methods to be added to +// RoleNamespaceLister. +type RoleNamespaceListerExpansion interface{} diff --git a/api/client/listers/authz/internalversion/multiclusterrolebinding.go b/api/client/listers/authz/internalversion/multiclusterrolebinding.go new file mode 100644 index 000000000..d23cbe555 --- /dev/null +++ b/api/client/listers/authz/internalversion/multiclusterrolebinding.go @@ -0,0 +1,101 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES 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 internalversion + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + authz "tkestack.io/tke/api/authz" +) + +// MultiClusterRoleBindingLister helps list MultiClusterRoleBindings. +// All objects returned here must be treated as read-only. +type MultiClusterRoleBindingLister interface { + // List lists all MultiClusterRoleBindings in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*authz.MultiClusterRoleBinding, err error) + // MultiClusterRoleBindings returns an object that can list and get MultiClusterRoleBindings. + MultiClusterRoleBindings(namespace string) MultiClusterRoleBindingNamespaceLister + MultiClusterRoleBindingListerExpansion +} + +// multiClusterRoleBindingLister implements the MultiClusterRoleBindingLister interface. +type multiClusterRoleBindingLister struct { + indexer cache.Indexer +} + +// NewMultiClusterRoleBindingLister returns a new MultiClusterRoleBindingLister. +func NewMultiClusterRoleBindingLister(indexer cache.Indexer) MultiClusterRoleBindingLister { + return &multiClusterRoleBindingLister{indexer: indexer} +} + +// List lists all MultiClusterRoleBindings in the indexer. +func (s *multiClusterRoleBindingLister) List(selector labels.Selector) (ret []*authz.MultiClusterRoleBinding, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*authz.MultiClusterRoleBinding)) + }) + return ret, err +} + +// MultiClusterRoleBindings returns an object that can list and get MultiClusterRoleBindings. +func (s *multiClusterRoleBindingLister) MultiClusterRoleBindings(namespace string) MultiClusterRoleBindingNamespaceLister { + return multiClusterRoleBindingNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// MultiClusterRoleBindingNamespaceLister helps list and get MultiClusterRoleBindings. +// All objects returned here must be treated as read-only. +type MultiClusterRoleBindingNamespaceLister interface { + // List lists all MultiClusterRoleBindings in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*authz.MultiClusterRoleBinding, err error) + // Get retrieves the MultiClusterRoleBinding from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*authz.MultiClusterRoleBinding, error) + MultiClusterRoleBindingNamespaceListerExpansion +} + +// multiClusterRoleBindingNamespaceLister implements the MultiClusterRoleBindingNamespaceLister +// interface. +type multiClusterRoleBindingNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all MultiClusterRoleBindings in the indexer for a given namespace. +func (s multiClusterRoleBindingNamespaceLister) List(selector labels.Selector) (ret []*authz.MultiClusterRoleBinding, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*authz.MultiClusterRoleBinding)) + }) + return ret, err +} + +// Get retrieves the MultiClusterRoleBinding from the indexer for a given namespace and name. +func (s multiClusterRoleBindingNamespaceLister) Get(name string) (*authz.MultiClusterRoleBinding, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(authz.Resource("multiclusterrolebinding"), name) + } + return obj.(*authz.MultiClusterRoleBinding), nil +} diff --git a/api/client/listers/authz/internalversion/policy.go b/api/client/listers/authz/internalversion/policy.go new file mode 100644 index 000000000..4f10f8eae --- /dev/null +++ b/api/client/listers/authz/internalversion/policy.go @@ -0,0 +1,101 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES 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 internalversion + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + authz "tkestack.io/tke/api/authz" +) + +// PolicyLister helps list Policies. +// All objects returned here must be treated as read-only. +type PolicyLister interface { + // List lists all Policies in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*authz.Policy, err error) + // Policies returns an object that can list and get Policies. + Policies(namespace string) PolicyNamespaceLister + PolicyListerExpansion +} + +// policyLister implements the PolicyLister interface. +type policyLister struct { + indexer cache.Indexer +} + +// NewPolicyLister returns a new PolicyLister. +func NewPolicyLister(indexer cache.Indexer) PolicyLister { + return &policyLister{indexer: indexer} +} + +// List lists all Policies in the indexer. +func (s *policyLister) List(selector labels.Selector) (ret []*authz.Policy, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*authz.Policy)) + }) + return ret, err +} + +// Policies returns an object that can list and get Policies. +func (s *policyLister) Policies(namespace string) PolicyNamespaceLister { + return policyNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// PolicyNamespaceLister helps list and get Policies. +// All objects returned here must be treated as read-only. +type PolicyNamespaceLister interface { + // List lists all Policies in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*authz.Policy, err error) + // Get retrieves the Policy from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*authz.Policy, error) + PolicyNamespaceListerExpansion +} + +// policyNamespaceLister implements the PolicyNamespaceLister +// interface. +type policyNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all Policies in the indexer for a given namespace. +func (s policyNamespaceLister) List(selector labels.Selector) (ret []*authz.Policy, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*authz.Policy)) + }) + return ret, err +} + +// Get retrieves the Policy from the indexer for a given namespace and name. +func (s policyNamespaceLister) Get(name string) (*authz.Policy, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(authz.Resource("policy"), name) + } + return obj.(*authz.Policy), nil +} diff --git a/api/client/listers/authz/internalversion/role.go b/api/client/listers/authz/internalversion/role.go new file mode 100644 index 000000000..fee033c39 --- /dev/null +++ b/api/client/listers/authz/internalversion/role.go @@ -0,0 +1,101 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES 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 internalversion + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + authz "tkestack.io/tke/api/authz" +) + +// RoleLister helps list Roles. +// All objects returned here must be treated as read-only. +type RoleLister interface { + // List lists all Roles in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*authz.Role, err error) + // Roles returns an object that can list and get Roles. + Roles(namespace string) RoleNamespaceLister + RoleListerExpansion +} + +// roleLister implements the RoleLister interface. +type roleLister struct { + indexer cache.Indexer +} + +// NewRoleLister returns a new RoleLister. +func NewRoleLister(indexer cache.Indexer) RoleLister { + return &roleLister{indexer: indexer} +} + +// List lists all Roles in the indexer. +func (s *roleLister) List(selector labels.Selector) (ret []*authz.Role, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*authz.Role)) + }) + return ret, err +} + +// Roles returns an object that can list and get Roles. +func (s *roleLister) Roles(namespace string) RoleNamespaceLister { + return roleNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// RoleNamespaceLister helps list and get Roles. +// All objects returned here must be treated as read-only. +type RoleNamespaceLister interface { + // List lists all Roles in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*authz.Role, err error) + // Get retrieves the Role from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*authz.Role, error) + RoleNamespaceListerExpansion +} + +// roleNamespaceLister implements the RoleNamespaceLister +// interface. +type roleNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all Roles in the indexer for a given namespace. +func (s roleNamespaceLister) List(selector labels.Selector) (ret []*authz.Role, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*authz.Role)) + }) + return ret, err +} + +// Get retrieves the Role from the indexer for a given namespace and name. +func (s roleNamespaceLister) Get(name string) (*authz.Role, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(authz.Resource("role"), name) + } + return obj.(*authz.Role), nil +} diff --git a/api/client/listers/authz/v1/configmap.go b/api/client/listers/authz/v1/configmap.go new file mode 100644 index 000000000..f628a6c1a --- /dev/null +++ b/api/client/listers/authz/v1/configmap.go @@ -0,0 +1,70 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES 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 ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1 "tkestack.io/tke/api/authz/v1" +) + +// ConfigMapLister helps list ConfigMaps. +// All objects returned here must be treated as read-only. +type ConfigMapLister interface { + // List lists all ConfigMaps in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.ConfigMap, err error) + // Get retrieves the ConfigMap from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.ConfigMap, error) + ConfigMapListerExpansion +} + +// configMapLister implements the ConfigMapLister interface. +type configMapLister struct { + indexer cache.Indexer +} + +// NewConfigMapLister returns a new ConfigMapLister. +func NewConfigMapLister(indexer cache.Indexer) ConfigMapLister { + return &configMapLister{indexer: indexer} +} + +// List lists all ConfigMaps in the indexer. +func (s *configMapLister) List(selector labels.Selector) (ret []*v1.ConfigMap, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.ConfigMap)) + }) + return ret, err +} + +// Get retrieves the ConfigMap from the index for a given name. +func (s *configMapLister) Get(name string) (*v1.ConfigMap, error) { + obj, exists, err := s.indexer.GetByKey(name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("configmap"), name) + } + return obj.(*v1.ConfigMap), nil +} diff --git a/api/client/listers/authz/v1/expansion_generated.go b/api/client/listers/authz/v1/expansion_generated.go new file mode 100644 index 000000000..e71d7ff67 --- /dev/null +++ b/api/client/listers/authz/v1/expansion_generated.go @@ -0,0 +1,49 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES 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 + +// ConfigMapListerExpansion allows custom methods to be added to +// ConfigMapLister. +type ConfigMapListerExpansion interface{} + +// MultiClusterRoleBindingListerExpansion allows custom methods to be added to +// MultiClusterRoleBindingLister. +type MultiClusterRoleBindingListerExpansion interface{} + +// MultiClusterRoleBindingNamespaceListerExpansion allows custom methods to be added to +// MultiClusterRoleBindingNamespaceLister. +type MultiClusterRoleBindingNamespaceListerExpansion interface{} + +// PolicyListerExpansion allows custom methods to be added to +// PolicyLister. +type PolicyListerExpansion interface{} + +// PolicyNamespaceListerExpansion allows custom methods to be added to +// PolicyNamespaceLister. +type PolicyNamespaceListerExpansion interface{} + +// RoleListerExpansion allows custom methods to be added to +// RoleLister. +type RoleListerExpansion interface{} + +// RoleNamespaceListerExpansion allows custom methods to be added to +// RoleNamespaceLister. +type RoleNamespaceListerExpansion interface{} diff --git a/api/client/listers/authz/v1/multiclusterrolebinding.go b/api/client/listers/authz/v1/multiclusterrolebinding.go new file mode 100644 index 000000000..2dc607cd9 --- /dev/null +++ b/api/client/listers/authz/v1/multiclusterrolebinding.go @@ -0,0 +1,101 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES 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 ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1 "tkestack.io/tke/api/authz/v1" +) + +// MultiClusterRoleBindingLister helps list MultiClusterRoleBindings. +// All objects returned here must be treated as read-only. +type MultiClusterRoleBindingLister interface { + // List lists all MultiClusterRoleBindings in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.MultiClusterRoleBinding, err error) + // MultiClusterRoleBindings returns an object that can list and get MultiClusterRoleBindings. + MultiClusterRoleBindings(namespace string) MultiClusterRoleBindingNamespaceLister + MultiClusterRoleBindingListerExpansion +} + +// multiClusterRoleBindingLister implements the MultiClusterRoleBindingLister interface. +type multiClusterRoleBindingLister struct { + indexer cache.Indexer +} + +// NewMultiClusterRoleBindingLister returns a new MultiClusterRoleBindingLister. +func NewMultiClusterRoleBindingLister(indexer cache.Indexer) MultiClusterRoleBindingLister { + return &multiClusterRoleBindingLister{indexer: indexer} +} + +// List lists all MultiClusterRoleBindings in the indexer. +func (s *multiClusterRoleBindingLister) List(selector labels.Selector) (ret []*v1.MultiClusterRoleBinding, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.MultiClusterRoleBinding)) + }) + return ret, err +} + +// MultiClusterRoleBindings returns an object that can list and get MultiClusterRoleBindings. +func (s *multiClusterRoleBindingLister) MultiClusterRoleBindings(namespace string) MultiClusterRoleBindingNamespaceLister { + return multiClusterRoleBindingNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// MultiClusterRoleBindingNamespaceLister helps list and get MultiClusterRoleBindings. +// All objects returned here must be treated as read-only. +type MultiClusterRoleBindingNamespaceLister interface { + // List lists all MultiClusterRoleBindings in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.MultiClusterRoleBinding, err error) + // Get retrieves the MultiClusterRoleBinding from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.MultiClusterRoleBinding, error) + MultiClusterRoleBindingNamespaceListerExpansion +} + +// multiClusterRoleBindingNamespaceLister implements the MultiClusterRoleBindingNamespaceLister +// interface. +type multiClusterRoleBindingNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all MultiClusterRoleBindings in the indexer for a given namespace. +func (s multiClusterRoleBindingNamespaceLister) List(selector labels.Selector) (ret []*v1.MultiClusterRoleBinding, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.MultiClusterRoleBinding)) + }) + return ret, err +} + +// Get retrieves the MultiClusterRoleBinding from the indexer for a given namespace and name. +func (s multiClusterRoleBindingNamespaceLister) Get(name string) (*v1.MultiClusterRoleBinding, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("multiclusterrolebinding"), name) + } + return obj.(*v1.MultiClusterRoleBinding), nil +} diff --git a/api/client/listers/authz/v1/policy.go b/api/client/listers/authz/v1/policy.go new file mode 100644 index 000000000..dbe8f7617 --- /dev/null +++ b/api/client/listers/authz/v1/policy.go @@ -0,0 +1,101 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES 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 ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1 "tkestack.io/tke/api/authz/v1" +) + +// PolicyLister helps list Policies. +// All objects returned here must be treated as read-only. +type PolicyLister interface { + // List lists all Policies in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Policy, err error) + // Policies returns an object that can list and get Policies. + Policies(namespace string) PolicyNamespaceLister + PolicyListerExpansion +} + +// policyLister implements the PolicyLister interface. +type policyLister struct { + indexer cache.Indexer +} + +// NewPolicyLister returns a new PolicyLister. +func NewPolicyLister(indexer cache.Indexer) PolicyLister { + return &policyLister{indexer: indexer} +} + +// List lists all Policies in the indexer. +func (s *policyLister) List(selector labels.Selector) (ret []*v1.Policy, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Policy)) + }) + return ret, err +} + +// Policies returns an object that can list and get Policies. +func (s *policyLister) Policies(namespace string) PolicyNamespaceLister { + return policyNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// PolicyNamespaceLister helps list and get Policies. +// All objects returned here must be treated as read-only. +type PolicyNamespaceLister interface { + // List lists all Policies in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Policy, err error) + // Get retrieves the Policy from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.Policy, error) + PolicyNamespaceListerExpansion +} + +// policyNamespaceLister implements the PolicyNamespaceLister +// interface. +type policyNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all Policies in the indexer for a given namespace. +func (s policyNamespaceLister) List(selector labels.Selector) (ret []*v1.Policy, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Policy)) + }) + return ret, err +} + +// Get retrieves the Policy from the indexer for a given namespace and name. +func (s policyNamespaceLister) Get(name string) (*v1.Policy, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("policy"), name) + } + return obj.(*v1.Policy), nil +} diff --git a/api/client/listers/authz/v1/role.go b/api/client/listers/authz/v1/role.go new file mode 100644 index 000000000..32190dd39 --- /dev/null +++ b/api/client/listers/authz/v1/role.go @@ -0,0 +1,101 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2020 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES 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 ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1 "tkestack.io/tke/api/authz/v1" +) + +// RoleLister helps list Roles. +// All objects returned here must be treated as read-only. +type RoleLister interface { + // List lists all Roles in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Role, err error) + // Roles returns an object that can list and get Roles. + Roles(namespace string) RoleNamespaceLister + RoleListerExpansion +} + +// roleLister implements the RoleLister interface. +type roleLister struct { + indexer cache.Indexer +} + +// NewRoleLister returns a new RoleLister. +func NewRoleLister(indexer cache.Indexer) RoleLister { + return &roleLister{indexer: indexer} +} + +// List lists all Roles in the indexer. +func (s *roleLister) List(selector labels.Selector) (ret []*v1.Role, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Role)) + }) + return ret, err +} + +// Roles returns an object that can list and get Roles. +func (s *roleLister) Roles(namespace string) RoleNamespaceLister { + return roleNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// RoleNamespaceLister helps list and get Roles. +// All objects returned here must be treated as read-only. +type RoleNamespaceLister interface { + // List lists all Roles in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Role, err error) + // Get retrieves the Role from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.Role, error) + RoleNamespaceListerExpansion +} + +// roleNamespaceLister implements the RoleNamespaceLister +// interface. +type roleNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all Roles in the indexer for a given namespace. +func (s roleNamespaceLister) List(selector labels.Selector) (ret []*v1.Role, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Role)) + }) + return ret, err +} + +// Get retrieves the Role from the indexer for a given namespace and name. +func (s roleNamespaceLister) Get(name string) (*v1.Role, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("role"), name) + } + return obj.(*v1.Role), nil +} diff --git a/api/openapi/zz_generated.openapi.go b/api/openapi/zz_generated.openapi.go index 8ec064a26..41c8fa70a 100644 --- a/api/openapi/zz_generated.openapi.go +++ b/api/openapi/zz_generated.openapi.go @@ -904,6 +904,16 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA "tkestack.io/tke/api/auth/v1.User": schema_tke_api_auth_v1_User(ref), "tkestack.io/tke/api/auth/v1.UserList": schema_tke_api_auth_v1_UserList(ref), "tkestack.io/tke/api/auth/v1.UserSpec": schema_tke_api_auth_v1_UserSpec(ref), + "tkestack.io/tke/api/authz/v1.ConfigMap": schema_tke_api_authz_v1_ConfigMap(ref), + "tkestack.io/tke/api/authz/v1.ConfigMapList": schema_tke_api_authz_v1_ConfigMapList(ref), + "tkestack.io/tke/api/authz/v1.MultiClusterRoleBinding": schema_tke_api_authz_v1_MultiClusterRoleBinding(ref), + "tkestack.io/tke/api/authz/v1.MultiClusterRoleBindingList": schema_tke_api_authz_v1_MultiClusterRoleBindingList(ref), + "tkestack.io/tke/api/authz/v1.MultiClusterRoleBindingSpec": schema_tke_api_authz_v1_MultiClusterRoleBindingSpec(ref), + "tkestack.io/tke/api/authz/v1.MultiClusterRoleBindingStatus": schema_tke_api_authz_v1_MultiClusterRoleBindingStatus(ref), + "tkestack.io/tke/api/authz/v1.Policy": schema_tke_api_authz_v1_Policy(ref), + "tkestack.io/tke/api/authz/v1.PolicyList": schema_tke_api_authz_v1_PolicyList(ref), + "tkestack.io/tke/api/authz/v1.Role": schema_tke_api_authz_v1_Role(ref), + "tkestack.io/tke/api/authz/v1.RoleList": schema_tke_api_authz_v1_RoleList(ref), "tkestack.io/tke/api/business/v1.ChartGroup": schema_tke_api_business_v1_ChartGroup(ref), "tkestack.io/tke/api/business/v1.ChartGroupList": schema_tke_api_business_v1_ChartGroupList(ref), "tkestack.io/tke/api/business/v1.ChartGroupSpec": schema_tke_api_business_v1_ChartGroupSpec(ref), @@ -45514,6 +45524,553 @@ func schema_tke_api_auth_v1_UserSpec(ref common.ReferenceCallback) common.OpenAP } } +func schema_tke_api_authz_v1_ConfigMap(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ConfigMap holds configuration data for tke to consume.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "data": { + SchemaProps: spec.SchemaProps{ + Description: "Data contains the configuration data. Each key must consist of alphanumeric characters, '-', '_' or '.'. Values with non-UTF-8 byte sequences must use the BinaryData field. The keys stored in Data must not overlap with the keys in the BinaryData field, this is enforced during validation process.", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Allows: true, + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "binaryData": { + SchemaProps: spec.SchemaProps{ + Description: "BinaryData contains the binary data. Each key must consist of alphanumeric characters, '-', '_' or '.'. BinaryData can contain byte sequences that are not in the UTF-8 range. The keys stored in BinaryData must not overlap with the ones in the Data field, this is enforced during validation process.", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Allows: true, + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + Format: "byte", + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, + } +} + +func schema_tke_api_authz_v1_ConfigMapList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ConfigMapList is a resource containing a list of ConfigMap objects.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "Items is the list of ConfigMaps.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("tkestack.io/tke/api/authz/v1.ConfigMap"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "tkestack.io/tke/api/authz/v1.ConfigMap"}, + } +} + +func schema_tke_api_authz_v1_MultiClusterRoleBinding(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("tkestack.io/tke/api/authz/v1.MultiClusterRoleBindingSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("tkestack.io/tke/api/authz/v1.MultiClusterRoleBindingStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "tkestack.io/tke/api/authz/v1.MultiClusterRoleBindingSpec", "tkestack.io/tke/api/authz/v1.MultiClusterRoleBindingStatus"}, + } +} + +func schema_tke_api_authz_v1_MultiClusterRoleBindingList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "List of rules.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("tkestack.io/tke/api/authz/v1.MultiClusterRoleBinding"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "tkestack.io/tke/api/authz/v1.MultiClusterRoleBinding"}, + } +} + +func schema_tke_api_authz_v1_MultiClusterRoleBindingSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "tenantID": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "username": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "roleName": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "clusters": { + SchemaProps: spec.SchemaProps{ + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + Required: []string{"tenantID", "username", "roleName", "clusters"}, + }, + }, + } +} + +func schema_tke_api_authz_v1_MultiClusterRoleBindingStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "phase": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_tke_api_authz_v1_Policy(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "Policy is a rbac template in TKE.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "displayName": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "tenantID": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "username": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "description": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "scope": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "rules": { + SchemaProps: spec.SchemaProps{ + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/api/rbac/v1.PolicyRule"), + }, + }, + }, + }, + }, + }, + Required: []string{"displayName", "scope", "rules"}, + }, + }, + Dependencies: []string{ + "k8s.io/api/rbac/v1.PolicyRule", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, + } +} + +func schema_tke_api_authz_v1_PolicyList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "PolicyList is the whole list of all rbac templates.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "List of policies", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("tkestack.io/tke/api/authz/v1.Policy"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "tkestack.io/tke/api/authz/v1.Policy"}, + } +} + +func schema_tke_api_authz_v1_Role(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "Role is a collection with multiple policies.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "displayName": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "tenantID": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "username": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "description": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "scope": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "policies": { + SchemaProps: spec.SchemaProps{ + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + Required: []string{"displayName", "scope", "policies"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, + } +} + +func schema_tke_api_authz_v1_RoleList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "RoleList is the whole list of policy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "List of rules.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("tkestack.io/tke/api/authz/v1.Role"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "tkestack.io/tke/api/authz/v1.Role"}, + } +} + func schema_tke_api_business_v1_ChartGroup(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ diff --git a/build/docker/tke-authz-api/Dockerfile b/build/docker/tke-authz-api/Dockerfile new file mode 100644 index 000000000..0a9c0f310 --- /dev/null +++ b/build/docker/tke-authz-api/Dockerfile @@ -0,0 +1,23 @@ +# Tencent is pleased to support the open source community by making TKEStack +# available. +# +# Copyright (C) 2012-2019 Tencent. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use +# this file except in compliance with the License. You may obtain a copy of the +# License at +# +# https://opensource.org/licenses/Apache-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OF ANY KIND, either express or implied. See the License for the +# specific language governing permissions and limitations under the License. + +FROM BASE_IMAGE + +RUN echo "hosts: files dns" >> /etc/nsswitch.conf + +WORKDIR /app +ADD tke-authz-api /app/bin/ +ENTRYPOINT ["/app/bin/tke-authz-api"] diff --git a/build/docker/tke-authz-controller/Dockerfile b/build/docker/tke-authz-controller/Dockerfile new file mode 100644 index 000000000..91c74d5f3 --- /dev/null +++ b/build/docker/tke-authz-controller/Dockerfile @@ -0,0 +1,23 @@ +# Tencent is pleased to support the open source community by making TKEStack +# available. +# +# Copyright (C) 2012-2019 Tencent. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use +# this file except in compliance with the License. You may obtain a copy of the +# License at +# +# https://opensource.org/licenses/Apache-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OF ANY KIND, either express or implied. See the License for the +# specific language governing permissions and limitations under the License. + +FROM BASE_IMAGE + +RUN echo "hosts: files dns" >> /etc/nsswitch.conf + +WORKDIR /app +ADD tke-authz-controller /app/bin/ +ENTRYPOINT ["/app/bin/tke-authz-controller"] diff --git a/build/lib/gen.mk b/build/lib/gen.mk index d041d4141..aee41e75a 100644 --- a/build/lib/gen.mk +++ b/build/lib/gen.mk @@ -20,7 +20,7 @@ K8S_APIMACHINERY_DIR = $(shell go list -f '{{ .Dir }}' -m k8s.io/apimachinery) K8S_API_DIR = $(shell go list -f '{{ .Dir }}' -m k8s.io/api) # set the gogo protobuf package dir GOGO_PROTOBUF_DIR = $(shell go list -f '{{ .Dir }}' -m github.com/gogo/protobuf) -EXT_PB_APIS = "k8s.io/api/core/v1 k8s.io/api/apps/v1" +EXT_PB_APIS = "k8s.io/api/core/v1 k8s.io/api/apps/v1 k8s.io/api/rbac/v1" # set the code generator image version CODE_GENERATOR_VERSION := v1.22.3 FIND := find . ! -path './pkg/platform/provider/baremetal/apis/*' @@ -42,7 +42,7 @@ gen.api: $(ROOT_PACKAGE)/api/client \ $(ROOT_PACKAGE)/api \ $(ROOT_PACKAGE)/api \ - "platform:v1 business:v1 notify:v1 registry:v1 monitor:v1 auth:v1 logagent:v1 application:v1 mesh:v1" + "platform:v1 business:v1 notify:v1 registry:v1 monitor:v1 auth:v1 logagent:v1 application:v1 mesh:v1 authz:v1" .PHONY: gen.gateway gen.gateway: diff --git a/build/script/openapi.sh b/build/script/openapi.sh index d95fbef6b..2aa730564 100755 --- a/build/script/openapi.sh +++ b/build/script/openapi.sh @@ -53,6 +53,7 @@ input_dirs=( "${API_PACKAGE}"/logagent/v1 "${API_PACKAGE}"/application/v1 "${API_PACKAGE}"/mesh/v1 + "${API_PACKAGE}"/authz/v1 ) echo "$(IFS=,; echo "${input_dirs[*]}")" diff --git a/cmd/tke-authz-api/apiserver.go b/cmd/tke-authz-api/apiserver.go new file mode 100644 index 000000000..6887cb637 --- /dev/null +++ b/cmd/tke-authz-api/apiserver.go @@ -0,0 +1,37 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package main + +import ( + "math/rand" + "os" + "runtime" + "time" + + "tkestack.io/tke/cmd/tke-authz-api/app" +) + +func main() { + rand.Seed(time.Now().UTC().UnixNano()) + if len(os.Getenv("GOMAXPROCS")) == 0 { + runtime.GOMAXPROCS(runtime.NumCPU()) + } + + app.NewApp("tke-authz-api").Run() +} diff --git a/cmd/tke-authz-api/app/app.go b/cmd/tke-authz-api/app/app.go new file mode 100644 index 000000000..e1f5d528f --- /dev/null +++ b/cmd/tke-authz-api/app/app.go @@ -0,0 +1,62 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package app + +import ( + commonapiserver "k8s.io/apiserver/pkg/server" + "tkestack.io/tke/cmd/tke-authz-api/app/config" + "tkestack.io/tke/cmd/tke-authz-api/app/options" + "tkestack.io/tke/pkg/app" + "tkestack.io/tke/pkg/util/log" +) + +const commandDesc = `The Application API server validates and configures data for the api objects which + include helm release. The API Server services REST operations and + provides the frontend to the release's shared state through which all other + components interact.` + +// NewApp creates a App object with default parameters. +func NewApp(basename string) *app.App { + opts := options.NewOptions(basename) + application := app.NewApp("Tencent Kubernetes Engine Authz API Server", basename, + app.WithOptions(opts), + app.WithDescription(commandDesc), + app.WithRunFunc(run(opts)), + ) + return application +} + +func run(opts *options.Options) app.RunFunc { + return func(basename string) error { + log.Init(opts.Log) + defer log.Flush() + + if err := opts.Complete(); err != nil { + return err + } + + cfg, err := config.CreateConfigFromOptions(basename, opts) + if err != nil { + return err + } + + stopCh := commonapiserver.SetupSignalHandler() + return Run(cfg, stopCh) + } +} diff --git a/cmd/tke-authz-api/app/config/config.go b/cmd/tke-authz-api/app/config/config.go new file mode 100644 index 000000000..c662e1dda --- /dev/null +++ b/cmd/tke-authz-api/app/config/config.go @@ -0,0 +1,167 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package config + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "time" + "tkestack.io/tke/api/authz" + authzv1 "tkestack.io/tke/api/authz/v1" + + "tkestack.io/tke/pkg/apiserver/util" + + genericapiserver "k8s.io/apiserver/pkg/server" + serverstorage "k8s.io/apiserver/pkg/server/storage" + "k8s.io/client-go/rest" + versionedclientset "tkestack.io/tke/api/client/clientset/versioned" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + versionedinformers "tkestack.io/tke/api/client/informers/externalversions" + generatedopenapi "tkestack.io/tke/api/openapi" + "tkestack.io/tke/cmd/tke-authz-api/app/options" + "tkestack.io/tke/pkg/apiserver/authentication" + "tkestack.io/tke/pkg/apiserver/authorization" + "tkestack.io/tke/pkg/apiserver/debug" + "tkestack.io/tke/pkg/apiserver/handler" + "tkestack.io/tke/pkg/apiserver/openapi" + "tkestack.io/tke/pkg/apiserver/storage" + "tkestack.io/tke/pkg/authz/apiserver" + controllerconfig "tkestack.io/tke/pkg/controller/config" +) + +const ( + license = "Apache 2.0" + title = "Tencent Kubernetes Engine Authz API" +) + +// Config is the running configuration structure of the TKE autz apiserver. +type Config struct { + ServerName string + GenericAPIServerConfig *genericapiserver.Config + VersionedSharedInformerFactory versionedinformers.SharedInformerFactory + StorageFactory *serverstorage.DefaultStorageFactory + PlatformClient platformversionedclient.PlatformV1Interface + DefaultPolicies []*authzv1.Policy + DefaultRoles []*authzv1.Role +} + +// CreateConfigFromOptions creates a running configuration instance based +// on a given TKE authz apiserver command line or configuration file option. +func CreateConfigFromOptions(serverName string, opts *options.Options) (*Config, error) { + genericAPIServerConfig := genericapiserver.NewConfig(authz.Codecs) + genericAPIServerConfig.BuildHandlerChainFunc = handler.BuildHandlerChain(nil, nil, nil) + genericAPIServerConfig.MergedResourceConfig = apiserver.DefaultAPIResourceConfigSource() + genericAPIServerConfig.EnableIndex = false + genericAPIServerConfig.EnableProfiling = false + + if err := util.SetupAuditConfig(genericAPIServerConfig, opts.Audit); err != nil { + return nil, err + } + if err := opts.Generic.ApplyTo(genericAPIServerConfig); err != nil { + return nil, err + } + if err := opts.SecureServing.ApplyTo(&genericAPIServerConfig.SecureServing, &genericAPIServerConfig.LoopbackClientConfig); err != nil { + return nil, err + } + + openapi.SetupOpenAPI(genericAPIServerConfig, generatedopenapi.GetOpenAPIDefinitions, title, license, opts.Generic.ExternalHost, opts.Generic.ExternalPort) + + // storageFactory + storageFactoryConfig := storage.NewFactoryConfig(authz.Codecs, authz.Scheme) + storageFactoryConfig.APIResourceConfig = genericAPIServerConfig.MergedResourceConfig + completedStorageFactoryConfig, err := storageFactoryConfig.Complete(opts.ETCD) + if err != nil { + return nil, err + } + storageFactory, err := completedStorageFactoryConfig.New() + if err != nil { + return nil, err + } + if err := opts.ETCD.ApplyWithStorageFactoryTo(storageFactory, genericAPIServerConfig); err != nil { + return nil, err + } + + // client config + genericAPIServerConfig.LoopbackClientConfig.ContentConfig.ContentType = "application/vnd.kubernetes.protobuf" + + kubeClientConfig := genericAPIServerConfig.LoopbackClientConfig + clientgoExternalClient, err := versionedclientset.NewForConfig(kubeClientConfig) + if err != nil { + return nil, fmt.Errorf("failed to create real external clientset: %v", err) + } + versionedInformers := versionedinformers.NewSharedInformerFactory(clientgoExternalClient, 10*time.Minute) + + debug.SetupDebug(genericAPIServerConfig, opts.Debug) + + if err := authentication.SetupAuthentication(genericAPIServerConfig, opts.Authentication); err != nil { + return nil, err + } + + if err := authorization.SetupAuthorization(genericAPIServerConfig, opts.Authorization); err != nil { + return nil, err + } + + // client config for platform apiserver + platformAPIServerClientConfig, ok, err := controllerconfig.BuildClientConfig(opts.PlatformAPIClient) + if err != nil { + return nil, err + } + if !ok || platformAPIServerClientConfig == nil { + return nil, fmt.Errorf("failed to initialize client config of platform API server") + } + platformClient, err := versionedclientset.NewForConfig(rest.AddUserAgent(platformAPIServerClientConfig, "tke-authz-api")) + if err != nil { + return nil, err + } + + var policies []*authzv1.Policy + if opts.Authz.DefaultPoliciesConfig != "" { + content, err := ioutil.ReadFile(opts.Authz.DefaultPoliciesConfig) + if err != nil { + return nil, err + } + err = json.Unmarshal(content, &policies) + if err != nil { + return nil, err + } + } + var roles []*authzv1.Role + if opts.Authz.DefaultRolesConfig != "" { + content, err := ioutil.ReadFile(opts.Authz.DefaultRolesConfig) + if err != nil { + return nil, err + } + err = json.Unmarshal(content, &roles) + if err != nil { + return nil, err + } + } + + cfg := &Config{ + ServerName: serverName, + GenericAPIServerConfig: genericAPIServerConfig, + VersionedSharedInformerFactory: versionedInformers, + StorageFactory: storageFactory, + PlatformClient: platformClient.PlatformV1(), + DefaultPolicies: policies, + DefaultRoles: roles, + } + return cfg, nil +} diff --git a/cmd/tke-authz-api/app/options/authz.go b/cmd/tke-authz-api/app/options/authz.go new file mode 100644 index 000000000..9428536b1 --- /dev/null +++ b/cmd/tke-authz-api/app/options/authz.go @@ -0,0 +1,61 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the “License”); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an “AS IS” BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package options + +import ( + "github.com/spf13/pflag" + "github.com/spf13/viper" +) + +const ( + flagDefaultPoliciesConfig = "default-policies-config" + flagDefaultRolesConfig = "default-roles-config" +) + +const ( + configDefaultPoliciesConfig = "authz.default_policies_config" + configDefaultRolesConfig = "authz.default_roles_config" +) + +type AuthzOptions struct { + DefaultPoliciesConfig string + DefaultRolesConfig string +} + +func NewAuthzOptions() *AuthzOptions { + return &AuthzOptions{} +} + +// AddFlags adds flags for console to the specified FlagSet object. +func (o *AuthzOptions) AddFlags(fs *pflag.FlagSet) { + fs.StringVar(&o.DefaultPoliciesConfig, flagDefaultPoliciesConfig, o.DefaultPoliciesConfig, "Default policies config") + _ = viper.BindPFlag(configDefaultPoliciesConfig, fs.Lookup(flagDefaultPoliciesConfig)) + + fs.StringVar(&o.DefaultRolesConfig, flagDefaultRolesConfig, o.DefaultRolesConfig, "Default roles config") + _ = viper.BindPFlag(configDefaultRolesConfig, fs.Lookup(flagDefaultRolesConfig)) +} + +// ApplyFlags parsing parameters from the command line or configuration file +// to the options instance. +func (o *AuthzOptions) ApplyFlags() []error { + var errs []error + o.DefaultPoliciesConfig = viper.GetString(configDefaultPoliciesConfig) + o.DefaultRolesConfig = viper.GetString(configDefaultRolesConfig) + return errs +} diff --git a/cmd/tke-authz-api/app/options/options.go b/cmd/tke-authz-api/app/options/options.go new file mode 100644 index 000000000..16b7e66a3 --- /dev/null +++ b/cmd/tke-authz-api/app/options/options.go @@ -0,0 +1,121 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package options + +import ( + "fmt" + + "github.com/spf13/pflag" + genericapiserveroptions "k8s.io/apiserver/pkg/server/options" + apiserveroptions "tkestack.io/tke/pkg/apiserver/options" + storageoptions "tkestack.io/tke/pkg/apiserver/storage/options" + controlleroptions "tkestack.io/tke/pkg/controller/options" + "tkestack.io/tke/pkg/util/cachesize" + "tkestack.io/tke/pkg/util/log" +) + +// Options is the main context object for the TKE application apiserver. +type Options struct { + Log *log.Options + SecureServing *apiserveroptions.SecureServingOptions + Debug *apiserveroptions.DebugOptions + ETCD *storageoptions.ETCDStorageOptions + Generic *apiserveroptions.GenericOptions + Authentication *apiserveroptions.AuthenticationWithAPIOptions + Authorization *apiserveroptions.AuthorizationOptions + PlatformAPIClient *controlleroptions.APIServerClientOptions + Audit *genericapiserveroptions.AuditOptions + Authz *AuthzOptions +} + +// NewOptions creates a new Options with a default config. +func NewOptions(serverName string) *Options { + return &Options{ + Log: log.NewOptions(), + SecureServing: apiserveroptions.NewSecureServingOptions(serverName, 9466), + Debug: apiserveroptions.NewDebugOptions(), + ETCD: storageoptions.NewETCDStorageOptions("/tke/authz"), + Generic: apiserveroptions.NewGenericOptions(), + Authentication: apiserveroptions.NewAuthenticationWithAPIOptions(), + Authorization: apiserveroptions.NewAuthorizationOptions(), + PlatformAPIClient: controlleroptions.NewAPIServerClientOptions("platform", true), + Audit: genericapiserveroptions.NewAuditOptions(), + Authz: NewAuthzOptions(), + } +} + +// AddFlags adds flags for a specific server to the specified FlagSet object. +func (o *Options) AddFlags(fs *pflag.FlagSet) { + o.Log.AddFlags(fs) + o.SecureServing.AddFlags(fs) + o.Debug.AddFlags(fs) + o.ETCD.AddFlags(fs) + o.Generic.AddFlags(fs) + o.Authentication.AddFlags(fs) + o.Authorization.AddFlags(fs) + o.PlatformAPIClient.AddFlags(fs) + o.Audit.AddFlags(fs) + o.Authz.AddFlags(fs) +} + +// ApplyFlags parsing parameters from the command line or configuration file +// to the options instance. +func (o *Options) ApplyFlags() []error { + var errs []error + + errs = append(errs, o.Log.ApplyFlags()...) + errs = append(errs, o.SecureServing.ApplyFlags()...) + errs = append(errs, o.Debug.ApplyFlags()...) + errs = append(errs, o.ETCD.ApplyFlags()...) + errs = append(errs, o.Generic.ApplyFlags()...) + errs = append(errs, o.Authentication.ApplyFlags()...) + errs = append(errs, o.Authorization.ApplyFlags()...) + errs = append(errs, o.PlatformAPIClient.ApplyFlags()...) + errs = append(errs, o.Authz.ApplyFlags()...) + + return errs +} + +// Complete set default Options. +// Should be called after tke-authz-api flags parsed. +func (o *Options) Complete() error { + if err := apiserveroptions.CompleteGenericAndSecureOptions(o.Generic, o.SecureServing); err != nil { + return err + } + + if o.ETCD.EnableWatchCache { + log.Infof("Initializing cache sizes based on %dMB limit", o.ETCD.DefaultWatchCacheSize) + sizes := cachesize.NewHeuristicWatchCacheSizes(o.ETCD.DefaultWatchCacheSize) + if userSpecified, err := genericapiserveroptions.ParseWatchCacheSizes(o.ETCD.WatchCacheSizes); err == nil { + for resource, size := range userSpecified { + sizes[resource] = size + } + } + + watchCacheSizes, err := genericapiserveroptions.WriteWatchCacheSizes(sizes) + if err != nil { + return err + } + o.ETCD.WatchCacheSizes = watchCacheSizes + } + if (o.Audit.WebhookOptions.ConfigFile != "" || o.Audit.LogOptions.Path != "") && o.Audit.PolicyFile == "" { + return fmt.Errorf("audit log/webhook config specified, but audit policy file is empty") + } + return nil +} diff --git a/cmd/tke-authz-api/app/run.go b/cmd/tke-authz-api/app/run.go new file mode 100644 index 000000000..a040cd538 --- /dev/null +++ b/cmd/tke-authz-api/app/run.go @@ -0,0 +1,36 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package app + +import ( + "tkestack.io/tke/cmd/tke-authz-api/app/config" + "tkestack.io/tke/pkg/util/log" +) + +// Run runs the specified TKE notify apiserver. This should never exit. +func Run(cfg *config.Config, stopCh <-chan struct{}) error { + log.Info("Starting Tencent Kubernetes Engine Application API server") + + server, err := CreateServerChain(cfg) + if err != nil { + return err + } + + return server.PrepareRun().Run(stopCh) +} diff --git a/cmd/tke-authz-api/app/server.go b/cmd/tke-authz-api/app/server.go new file mode 100644 index 000000000..d645579dc --- /dev/null +++ b/cmd/tke-authz-api/app/server.go @@ -0,0 +1,103 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package app + +import ( + "context" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + genericapiserver "k8s.io/apiserver/pkg/server" + versionedclientset "tkestack.io/tke/api/client/clientset/versioned" + "tkestack.io/tke/cmd/tke-authz-api/app/config" + "tkestack.io/tke/pkg/authz/apiserver" + "tkestack.io/tke/pkg/platform/apiserver/filter" + "tkestack.io/tke/pkg/util/log" +) + +// CreateServerChain creates the api servers connected via delegation. +func CreateServerChain(cfg *config.Config) (*genericapiserver.GenericAPIServer, error) { + apiServerConfig := createAPIServerConfig(cfg) + apiServer, err := CreateAPIServer(apiServerConfig, genericapiserver.NewEmptyDelegate()) + if err != nil { + return nil, err + } + + if err := registerHandler(apiServer); err != nil { + return nil, err + } + + apiServer.GenericAPIServer.AddPostStartHookOrDie("start-authz-api-server-informers", func(ctx genericapiserver.PostStartHookContext) error { + cfg.VersionedSharedInformerFactory.Start(ctx.StopCh) + return nil + }) + apiServer.GenericAPIServer.AddPostStartHookOrDie("init-authz-default", func(ctx genericapiserver.PostStartHookContext) error { + client, err := versionedclientset.NewForConfig(ctx.LoopbackClientConfig) + if err != nil { + log.Warnf("failed to generate authz client, err '%#v'", err) + return err + } + log.Infof("init default policies ...") + for _, pol := range cfg.DefaultPolicies { + if _, err := client.AuthzV1().Policies(pol.Namespace).Create(context.TODO(), pol, metav1.CreateOptions{}); err != nil && !errors.IsAlreadyExists(err) { + log.Warnf("failed to init policy '%s/%s', err '%#v'", pol.Namespace, pol.Name, err) + return err + } + } + log.Infof("init default roles ...") + for _, rol := range cfg.DefaultRoles { + if _, err := client.AuthzV1().Roles(rol.Namespace).Create(context.TODO(), rol, metav1.CreateOptions{}); err != nil && !errors.IsAlreadyExists(err) { + log.Warnf("failed to init role '%s/%s', err '%#v'", rol.Namespace, rol.Name, err) + return err + } + } + return nil + }) + return apiServer.GenericAPIServer, nil +} + +// CreateAPIServer creates and wires a workable tke-business-api +func CreateAPIServer(apiServerConfig *apiserver.Config, delegateAPIServer genericapiserver.DelegationTarget) (*apiserver.APIServer, error) { + return apiServerConfig.Complete().New(delegateAPIServer) +} + +func createAPIServerConfig(cfg *config.Config) *apiserver.Config { + return &apiserver.Config{ + GenericConfig: &genericapiserver.RecommendedConfig{ + Config: *cfg.GenericAPIServerConfig, + }, + ExtraConfig: apiserver.ExtraConfig{ + ServerName: cfg.ServerName, + VersionedInformers: cfg.VersionedSharedInformerFactory, + StorageFactory: cfg.StorageFactory, + APIResourceConfigSource: cfg.StorageFactory.APIResourceConfigSource, + PlatformClient: cfg.PlatformClient, + }, + } +} + +func createFilterChain(apiServer *genericapiserver.GenericAPIServer) { + apiServer.Handler.FullHandlerChain = filter.WithFuzzyResource(apiServer.Handler.FullHandlerChain) + apiServer.Handler.FullHandlerChain = filter.WithCluster(apiServer.Handler.FullHandlerChain) +} + +func registerHandler(apiServer *apiserver.APIServer) error { + createFilterChain(apiServer.GenericAPIServer) + log.Info("All of http handlers registered", log.Strings("paths", apiServer.GenericAPIServer.Handler.ListedPaths())) + return nil +} diff --git a/cmd/tke-authz-controller/app/app.go b/cmd/tke-authz-controller/app/app.go new file mode 100644 index 000000000..811ad213d --- /dev/null +++ b/cmd/tke-authz-controller/app/app.go @@ -0,0 +1,61 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package app + +import ( + commonapiserver "k8s.io/apiserver/pkg/server" + "tkestack.io/tke/cmd/tke-authz-controller/app/config" + "tkestack.io/tke/cmd/tke-authz-controller/app/options" + "tkestack.io/tke/pkg/app" + "tkestack.io/tke/pkg/util/log" +) + +const commandDesc = `The authz controller manager is a daemon that embeds the core control loops. In + authz of robotics and automation, a control loop is a non-terminating + loop that regulates the state of the system. In TKE, a controller is a control + loop that watches the shared state of the application through the + apiserver and makes changes attempting to move the current state towards the + desired state.` + +// NewApp creates a App object with default parameters. +func NewApp(basename string) *app.App { + opts := options.NewOptions(basename, KnownControllers(), ControllersDisabledByDefault.List()) + application := app.NewApp("Tencent Kubernetes Engine Application Controller Manager", + basename, + app.WithOptions(opts), + app.WithDescription(commandDesc), + app.WithRunFunc(run(opts)), + ) + return application +} + +func run(opts *options.Options) app.RunFunc { + return func(basename string) error { + log.Init(opts.Log) + defer log.Flush() + + cfg, err := config.CreateConfigFromOptions(basename, opts) + if err != nil { + return err + } + + stopCh := commonapiserver.SetupSignalHandler() + return Run(cfg, stopCh) + } +} diff --git a/cmd/tke-authz-controller/app/authz.go b/cmd/tke-authz-controller/app/authz.go new file mode 100644 index 000000000..5ace327f4 --- /dev/null +++ b/cmd/tke-authz-controller/app/authz.go @@ -0,0 +1,73 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package app + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "net/http" + "time" + authzv1 "tkestack.io/tke/api/authz/v1" + "tkestack.io/tke/pkg/authz/controller/multiclusterrolebinding" + "tkestack.io/tke/pkg/authz/controller/policy" + "tkestack.io/tke/pkg/authz/controller/role" +) + +func startMultiClusterRoleBindingController(ctx ControllerContext) (http.Handler, bool, error) { + if !ctx.AvailableResources[schema.GroupVersionResource{Group: authzv1.GroupName, Version: "v1", Resource: "multiclusterrolebindings"}] { + return nil, false, nil + } + ctrl := multiclusterrolebinding.NewController( + ctx.ClientBuilder.ClientOrDie("multiclusterrolebinding-controller"), + ctx.PlatformClient, + ctx.InformerFactory.Authz().V1().Policies(), + ctx.InformerFactory.Authz().V1().Roles(), + ctx.InformerFactory.Authz().V1().MultiClusterRoleBindings(), + 3*time.Minute, + ) + go ctrl.Run(4, ctx.Stop) + return nil, true, nil +} + +func startPolicyController(ctx ControllerContext) (http.Handler, bool, error) { + if !ctx.AvailableResources[schema.GroupVersionResource{Group: authzv1.GroupName, Version: "v1", Resource: "policies"}] { + return nil, false, nil + } + ctrl := policy.NewController( + ctx.ClientBuilder.ClientOrDie("policy-controller"), + ctx.InformerFactory.Authz().V1().Policies(), + 5*time.Minute, + ) + go ctrl.Run(4, ctx.Stop) + return nil, true, nil +} + +func startRoleController(ctx ControllerContext) (http.Handler, bool, error) { + if !ctx.AvailableResources[schema.GroupVersionResource{Group: authzv1.GroupName, Version: "v1", Resource: "roles"}] { + return nil, false, nil + } + ctrl := role.NewController( + ctx.ClientBuilder.ClientOrDie("role-controller"), + ctx.PlatformClient, + ctx.InformerFactory.Authz().V1().Roles(), + ctx.InformerFactory.Authz().V1().MultiClusterRoleBindings(), + 5*time.Minute, + ) + go ctrl.Run(4, ctx.Stop) + return nil, true, nil +} diff --git a/cmd/tke-authz-controller/app/config/config.go b/cmd/tke-authz-controller/app/config/config.go new file mode 100644 index 000000000..5b63a6d51 --- /dev/null +++ b/cmd/tke-authz-controller/app/config/config.go @@ -0,0 +1,104 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package config + +import ( + "fmt" + "net" + + "k8s.io/apiserver/pkg/authentication/request/anonymous" + "k8s.io/apiserver/pkg/authorization/authorizerfactory" + apiserver "k8s.io/apiserver/pkg/server" + restclient "k8s.io/client-go/rest" + versionedclientset "tkestack.io/tke/api/client/clientset/versioned" + "tkestack.io/tke/cmd/tke-authz-controller/app/options" + controllerconfig "tkestack.io/tke/pkg/controller/config" + controlleroptions "tkestack.io/tke/pkg/controller/options" +) + +// Config is the running configuration structure of the TKE controller manager. +type Config struct { + SecureServing *apiserver.SecureServingInfo + // LoopbackClientConfig is a config for a privileged loopback connection + LoopbackClientConfig *restclient.Config + Authentication apiserver.AuthenticationInfo + Authorization apiserver.AuthorizationInfo + ServerName string + // the client only used for leader election + LeaderElectionClient *versionedclientset.Clientset + Component controlleroptions.ComponentConfiguration + + // the rest config for the authz apiserver + AuthzAPIServerClientConfig *restclient.Config + // the rest config for the platform apiserver + PlatformAPIServerClientConfig *restclient.Config +} + +// CreateConfigFromOptions creates a running configuration instance based +// on a given TKE apiserver command line or configuration file option. +func CreateConfigFromOptions(serverName string, opts *options.Options) (*Config, error) { + if err := opts.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{net.ParseIP("127.0.0.1")}); err != nil { + return nil, fmt.Errorf("error creating self-signed certificates: %v", err) + } + + authzAPIServerClientConfig, ok, err := controllerconfig.BuildClientConfig(opts.AuthzAPIClient) + if err != nil { + return nil, err + } + if !ok { + return nil, fmt.Errorf("failed to initialize client config of application API server") + } + + // shallow copy, do not modify the apiServerClientConfig.Timeout. + config := *authzAPIServerClientConfig + config.Timeout = opts.Component.LeaderElection.RenewDeadline + leaderElectionClient := versionedclientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "leader-election")) + + platformAPIServerClientConfig, ok, err := controllerconfig.BuildClientConfig(opts.PlatformAPIClient) + if err != nil { + return nil, err + } + if !ok { + return nil, fmt.Errorf("failed to initialize client config of platform API server") + } + + controllerManagerConfig := &Config{ + ServerName: serverName, + LeaderElectionClient: leaderElectionClient, + Authorization: apiserver.AuthorizationInfo{ + Authorizer: authorizerfactory.NewAlwaysAllowAuthorizer(), + }, + Authentication: apiserver.AuthenticationInfo{ + Authenticator: anonymous.NewAuthenticator(), + }, + AuthzAPIServerClientConfig: authzAPIServerClientConfig, + PlatformAPIServerClientConfig: platformAPIServerClientConfig, + } + + if err := opts.Component.ApplyTo(&controllerManagerConfig.Component); err != nil { + return nil, err + } + if err := opts.SecureServing.ApplyTo(&controllerManagerConfig.SecureServing, &controllerManagerConfig.LoopbackClientConfig); err != nil { + return nil, err + } + if err := opts.Debug.ApplyTo(&controllerManagerConfig.Component.Debugging); err != nil { + return nil, err + } + return controllerManagerConfig, nil +} diff --git a/cmd/tke-authz-controller/app/context.go b/cmd/tke-authz-controller/app/context.go new file mode 100644 index 000000000..3553bfac0 --- /dev/null +++ b/cmd/tke-authz-controller/app/context.go @@ -0,0 +1,129 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package app + +import ( + "fmt" + "net/http" + "time" + + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/wait" + cacheddiscovery "k8s.io/client-go/discovery/cached" + "k8s.io/client-go/rest" + "k8s.io/client-go/restmapper" + versionedclientset "tkestack.io/tke/api/client/clientset/versioned" + platformv1 "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + versionedinformers "tkestack.io/tke/api/client/informers/externalversions" + "tkestack.io/tke/cmd/tke-authz-controller/app/config" + "tkestack.io/tke/pkg/controller" + "tkestack.io/tke/pkg/controller/util" +) + +// InitFunc is used to launch a particular controller. It may run additional "should I activate checks". +// Any error returned will cause the controller process to `Fatal` +// The bool indicates whether the controller was enabled. +type InitFunc func(ctx ControllerContext) (debuggingHandler http.Handler, enabled bool, err error) + +// ControllerContext represents the context of controller. +type ControllerContext struct { + // ClientBuilder will provide a client for this controller to use + ClientBuilder controller.ClientBuilder + + // InformerFactory gives access to informers for the controller. + InformerFactory versionedinformers.SharedInformerFactory + + // Config provides access to init options for a given controller + Config config.Config + + // DeferredDiscoveryRESTMapper is a RESTMapper that will defer + // initialization of the RESTMapper until the first mapping is + // requested. + RESTMapper *restmapper.DeferredDiscoveryRESTMapper + + // AvailableResources is a map listing currently available resources + AvailableResources map[schema.GroupVersionResource]bool + + // Stop is the stop channel + Stop <-chan struct{} + + // InformersStarted is closed after all of the controllers have been initialized and are running. After this point it is safe, + // for an individual controller to start the shared informers. Before it is closed, they should not. + InformersStarted chan struct{} + + // ResyncPeriod generates a duration each time it is invoked; this is so that + // multiple controllers don't get into lock-step and all hammer the apiserver + // with list requests simultaneously. + ResyncPeriod func() time.Duration + ControllerStartInterval time.Duration + + PlatformClient platformv1.PlatformV1Interface +} + +// IsControllerEnabled returns whether the controller has been enabled +func (c ControllerContext) IsControllerEnabled(name string) bool { + return util.IsControllerEnabled(name, ControllersDisabledByDefault) +} + +// CreateControllerContext creates a context struct containing references to resources needed by the +// controllers such as the cloud provider and clientBuilder. rootClientBuilder is only used for +// the shared-informers client and token controller. +func CreateControllerContext(cfg *config.Config, rootClientBuilder controller.ClientBuilder, stop <-chan struct{}) (ControllerContext, error) { + platformClient, err := versionedclientset.NewForConfig(rest.AddUserAgent(cfg.PlatformAPIServerClientConfig, "tke-authz-controller")) + if err != nil { + return ControllerContext{}, fmt.Errorf("failed to create the platform client: %v", err) + } + + versionedClient := rootClientBuilder.ClientOrDie("shared-informers") + sharedInformers := versionedinformers.NewSharedInformerFactory(versionedClient, controller.ResyncPeriod(&cfg.Component)()) + + // If apiserver is not running we should wait for some time and fail only then. This is particularly + // important when we start apiserver and controller manager at the same time. + if err := controller.WaitForAPIServer(versionedClient, 10*time.Second); err != nil { + return ControllerContext{}, fmt.Errorf("failed to wait for apiserver being healthy: %v", err) + } + + // Use a discovery client capable of being refreshed. + discoveryClient := rootClientBuilder.ClientOrDie("controller-discovery") + cachedClient := cacheddiscovery.NewMemCacheClient(discoveryClient.Discovery()) + restMapper := restmapper.NewDeferredDiscoveryRESTMapper(cachedClient) + go wait.Until(func() { + restMapper.Reset() + }, 5*time.Minute, stop) + + availableResources, err := controller.GetAvailableResources(rootClientBuilder) + if err != nil { + return ControllerContext{}, err + } + + ctx := ControllerContext{ + ClientBuilder: rootClientBuilder, + InformerFactory: sharedInformers, + Config: *cfg, + RESTMapper: restMapper, + AvailableResources: availableResources, + Stop: stop, + InformersStarted: make(chan struct{}), + ResyncPeriod: controller.ResyncPeriod(&cfg.Component), + ControllerStartInterval: cfg.Component.ControllerStartInterval, + PlatformClient: platformClient.PlatformV1(), + } + + return ctx, nil +} diff --git a/cmd/tke-authz-controller/app/controller.go b/cmd/tke-authz-controller/app/controller.go new file mode 100644 index 000000000..7737a1590 --- /dev/null +++ b/cmd/tke-authz-controller/app/controller.go @@ -0,0 +1,85 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package app + +import ( + "net/http" + "time" + + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/apiserver/pkg/server/mux" + "tkestack.io/tke/pkg/util/log" +) + +const ( + // ControllerStartJitter used when starting controller managers. + ControllerStartJitter = 1.0 +) + +// ControllersDisabledByDefault configured all controllers that are turned off +// by default. +var ControllersDisabledByDefault = sets.NewString() + +// KnownControllers returns the known controllers. +func KnownControllers() []string { + ret := sets.StringKeySet(NewControllerInitializers()) + return ret.List() +} + +// NewControllerInitializers is a public map of named controller groups (you can start more than one in an init func) +// paired to their InitFunc. This allows for structured downstream composition and subdivision. +func NewControllerInitializers() map[string]InitFunc { + controllers := map[string]InitFunc{} + controllers["policies"] = startPolicyController + controllers["roles"] = startRoleController + controllers["multiclusterrolebindings"] = startMultiClusterRoleBindingController + return controllers +} + +// StartControllers to start the controller. +func StartControllers(ctx ControllerContext, controllers map[string]InitFunc, unsecuredMux *mux.PathRecorderMux) error { + for controllerName, initFn := range controllers { + if !ctx.IsControllerEnabled(controllerName) { + log.Warnf("%q is disabled", controllerName) + continue + } + + time.Sleep(wait.Jitter(ctx.ControllerStartInterval, ControllerStartJitter)) + + log.Infof("Starting %q", controllerName) + debugHandler, started, err := initFn(ctx) + if err != nil { + log.Errorf("Error starting %q", controllerName) + return err + } + if !started { + log.Warnf("Skipping %q", controllerName) + continue + } + if debugHandler != nil && unsecuredMux != nil { + basePath := "/debug/controllers/" + controllerName + unsecuredMux.UnlistedHandle(basePath, http.StripPrefix(basePath, debugHandler)) + unsecuredMux.UnlistedHandlePrefix(basePath+"/", http.StripPrefix(basePath, debugHandler)) + } + log.Infof("Started %q", controllerName) + } + + return nil +} diff --git a/cmd/tke-authz-controller/app/options/feature.go b/cmd/tke-authz-controller/app/options/feature.go new file mode 100644 index 000000000..53f5750cc --- /dev/null +++ b/cmd/tke-authz-controller/app/options/feature.go @@ -0,0 +1,89 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the “License”); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an “AS IS” BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package options + +import ( + "time" + + "github.com/spf13/pflag" + "github.com/spf13/viper" + appconfig "tkestack.io/tke/pkg/application/config" +) + +const ( + flagConcurrentSyncs = "concurrent-app-syncs" + flagSyncAppPeriod = "sync-app-period" +) + +const ( + configSyncAppPeriod = "controller.sync_app_period" + configConcurrentAppSyncs = "controller.concurrent_app_syncs" +) + +// ControllerOptions contains configuration items related to application attributes. +type ControllerOptions struct { + SyncAppPeriod time.Duration + ConcurrentAppSyncs int +} + +// FeatureOptions contains configuration items related to application attributes. +type FeatureOptions struct { + Controller ControllerOptions +} + +// NewFeatureOptions creates a FeatureOptions object with default parameters. +func NewFeatureOptions() *FeatureOptions { + return &FeatureOptions{ + Controller: ControllerOptions{ + SyncAppPeriod: defaultSyncPeriod, + ConcurrentAppSyncs: defaultconcurrentSyncs, + }, + } +} + +// AddFlags adds flags for console to the specified FlagSet object. +func (o *FeatureOptions) AddFlags(fs *pflag.FlagSet) { + fs.DurationVar(&o.Controller.SyncAppPeriod, flagSyncAppPeriod, o.Controller.SyncAppPeriod, "The period for app health checks") + _ = viper.BindPFlag(configSyncAppPeriod, fs.Lookup(flagSyncAppPeriod)) + + fs.IntVar(&o.Controller.ConcurrentAppSyncs, flagConcurrentSyncs, o.Controller.ConcurrentAppSyncs, "The number of app objects that are allowed to sync concurrently. Larger number = more responsive app termination, but more CPU (and network) load") + _ = viper.BindPFlag(configConcurrentAppSyncs, fs.Lookup(flagConcurrentSyncs)) +} + +// ApplyFlags parsing parameters from the command line or configuration file +// to the options instance. +func (o *FeatureOptions) ApplyFlags() []error { + var errs []error + + o.Controller.SyncAppPeriod = viper.GetDuration(configSyncAppPeriod) + o.Controller.ConcurrentAppSyncs = viper.GetInt(configConcurrentAppSyncs) + return errs +} + +// ApplyTo fills up Debugging config with options. +func (o *ControllerOptions) ApplyTo(cfg *appconfig.AppControllerConfiguration) error { + if o == nil { + return nil + } + + cfg.ConcurrentSyncs = o.ConcurrentAppSyncs + cfg.SyncPeriod = o.SyncAppPeriod + + return nil +} diff --git a/cmd/tke-authz-controller/app/options/options.go b/cmd/tke-authz-controller/app/options/options.go new file mode 100644 index 000000000..9a04a9f40 --- /dev/null +++ b/cmd/tke-authz-controller/app/options/options.go @@ -0,0 +1,85 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package options + +import ( + "time" + + "github.com/spf13/pflag" + apiserveroptions "tkestack.io/tke/pkg/apiserver/options" + controlleroptions "tkestack.io/tke/pkg/controller/options" + "tkestack.io/tke/pkg/util/log" +) + +const ( + defaultSyncPeriod = 30 * time.Second + defaultconcurrentSyncs = 10 +) + +// Options is the main context object for the TKE controller manager. +type Options struct { + Log *log.Options + Debug *apiserveroptions.DebugOptions + SecureServing *apiserveroptions.SecureServingOptions + Component *controlleroptions.ComponentOptions + AuthzAPIClient *controlleroptions.APIServerClientOptions + PlatformAPIClient *controlleroptions.APIServerClientOptions + + FeatureOptions *FeatureOptions +} + +// NewOptions creates a new Options with a default config. +func NewOptions(serverName string, allControllers []string, disabledByDefaultControllers []string) *Options { + return &Options{ + Log: log.NewOptions(), + Debug: apiserveroptions.NewDebugOptions(), + SecureServing: apiserveroptions.NewSecureServingOptions(serverName, 9467), + Component: controlleroptions.NewComponentOptions(allControllers, disabledByDefaultControllers), + AuthzAPIClient: controlleroptions.NewAPIServerClientOptions("authz", true), + PlatformAPIClient: controlleroptions.NewAPIServerClientOptions("platform", true), + FeatureOptions: NewFeatureOptions(), + } +} + +// AddFlags adds flags for a specific server to the specified FlagSet object. +func (o *Options) AddFlags(fs *pflag.FlagSet) { + o.Log.AddFlags(fs) + o.Debug.AddFlags(fs) + o.SecureServing.AddFlags(fs) + o.Component.AddFlags(fs) + o.AuthzAPIClient.AddFlags(fs) + o.PlatformAPIClient.AddFlags(fs) + o.FeatureOptions.AddFlags(fs) +} + +// ApplyFlags parsing parameters from the command line or configuration file +// to the options instance. +func (o *Options) ApplyFlags() []error { + var errs []error + + errs = append(errs, o.Log.ApplyFlags()...) + errs = append(errs, o.Debug.ApplyFlags()...) + errs = append(errs, o.SecureServing.ApplyFlags()...) + errs = append(errs, o.Component.ApplyFlags()...) + errs = append(errs, o.AuthzAPIClient.ApplyFlags()...) + errs = append(errs, o.PlatformAPIClient.ApplyFlags()...) + errs = append(errs, o.FeatureOptions.ApplyFlags()...) + + return errs +} diff --git a/cmd/tke-authz-controller/app/run.go b/cmd/tke-authz-controller/app/run.go new file mode 100644 index 000000000..360b2b3d6 --- /dev/null +++ b/cmd/tke-authz-controller/app/run.go @@ -0,0 +1,115 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package app + +import ( + "context" + "os" + "time" + "tkestack.io/tke/api/authz" + + "k8s.io/apimachinery/pkg/util/uuid" + "k8s.io/apiserver/pkg/server/healthz" + "tkestack.io/tke/cmd/tke-authz-controller/app/config" + "tkestack.io/tke/pkg/controller" + "tkestack.io/tke/pkg/util/leaderelection" + "tkestack.io/tke/pkg/util/leaderelection/resourcelock" + "tkestack.io/tke/pkg/util/log" +) + +// Run runs the specified application controller manager. This should never exit. +func Run(cfg *config.Config, stopCh <-chan struct{}) error { + log.Info("Starting Tencent Kubernetes Engine application controller manager") + + // Setup any healthz checks we will want to use. + var checks []healthz.HealthChecker + var electionChecker *leaderelection.HealthzAdaptor + if cfg.Component.LeaderElection.LeaderElect { + electionChecker = leaderelection.NewLeaderHealthzAdaptor(time.Second * 20) + checks = append(checks, electionChecker) + } + + // Start the controller manager HTTP server + // serverMux is the handler for these controller *after* authn/authz filters have been applied + serverMux := controller.NewBaseHandler(&cfg.Component.Debugging, checks...) + handler := controller.BuildHandlerChain(serverMux, &cfg.Authorization, &cfg.Authentication, authz.Codecs) + if _, err := cfg.SecureServing.Serve(handler, 0, stopCh); err != nil { + return err + } + + run := func(ctx context.Context) { + rootClientBuilder := controller.SimpleControllerClientBuilder{ + ClientConfig: cfg.AuthzAPIServerClientConfig, + } + + controllerContext, err := CreateControllerContext(cfg, rootClientBuilder, ctx.Done()) + if err != nil { + log.Fatalf("error building controller context: %v", err) + } + + if err := StartControllers(controllerContext, NewControllerInitializers(), serverMux); err != nil { + log.Fatalf("error starting controllers: %v", err) + } + + controllerContext.InformerFactory.Start(controllerContext.Stop) + close(controllerContext.InformersStarted) + + select {} + } + + ctx, cancel := context.WithCancel(context.TODO()) + go func() { + <-stopCh + cancel() + }() + + if !cfg.Component.LeaderElection.LeaderElect { + run(ctx) + panic("unreachable") + } + + id, err := os.Hostname() + if err != nil { + return err + } + + // add a uniquifier so that two processes on the same host don't accidentally both become active + id = id + "_" + string(uuid.NewUUID()) + rl := resourcelock.NewAuthz(cfg.ServerName, + cfg.LeaderElectionClient.AuthzV1(), + resourcelock.Config{ + Identity: id, + }) + + leaderelection.RunOrDie(ctx, leaderelection.ElectionConfig{ + Lock: rl, + LeaseDuration: cfg.Component.LeaderElection.LeaseDuration.Duration, + RenewDeadline: cfg.Component.LeaderElection.RenewDeadline.Duration, + RetryPeriod: cfg.Component.LeaderElection.RetryPeriod.Duration, + Callbacks: leaderelection.LeaderCallbacks{ + OnStartedLeading: run, + OnStoppedLeading: func() { + log.Fatalf("leaderelection lost") + }, + }, + WatchDog: electionChecker, + Name: cfg.ServerName, + }) + panic("unreachable") +} diff --git a/cmd/tke-authz-controller/controller-manager.go b/cmd/tke-authz-controller/controller-manager.go new file mode 100644 index 000000000..932ca174c --- /dev/null +++ b/cmd/tke-authz-controller/controller-manager.go @@ -0,0 +1,37 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the “License”); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an “AS IS” BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package main + +import ( + "math/rand" + "os" + "runtime" + "time" + + "tkestack.io/tke/cmd/tke-authz-controller/app" +) + +func main() { + rand.Seed(time.Now().UTC().UnixNano()) + if len(os.Getenv("GOMAXPROCS")) == 0 { + runtime.GOMAXPROCS(runtime.NumCPU()) + } + + app.NewApp("tke-authz-controller").Run() +} diff --git a/hack/authz/policies.json b/hack/authz/policies.json new file mode 100644 index 000000000..4b0014cb9 --- /dev/null +++ b/hack/authz/policies.json @@ -0,0 +1,1041 @@ +[ + { + "metadata": { + "name": "pol-admin", + "namespace": "default", + "annotations": { + "authz.tkestack.io/region": "ap-guangzhou", + "authz.tkestack.io/provider-name": "clusternet" + } + }, + "displayName": "admin", + "description": "集群管理员身份,对集群内所有资源具有读写权限", + "scope": "MultiCluster", + "tenantID": "default", + "username": "admin", + "rules": [ + { + "apiGroups": [ + "*" + ], + "resources": [ + "*" + ], + "verbs": [ + "*" + ] + }, + { + "nonResourceURLs": [ + "*" + ], + "verbs": [ + "*" + ] + } + ] + }, + { + "metadata": { + "name": "pol-view", + "namespace": "default", + "annotations": { + "authz.tkestack.io/region": "ap-guangzhou", + "authz.tkestack.io/provider-name": "clusternet" + } + }, + "displayName": "view", + "description": "对所有命名空间或所选命名空间下控制台可见资源的只读权限", + "scope": "MultiCluster", + "tenantID": "default", + "username": "default", + "rules": [ + { + "apiGroups": [ + "" + ], + "resources": [ + "pods", + "pods/attach", + "pods/exec", + "pods/portforward", + "pods/proxy" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "" + ], + "resources": [ + "configmaps", + "endpoints", + "persistentvolumeclaims", + "replicationcontrollers", + "replicationcontrollers/scale", + "secrets", + "serviceaccounts", + "services", + "services/proxy" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "" + ], + "resources": [ + "nodes", + "persistentvolumes" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "" + ], + "resources": [ + "events", + "replicationcontrollers/status", + "pods/log", + "pods/status", + "componentstatuses" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "apps" + ], + "resources": [ + "daemonsets", + "deployments", + "deployments/rollback", + "deployments/scale", + "replicasets", + "replicasets/scale", + "statefulsets" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "autoscaling" + ], + "resources": [ + "horizontalpodautoscalers" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "storage.k8s.io" + ], + "resources": [ + "storageclasses" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "batch" + ], + "resources": [ + "cronjobs", + "jobs" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "extensions", + "networking.k8s.io" + ], + "resources": [ + "daemonsets", + "deployments", + "deployments/rollback", + "deployments/scale", + "ingresses", + "replicasets", + "replicasets/scale", + "replicationcontrollers/scale" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "servicecatalog.k8s.io" + ], + "resources": [ + "clusterserviceclasses", + "clusterserviceplans", + "clusterservicebrokers", + "serviceinstances", + "servicebindings" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "policy" + ], + "resources": [ + "poddisruptionbudgets" + ], + "verbs": [ + "get", + "list" + ] + }, + { + "apiGroups": [ + "networking.istio.io", + "config.istio.io", + "rbac.istio.io", + "authentication.istio.io", + "security.istio.io", + "install.istio.io" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "apiextensions.k8s.io" + ], + "resources": [ + "customresourcedefinitions" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "networking.tke.cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "ccs.cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "cls.cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "watch" + ] + } + ] + }, + { + "metadata": { + "name": "pol-ops", + "namespace": "default", + "annotations": { + "authz.tkestack.io/region": "ap-guangzhou", + "authz.tkestack.io/provider-name": "clusternet" + } + }, + "displayName": "ops", + "description": "对所有命名空间下资源的读写权限,拥有集群节点、存储卷、命名空间、配额的读写权限", + "scope": "MultiCluster", + "tenantID": "default", + "username": "admin", + "rules": [ + { + "apiGroups": [ + "" + ], + "resources": [ + "pods", + "pods/attach", + "pods/exec", + "pods/portforward", + "pods/proxy" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "" + ], + "resources": [ + "configmaps", + "endpoints", + "persistentvolumeclaims", + "replicationcontrollers", + "replicationcontrollers/scale", + "secrets", + "serviceaccounts", + "services", + "services/proxy" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "" + ], + "resources": [ + "bindings", + "events", + "limitranges", + "namespaces/status", + "replicationcontrollers/status", + "pods/log", + "pods/status", + "resourcequotas", + "resourcequotas/status", + "componentstatuses" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "" + ], + "resources": [ + "namespaces", + "nodes", + "persistentvolumes" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "apps" + ], + "resources": [ + "daemonsets", + "deployments", + "deployments/rollback", + "deployments/scale", + "replicasets", + "replicasets/scale", + "statefulsets" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "autoscaling" + ], + "resources": [ + "horizontalpodautoscalers" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "batch" + ], + "resources": [ + "cronjobs", + "jobs" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "extensions", + "networking.k8s.io" + ], + "resources": [ + "daemonsets", + "deployments", + "deployments/rollback", + "deployments/scale", + "ingresses", + "replicasets", + "replicasets/scale", + "replicationcontrollers/scale" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "servicecatalog.k8s.io" + ], + "resources": [ + "clusterserviceclasses", + "clusterserviceplans", + "clusterservicebrokers", + "serviceinstances", + "servicebindings" + ], + "verbs": [ + "create", + "delete", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "servicecatalog.k8s.io" + ], + "resources": [ + "clusterservicebrokers/status", + "clusterserviceclasses/status", + "clusterserviceplans/status", + "serviceinstances/status", + "serviceinstances/reference", + "servicebindings/status" + ], + "verbs": [ + "update" + ] + }, + { + "apiGroups": [ + "storage.k8s.io" + ], + "resources": [ + "storageclasses" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "policy" + ], + "resources": [ + "poddisruptionbudgets" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "networking.istio.io", + "config.istio.io", + "rbac.istio.io", + "authentication.istio.io", + "install.istio.io", + "security.istio.io" + ], + "resources": [ + "*" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "apiextensions.k8s.io" + ], + "resources": [ + "customresourcedefinitions" + ], + "verbs": [ + "get", + "list", + "create", + "watch", + "patch", + "update", + "delete", + "deletecollection" + ] + }, + { + "apiGroups": [ + "networking.tke.cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "create", + "watch", + "patch", + "update", + "delete", + "deletecollection" + ] + }, + { + "apiGroups": [ + "cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "create", + "watch", + "patch", + "update", + "delete", + "deletecollection" + ] + }, + { + "apiGroups": [ + "ccs.cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "create", + "watch", + "patch", + "update", + "delete", + "deletecollection" + ] + }, + { + "apiGroups": [ + "cls.cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "create", + "watch", + "patch", + "update", + "delete", + "deletecollection" + ] + } + ] + }, + { + "metadata": { + "name": "pol-dev", + "namespace": "default", + "annotations": { + "authz.tkestack.io/region": "ap-guangzhou", + "authz.tkestack.io/provider-name": "clusternet" + } + }, + "displayName": "dev", + "description": "对所有命名空间或所选命名空间下控制台可见资源的读写权限", + "scope": "MultiCluster", + "tenantID": "default", + "username": "admin", + "rules": [ + { + "apiGroups": [ + "" + ], + "resources": [ + "pods", + "pods/attach", + "pods/exec", + "pods/portforward", + "pods/proxy" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "" + ], + "resources": [ + "configmaps", + "endpoints", + "persistentvolumeclaims", + "replicationcontrollers", + "replicationcontrollers/scale", + "secrets", + "serviceaccounts", + "services", + "services/proxy" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "" + ], + "resources": [ + "events", + "replicationcontrollers/status", + "pods/log", + "pods/status", + "componentstatuses" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "" + ], + "resources": [ + "namespaces", + "nodes", + "persistentvolumes" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "apps" + ], + "resources": [ + "daemonsets", + "deployments", + "deployments/rollback", + "deployments/scale", + "replicasets", + "replicasets/scale", + "statefulsets" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "autoscaling" + ], + "resources": [ + "horizontalpodautoscalers" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "batch" + ], + "resources": [ + "cronjobs", + "jobs" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "extensions", + "networking.k8s.io" + ], + "resources": [ + "daemonsets", + "deployments", + "deployments/rollback", + "deployments/scale", + "ingresses", + "replicasets", + "replicasets/scale", + "replicationcontrollers/scale" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "servicecatalog.k8s.io" + ], + "resources": [ + "clusterserviceclasses", + "clusterserviceplans", + "clusterservicebrokers", + "serviceinstances", + "servicebindings" + ], + "verbs": [ + "create", + "delete", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "servicecatalog.k8s.io" + ], + "resources": [ + "clusterservicebrokers/status", + "clusterserviceclasses/status", + "clusterserviceplans/status", + "serviceinstances/status", + "serviceinstances/reference", + "servicebindings/status" + ], + "verbs": [ + "update" + ] + }, + { + "apiGroups": [ + "storage.k8s.io" + ], + "resources": [ + "storageclasses" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "policy" + ], + "resources": [ + "poddisruptionbudgets" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "networking.istio.io", + "config.istio.io", + "rbac.istio.io", + "authentication.istio.io", + "security.istio.io", + "install.istio.io" + ], + "resources": [ + "*" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "apiGroups": [ + "apiextensions.k8s.io" + ], + "resources": [ + "customresourcedefinitions" + ], + "verbs": [ + "get", + "list", + "create", + "watch", + "patch", + "update", + "delete", + "deletecollection" + ] + }, + { + "apiGroups": [ + "networking.tke.cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "ccs.cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "watch" + ] + }, + { + "apiGroups": [ + "cls.cloud.tencent.com" + ], + "resources": [ + "*" + ], + "verbs": [ + "get", + "list", + "watch" + ] + } + ] + } +] diff --git a/hack/authz/roles.json b/hack/authz/roles.json new file mode 100644 index 000000000..48f5ff7b1 --- /dev/null +++ b/hack/authz/roles.json @@ -0,0 +1,74 @@ +[ + { + "metadata":{ + "name":"rol-admin", + "namespace":"default", + "annotations":{ + "authz.tkestack.io/region":"ap-guangzhou", + "authz.tkestack.io/provider-name":"clusternet" + } + }, + "displayName":"admin", + "description":"集群管理员身份,对集群内所有资源具有读写权限", + "scope":"MultiCluster", + "tenantID":"default", + "username":"admin", + "policies":[ + "default/pol-admin" + ] + }, + { + "metadata":{ + "name":"rol-view", + "namespace":"default", + "annotations":{ + "authz.tkestack.io/region":"ap-guangzhou", + "authz.tkestack.io/provider-name":"clusternet" + } + }, + "displayName":"view", + "description":"对所有命名空间或所选命名空间下控制台可见资源的只读权限", + "scope":"MultiCluster", + "tenantID":"default", + "username":"admin", + "policies":[ + "default/pol-view" + ] + }, + { + "metadata":{ + "name":"rol-ops", + "namespace":"default", + "annotations":{ + "authz.tkestack.io/region":"ap-guangzhou", + "authz.tkestack.io/provider-name":"clusternet" + } + }, + "displayName":"ops", + "description":"对所有命名空间下资源的读写权限,拥有集群节点、存储卷、命名空间、配额的读写权限", + "scope":"MultiCluster", + "tenantID":"default", + "username":"admin", + "policies":[ + "default/pol-ops" + ] + }, + { + "metadata":{ + "name":"rol-dev", + "namespace":"default", + "annotations":{ + "authz.tkestack.io/region":"ap-guangzhou", + "authz.tkestack.io/provider-name":"clusternet" + } + }, + "displayName":"dev", + "description":"对所有命名空间或所选命名空间下控制台可见资源的读写权限", + "scope":"MultiCluster", + "tenantID":"default", + "username":"admin", + "policies":[ + "default/pol-dev" + ] + } +] diff --git a/pkg/apiserver/authentication/user.go b/pkg/apiserver/authentication/user.go index b0a3c8db6..271d85816 100644 --- a/pkg/apiserver/authentication/user.go +++ b/pkg/apiserver/authentication/user.go @@ -20,6 +20,8 @@ package authentication import ( "context" + "encoding/json" + "tkestack.io/tke/pkg/util/log" "k8s.io/apiserver/pkg/endpoints/request" "tkestack.io/tke/pkg/apiserver/authentication/authenticator/oidc" @@ -63,6 +65,20 @@ func GetUID(ctx context.Context) (uid string) { return userInfo.GetUID() } +func GetExtraValue(key string, ctx context.Context) []string { + userInfo, ok := request.UserFrom(ctx) + if !ok { + return nil + } + extra := userInfo.GetExtra() + marshal, _ := json.Marshal(extra) + log.Infof("extra '%s'", marshal) + if len(extra) > 0 { + return extra[key] + } + return nil +} + // IsAdministrator check whether administrator func IsAdministrator(ctx context.Context, privilegedUsername string) bool { username, tenantID := UsernameAndTenantID(ctx) diff --git a/pkg/authz/apiserver/apiserver.go b/pkg/authz/apiserver/apiserver.go new file mode 100644 index 000000000..833d724a2 --- /dev/null +++ b/pkg/authz/apiserver/apiserver.go @@ -0,0 +1,145 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package apiserver + +import ( + "k8s.io/apiserver/pkg/registry/generic" + genericapiserver "k8s.io/apiserver/pkg/server" + serverstorage "k8s.io/apiserver/pkg/server/storage" + authzv1 "tkestack.io/tke/api/authz/v1" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + versionedinformers "tkestack.io/tke/api/client/informers/externalversions" + "tkestack.io/tke/pkg/apiserver/storage" + authzrest "tkestack.io/tke/pkg/authz/registry/rest" + "tkestack.io/tke/pkg/util/log" +) + +// ExtraConfig contains the additional configuration of apiserver. +type ExtraConfig struct { + ServerName string + APIResourceConfigSource serverstorage.APIResourceConfigSource + StorageFactory serverstorage.StorageFactory + VersionedInformers versionedinformers.SharedInformerFactory + PlatformClient platformversionedclient.PlatformV1Interface +} + +// Config contains the core configuration instance of apiserver and +// additional configuration. +type Config struct { + GenericConfig *genericapiserver.RecommendedConfig + ExtraConfig ExtraConfig +} + +type completedConfig struct { + GenericConfig genericapiserver.CompletedConfig + ExtraConfig *ExtraConfig +} + +// CompletedConfig embed a private pointer of Config. +type CompletedConfig struct { + // Embed a private pointer that cannot be instantiated outside of this package. + *completedConfig +} + +// APIServer contains state for a tke api server. +type APIServer struct { + GenericAPIServer *genericapiserver.GenericAPIServer +} + +// Complete fills in any fields not set that are required to have valid data. +// It's mutating the receiver. +func (cfg *Config) Complete() CompletedConfig { + c := completedConfig{ + cfg.GenericConfig.Complete(), + &cfg.ExtraConfig, + } + + return CompletedConfig{&c} +} + +// New returns a new instance of APIServer from the given config. +func (c completedConfig) New(delegationTarget genericapiserver.DelegationTarget) (*APIServer, error) { + s, err := c.GenericConfig.New(c.ExtraConfig.ServerName, delegationTarget) + if err != nil { + return nil, err + } + + m := &APIServer{ + GenericAPIServer: s, + } + + // The order here is preserved in discovery. + restStorageProviders := []storage.RESTStorageProvider{ + &authzrest.StorageProvider{ + LoopbackClientConfig: c.GenericConfig.LoopbackClientConfig, + Authorizer: c.GenericConfig.Authorization.Authorizer, + PlatformClient: c.ExtraConfig.PlatformClient, + }, + } + m.InstallAPIs(c.ExtraConfig.APIResourceConfigSource, c.GenericConfig.RESTOptionsGetter, restStorageProviders...) + + log.Info("All of http handlers registered", log.Strings("paths", m.GenericAPIServer.Handler.ListedPaths())) + + return m, nil +} + +// InstallAPIs will install the APIs for the restStorageProviders if they are enabled. +func (m *APIServer) InstallAPIs(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter, restStorageProviders ...storage.RESTStorageProvider) { + var apiGroupsInfo []genericapiserver.APIGroupInfo + + for _, restStorageBuilder := range restStorageProviders { + groupName := restStorageBuilder.GroupName() + if !apiResourceConfigSource.AnyVersionForGroupEnabled(groupName) { + log.Infof("Skipping disabled API group %q.", groupName) + continue + } + apiGroupInfo, enabled := restStorageBuilder.NewRESTStorage(apiResourceConfigSource, restOptionsGetter) + if !enabled { + log.Warnf("Problem initializing API group %q, skipping.", groupName) + continue + } + log.Infof("Enabling API group %q.", groupName) + + if postHookProvider, ok := restStorageBuilder.(genericapiserver.PostStartHookProvider); ok { + name, hook, err := postHookProvider.PostStartHook() + if err != nil { + log.Fatalf("Error building PostStartHook: %v", err) + } + m.GenericAPIServer.AddPostStartHookOrDie(name, hook) + } + + apiGroupsInfo = append(apiGroupsInfo, apiGroupInfo) + } + + for i := range apiGroupsInfo { + if err := m.GenericAPIServer.InstallAPIGroup(&apiGroupsInfo[i]); err != nil { + log.Fatalf("Error in registering group versions: %v", err) + } + } +} + +// DefaultAPIResourceConfigSource returns which groupVersion enabled and its +// resources enabled/disabled. +func DefaultAPIResourceConfigSource() *serverstorage.ResourceConfig { + ret := serverstorage.NewResourceConfig() + ret.EnableVersions( + authzv1.SchemeGroupVersion, + ) + return ret +} diff --git a/pkg/authz/apiserver/install.go b/pkg/authz/apiserver/install.go new file mode 100644 index 000000000..2eb6e5c68 --- /dev/null +++ b/pkg/authz/apiserver/install.go @@ -0,0 +1,41 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package apiserver + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "tkestack.io/tke/api/authz" + + // register application group api scheme for api server. + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + _ "tkestack.io/tke/api/authz/install" +) + +func init() { + metav1.AddToGroupVersion(authz.Scheme, schema.GroupVersion{Version: "v1"}) + + unversioned := schema.GroupVersion{Group: "", Version: "v1"} + authz.Scheme.AddUnversionedTypes(unversioned, + &metav1.Status{}, + &metav1.APIVersions{}, + &metav1.APIGroupList{}, + &metav1.APIGroup{}, + &metav1.APIResourceList{}, + ) +} diff --git a/pkg/authz/constant/constant.go b/pkg/authz/constant/constant.go new file mode 100644 index 000000000..53ebfb95a --- /dev/null +++ b/pkg/authz/constant/constant.go @@ -0,0 +1,11 @@ +package constant + +const ( + RoleNamespace = "authz.tkestack.io/role-namespace" + RoleName = "authz.tkestack.io/role-name" + Username = "authz.tkestack.io/username" + DispatchAllClusters = "authz.tkestack.io/dispatch-all-clusters" + LastDispatchedClusters = "authz.tkestack.io/last-dispatched-clusters" + UpdatedByPolicyController = "authz.tkestack.io/updated-by-policy-controller" + UpdatedByRoleController = "authz.tkestack.io/update-by-role-controller" +) diff --git a/pkg/authz/controller/multiclusterrolebinding/deletion/multiclusterrolebinding_resources_deleter.go b/pkg/authz/controller/multiclusterrolebinding/deletion/multiclusterrolebinding_resources_deleter.go new file mode 100644 index 000000000..26a6a2466 --- /dev/null +++ b/pkg/authz/controller/multiclusterrolebinding/deletion/multiclusterrolebinding_resources_deleter.go @@ -0,0 +1,56 @@ +package deletion + +import ( + "golang.org/x/net/context" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + apiauthzv1 "tkestack.io/tke/api/authz/v1" + clientset "tkestack.io/tke/api/client/clientset/versioned" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + "tkestack.io/tke/pkg/authz/provider" + "tkestack.io/tke/pkg/util/log" +) + +type MultiClusterRoleBindingDeleter interface { + Delete(ctx context.Context, mcrb *apiauthzv1.MultiClusterRoleBinding, provider provider.Provider) error +} + +func New(client clientset.Interface, platformClient platformversionedclient.PlatformV1Interface) MultiClusterRoleBindingDeleter { + return &MultiClusterRoleBindingResourcesDeleter{ + client: client, + platformClient: platformClient, + } +} + +type MultiClusterRoleBindingResourcesDeleter struct { + client clientset.Interface + platformClient platformversionedclient.PlatformV1Interface +} + +func (c *MultiClusterRoleBindingResourcesDeleter) Delete(ctx context.Context, mcrb *apiauthzv1.MultiClusterRoleBinding, provider provider.Provider) error { + // 删除集群中对应的资源 + if err := provider.DeleteMultiClusterRoleBindingResources(ctx, c.platformClient, mcrb); err != nil { + log.Warnf("Unable to finalize MultiClusterRoleBinding '%s/%s', err: %v", mcrb.Namespace, mcrb.Name, err) + return err + } + policyFinalize := apiauthzv1.MultiClusterRoleBinding{} + policyFinalize.ObjectMeta = mcrb.ObjectMeta + policyFinalize.Finalizers = []string{} + if err := c.client.AuthzV1().RESTClient().Put().Resource("multiclusterrolebindings"). + Namespace(mcrb.Namespace). + Name(mcrb.Name). + SubResource("finalize"). + Body(&policyFinalize). + Do(context.Background()). + Into(&policyFinalize); err != nil { + log.Warnf("Unable to finalize multiclusterrolebinding '%s/%s', err: %v", mcrb.Namespace, mcrb.Name, err) + return err + } + if err := c.client.AuthzV1().MultiClusterRoleBindings(mcrb.Namespace).Delete(ctx, mcrb.Name, metav1.DeleteOptions{}); err != nil { + if !errors.IsNotFound(err) { + log.Warnf("Unable to delete multiclusterrolebinding '%s/%s', err: %v", mcrb.Namespace, mcrb.Name, err) + return err + } + } + return nil +} diff --git a/pkg/authz/controller/multiclusterrolebinding/multiclusterrolebinding_controller.go b/pkg/authz/controller/multiclusterrolebinding/multiclusterrolebinding_controller.go new file mode 100644 index 000000000..fbf1f89a6 --- /dev/null +++ b/pkg/authz/controller/multiclusterrolebinding/multiclusterrolebinding_controller.go @@ -0,0 +1,389 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package multiclusterrolebinding + +import ( + "context" + "encoding/json" + "fmt" + rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/tools/cache" + "k8s.io/client-go/util/workqueue" + "reflect" + "time" + apiauthzv1 "tkestack.io/tke/api/authz/v1" + clientset "tkestack.io/tke/api/client/clientset/versioned" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + authzv1informer "tkestack.io/tke/api/client/informers/externalversions/authz/v1" + authzv1 "tkestack.io/tke/api/client/listers/authz/v1" + apiplatformv1 "tkestack.io/tke/api/platform/v1" + "tkestack.io/tke/pkg/authz/constant" + "tkestack.io/tke/pkg/authz/controller/multiclusterrolebinding/deletion" + authzprovider "tkestack.io/tke/pkg/authz/provider" + controllerutil "tkestack.io/tke/pkg/controller" + clusterprovider "tkestack.io/tke/pkg/platform/provider/cluster" + "tkestack.io/tke/pkg/util/log" + "tkestack.io/tke/pkg/util/metrics" +) + +const ( + // appDeletionGracePeriod is the time period to wait before processing a received channel event. + // This allows time for the following to occur: + // * lifecycle admission plugins on HA apiservers to also observe a channel + // deletion and prevent new objects from being created in the terminating channel + // * non-leader etcd servers to observe last-minute object creations in a channel + // so this controller's cleanup can actually clean up all objects + appDeletionGracePeriod = 5 * time.Second +) + +const ( + controllerName = "multiclusterrolebinding-controller" +) + +type Controller struct { + client clientset.Interface + platformClient platformversionedclient.PlatformV1Interface + queue workqueue.RateLimitingInterface + policyLister authzv1.PolicyLister + policySynced cache.InformerSynced + roleLister authzv1.RoleLister + roleSynced cache.InformerSynced + mcrbLister authzv1.MultiClusterRoleBindingLister + mcrbSynced cache.InformerSynced + mcrbDeleter deletion.MultiClusterRoleBindingDeleter + stopCh <-chan struct{} +} + +// NewController creates a new Controller object. +func NewController( + client clientset.Interface, + platformClient platformversionedclient.PlatformV1Interface, + policyInformer authzv1informer.PolicyInformer, + roleInformer authzv1informer.RoleInformer, + mcrbInformer authzv1informer.MultiClusterRoleBindingInformer, + resyncPeriod time.Duration) *Controller { + // create the controller so we can inject the enqueue function + controller := &Controller{ + client: client, + platformClient: platformClient, + queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), controllerName), + mcrbDeleter: deletion.New(client, platformClient), + } + if client != nil && + client.AuthzV1().RESTClient() != nil && + !reflect.ValueOf(client.AuthzV1().RESTClient()).IsNil() && + client.AuthzV1().RESTClient().GetRateLimiter() != nil { + _ = metrics.RegisterMetricAndTrackRateLimiterUsage(controllerName, client.AuthzV1().RESTClient().GetRateLimiter()) + } + + mcrbInformer.Informer().AddEventHandlerWithResyncPeriod( + cache.FilteringResourceEventHandler{ + Handler: cache.ResourceEventHandlerFuncs{ + AddFunc: controller.enqueue, + UpdateFunc: func(oldObj, newObj interface{}) { + old, ok1 := oldObj.(*apiauthzv1.MultiClusterRoleBinding) + cur, ok2 := newObj.(*apiauthzv1.MultiClusterRoleBinding) + if ok1 && ok2 { + if cur.Labels[constant.DispatchAllClusters] == "true" { + controller.enqueue(newObj) + } else if controller.needsUpdate(old, cur) { + controller.enqueue(newObj) + } + } + }, + DeleteFunc: controller.enqueue, + }, + FilterFunc: func(obj interface{}) bool { + mcrb, ok := obj.(*apiauthzv1.MultiClusterRoleBinding) + if !ok { + return false + } + provider, err := authzprovider.GetProvider(mcrb.Annotations) + if err != nil { + return true + } + return provider.OnFilter(context.TODO(), mcrb.Annotations) + }, + }, + resyncPeriod, + ) + + controller.policyLister = policyInformer.Lister() + controller.policySynced = policyInformer.Informer().HasSynced + controller.roleLister = roleInformer.Lister() + controller.roleSynced = roleInformer.Informer().HasSynced + controller.mcrbLister = mcrbInformer.Lister() + controller.mcrbSynced = mcrbInformer.Informer().HasSynced + return controller +} + +func (c *Controller) enqueue(obj interface{}) { + key, err := controllerutil.KeyFunc(obj) + if err != nil { + log.Error("Couldn't get key for object", log.Any("object", obj), log.Err(err)) + return + } + c.queue.AddAfter(key, appDeletionGracePeriod) +} + +func (c *Controller) needsUpdate(old *apiauthzv1.MultiClusterRoleBinding, new *apiauthzv1.MultiClusterRoleBinding) bool { + if old.UID != new.UID { + return true + } + if !reflect.DeepEqual(old.Annotations, new.Annotations) { + return true + } + if !reflect.DeepEqual(old.Spec, new.Spec) { + return true + } + if !reflect.DeepEqual(old.Status, new.Status) { + return true + } + if !reflect.DeepEqual(old.DeletionTimestamp, new.DeletionTimestamp) { + return true + } + return false +} + +// Run will set up the event handlers for types we are interested in, as well +// as syncing informer caches and starting workers. +func (c *Controller) Run(workers int, stopCh <-chan struct{}) { + defer runtime.HandleCrash() + defer c.queue.ShutDown() + + // Start the informer factories to begin populating the informer caches + log.Info("Starting app controller") + defer log.Info("Shutting down app controller") + + if ok := cache.WaitForCacheSync(stopCh, c.mcrbSynced, c.policySynced); !ok { + log.Error("Failed to wait for app caches to sync") + return + } + + c.stopCh = stopCh + for i := 0; i < workers; i++ { + go wait.Until(c.worker, time.Second, stopCh) + } + + <-stopCh +} + +// worker processes the queue of app objects. +// Each app can be in the queue at most once. +// The system ensures that no two workers can process +// the same app at the same time. +func (c *Controller) worker() { + workFunc := func() bool { + key, quit := c.queue.Get() + if quit { + return true + } + defer c.queue.Done(key) + + err := c.syncItem(key.(string)) + if err == nil { + // no error, forget this entry and return + c.queue.Forget(key) + return false + } + + // rather than wait for a full resync, re-add the app to the queue to be processed + c.queue.AddRateLimited(key) + runtime.HandleError(err) + return false + } + + for { + quit := workFunc() + if quit { + return + } + } +} + +func (c *Controller) syncItem(key string) error { + startTime := time.Now() + defer func() { + log.Info("Finished syncing MultiClusterRoleBinding", log.String("MultiClusterRoleBinding", key), log.Duration("processTime", time.Since(startTime))) + }() + ns, name, err := cache.SplitMetaNamespaceKey(key) + if err != nil { + return err + } + + mcrb, err := c.mcrbLister.MultiClusterRoleBindings(ns).Get(name) + if err != nil { + if errors.IsNotFound(err) { + log.Info("MultiClusterRoleBinding has been deleted. Attempting to cleanup resources", + log.String("namespace", ns), + log.String("name", name)) + return nil + } + log.Warn("Unable to retrieve MultiClusterRoleBinding from store", + log.String("namespace", ns), + log.String("name", name), log.Err(err)) + return err + } + mcrb = mcrb.DeepCopy() + provider, err := authzprovider.GetProvider(mcrb.Annotations) + if err != nil { + log.Warn("Unable to retrieve provider", + log.String("namespace", ns), + log.String("name", name), log.Err(err)) + return err + } + ctx := provider.InitContext(mcrb) + if mcrb.Labels[constant.DispatchAllClusters] == "true" { + mcrb.Spec.Clusters, err = provider.GetTenantClusters(ctx, c.platformClient, mcrb.Namespace) + if err != nil { + log.Warnf("failed to get tenant clusters, err '%v'", err) + return err + } + } + + switch mcrb.Status.Phase { + case apiauthzv1.BindingActive: + return c.handleActive(ctx, mcrb, provider) + case apiauthzv1.BindingTerminating: + return c.mcrbDeleter.Delete(ctx, mcrb, provider) + default: + return fmt.Errorf("unknown MultiClusterRoleBinding phase '%s'", mcrb.Status.Phase) + } +} + +func (c *Controller) handleActive(ctx context.Context, mcrb *apiauthzv1.MultiClusterRoleBinding, provider authzprovider.Provider) error { + roleNs, roleName, err := cache.SplitMetaNamespaceKey(mcrb.Spec.RoleName) + if err != nil { + log.Warnf("failed to parse Role namespace/name '%s'", mcrb.Spec.RoleName) + return err + } + + role, err := c.roleLister.Roles(roleNs).Get(roleName) + if err != nil { + if errors.IsNotFound(err) { + log.Warnf("Role '%s/%s' has been deleted", roleNs, roleName) + return c.client.AuthzV1().MultiClusterRoleBindings(mcrb.Namespace).Delete(context.TODO(), mcrb.Name, metav1.DeleteOptions{}) + } + log.Warn("Unable to retrieve Role from store", + log.String("namespace", roleNs), + log.String("name", roleName), log.Err(err)) + return err + } + + // 将Role关联的多个Policy合并 + policies, err := c.combineRolePolicies(role) + if err != nil { + log.Warn("Unable to combine role policies", + log.String("namespace", roleNs), + log.String("name", roleName), log.Err(err)) + return err + } + + // 获取user在各个cluster内的subject + clusterSubjects := map[string]*rbacv1.Subject{} + clusters := []string{} + for _, cls := range mcrb.Spec.Clusters { + cluster, err := clusterprovider.GetV1ClusterByName(ctx, c.platformClient, cls, mcrb.Spec.Username) + if err != nil { + if errors.IsNotFound(err) { + // 如果集群已经被删除,则跳过 + log.Infof("Cluster '%s' is not exist", cls) + continue + } + log.Warnf("GetV1ClusterByName failed, cluster: '%s', user: '%s', err: '%#v'", cls, mcrb.Spec.Username, err) + return err + } + if cluster.Status.Phase != "Waiting" && cluster.Status.Phase != apiplatformv1.ClusterInitializing && cluster.Status.Phase != apiplatformv1.ClusterTerminating { + clusters = append(clusters, cls) + } + subject, err := provider.GetSubject(ctx, mcrb.Spec.Username, cluster) + if err != nil { + log.Warnf("GetSubject failed, cluster: '%s', user: '%s', err: '%#v'", cls, mcrb.Spec.Username, err) + return err + } + clusterSubjects[cls] = subject + } + mcrb.Spec.Clusters = clusters + if len(clusters) != 0 { + // 执行权限分发 + if err = provider.DispatchMultiClusterRoleBinding(ctx, c.platformClient, mcrb, policies, clusterSubjects); err != nil { + log.Warnf("DispatchMultiClusterRoleBinding failed, MultiClusterRoleBinding: '%s', err: '%#v'", mcrb.Name, err) + return err + } + } + + // 删除已经解绑的资源 + var lastDispatchedClusters []string + if lastStr, ok := mcrb.Annotations[constant.LastDispatchedClusters]; ok { + err = json.Unmarshal([]byte(lastStr), &lastDispatchedClusters) + if err != nil { + log.Warnf("Unmarshal lastDispatchedClusters failed', err: '%#v'", err) + return err + } + } + oldSet := sets.NewString(lastDispatchedClusters...) + newSet := sets.NewString(mcrb.Spec.Clusters...) + oldDifference := oldSet.Difference(newSet) + newDifference := newSet.Difference(oldSet) + if len(oldDifference) != 0 { + if err = provider.DeleteUnbindingResources(ctx, c.platformClient, mcrb, oldDifference.List()); err != nil { + log.Warnf("DeleteUnbindingResources '%s/%s' failed', err: '%#v'", mcrb.Namespace, mcrb.Name, err) + return err + } + } + if (len(oldDifference) != 0 || len(newDifference) != 0) || len(mcrb.Spec.Clusters) == 0 { + if len(mcrb.Spec.Clusters) == 0 { + delete(mcrb.Annotations, constant.LastDispatchedClusters) + } else { + clsBytes, _ := json.Marshal(mcrb.Spec.Clusters) + mcrb.Annotations[constant.LastDispatchedClusters] = string(clsBytes) + } + if mcrb.Labels[constant.DispatchAllClusters] == "true" { + mcrb.Spec.Clusters = []string{"*"} + } + if _, err = c.client.AuthzV1().MultiClusterRoleBindings(mcrb.Namespace).Update(context.Background(), mcrb, metav1.UpdateOptions{}); err != nil { + log.Warnf("Update MultiClusterRoleBindings '%s/%s' failed', err: '%#v'", mcrb.Namespace, mcrb.Name, err) + return err + } + } + return nil +} + +func (c *Controller) combineRolePolicies(role *apiauthzv1.Role) ([]rbacv1.PolicyRule, error) { + var policyRules []rbacv1.PolicyRule + for _, policy := range role.Policies { + policyNamespace, policyName, _ := cache.SplitMetaNamespaceKey(policy) + pol, err := c.policyLister.Policies(policyNamespace).Get(policyName) + if err != nil { + if errors.IsNotFound(err) { + log.Warnf("Policy '%s/%s' is not exist", policyNamespace, policyName) + continue + } + log.Warnf("Unable get policy '%s/%s', err: '%v'", policyNamespace, policyName, err) + return nil, err + } + policyRules = append(policyRules, pol.Rules...) + } + return policyRules, nil +} diff --git a/pkg/authz/controller/policy/policy_controller.go b/pkg/authz/controller/policy/policy_controller.go new file mode 100644 index 000000000..e4467ff69 --- /dev/null +++ b/pkg/authz/controller/policy/policy_controller.go @@ -0,0 +1,272 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package policy + +import ( + "context" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/tools/cache" + "k8s.io/client-go/util/workqueue" + "reflect" + "time" + apiauthzv1 "tkestack.io/tke/api/authz/v1" + clientset "tkestack.io/tke/api/client/clientset/versioned" + authzv1informer "tkestack.io/tke/api/client/informers/externalversions/authz/v1" + authzv1 "tkestack.io/tke/api/client/listers/authz/v1" + "tkestack.io/tke/pkg/authz/constant" + "tkestack.io/tke/pkg/authz/controller/policyrolecache" + authzprovider "tkestack.io/tke/pkg/authz/provider" + controllerutil "tkestack.io/tke/pkg/controller" + "tkestack.io/tke/pkg/util/log" + "tkestack.io/tke/pkg/util/metrics" +) + +const ( + deletionGracePeriod = 5 * time.Second +) + +const ( + controllerName = "policy-controller" +) + +type Controller struct { + client clientset.Interface + queue workqueue.RateLimitingInterface + policyLister authzv1.PolicyLister + policySynced cache.InformerSynced + stopCh <-chan struct{} +} + +// NewController creates a new Controller object. +func NewController( + client clientset.Interface, + policyInformer authzv1informer.PolicyInformer, + resyncPeriod time.Duration) *Controller { + // create the controller so we can inject the enqueue function + controller := &Controller{ + client: client, + queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), controllerName), + } + if client != nil && + client.AuthzV1().RESTClient() != nil && + !reflect.ValueOf(client.AuthzV1().RESTClient()).IsNil() && + client.AuthzV1().RESTClient().GetRateLimiter() != nil { + _ = metrics.RegisterMetricAndTrackRateLimiterUsage(controllerName, client.AuthzV1().RESTClient().GetRateLimiter()) + } + + policyInformer.Informer().AddEventHandlerWithResyncPeriod( + cache.FilteringResourceEventHandler{ + Handler: cache.ResourceEventHandlerFuncs{ + AddFunc: func(obj interface{}) { + controller.enqueue(obj) + }, + UpdateFunc: func(oldObj, newObj interface{}) { + old, ok1 := oldObj.(*apiauthzv1.Policy) + cur, ok2 := newObj.(*apiauthzv1.Policy) + if ok1 && ok2 && controller.needsUpdate(old, cur) { + controller.enqueue(cur) + } + }, + DeleteFunc: func(obj interface{}) { + controller.enqueue(obj) + }, + }, + FilterFunc: func(obj interface{}) bool { + policy, ok := obj.(*apiauthzv1.Policy) + if !ok || policy.Scope != apiauthzv1.MultiClusterScope { + return false + } + provider, err := authzprovider.GetProvider(policy.Annotations) + if err != nil { + return true + } + return provider.OnFilter(context.TODO(), policy.Annotations) + }, + }, + resyncPeriod, + ) + controller.policyLister = policyInformer.Lister() + controller.policySynced = policyInformer.Informer().HasSynced + return controller +} + +func (c *Controller) needsUpdate(old *apiauthzv1.Policy, new *apiauthzv1.Policy) bool { + if old.UID != new.UID { + return true + } + if !reflect.DeepEqual(old.Rules, new.Rules) { + return true + } + return false +} + +func (c *Controller) enqueue(obj interface{}) { + key, err := controllerutil.KeyFunc(obj) + if err != nil { + log.Error("Couldn't get key for object", log.Any("object", obj), log.Err(err)) + return + } + c.queue.AddAfter(key, deletionGracePeriod) +} + +// Run will set up the event handlers for types we are interested in, as well +// as syncing informer caches and starting workers. +func (c *Controller) Run(workers int, stopCh <-chan struct{}) { + defer runtime.HandleCrash() + defer c.queue.ShutDown() + + // Start the informer factories to begin populating the informer caches + log.Info("Starting policy controller") + defer log.Info("Shutting down policy controller") + + if ok := cache.WaitForCacheSync(stopCh, c.policySynced); !ok { + log.Error("Failed to wait for policy caches to sync") + return + } + + c.stopCh = stopCh + for i := 0; i < workers; i++ { + go wait.Until(c.worker, time.Second, stopCh) + } + + <-stopCh +} + +// worker processes the queue of app objects. +// Each app can be in the queue at most once. +// The system ensures that no two workers can process +// the same app at the same time. +func (c *Controller) worker() { + workFunc := func() bool { + key, quit := c.queue.Get() + if quit { + return true + } + defer c.queue.Done(key) + + _, err := c.syncItem(key.(string)) + if err == nil { + // no error, forget this entry and return + c.queue.Forget(key) + return false + } + + // rather than wait for a full resync, re-add the app to the queue to be processed + c.queue.AddRateLimited(key) + runtime.HandleError(err) + return false + } + + for { + quit := workFunc() + if quit { + return + } + } +} + +func (c *Controller) syncItem(key string) (policyDeleted bool, retErr error) { + startTime := time.Now() + defer func() { + log.Info("Finished syncing policy", log.String("policy", key), log.Duration("processTime", time.Since(startTime))) + }() + ns, name, err := cache.SplitMetaNamespaceKey(key) + if err != nil { + return policyDeleted, err + } + + defer func() { + if policyDeleted && retErr == nil { + log.Infof("Delete key '%s' from policy role cache", key) + policyrolecache.Cache.DeletePolicy(key) + } + }() + + policy, err := c.policyLister.Policies(ns).Get(name) + if err != nil { + if errors.IsNotFound(err) { + log.Info("Policy has been deleted. Attempting to cleanup resources", + log.String("namespace", ns), + log.String("name", name)) + policyDeleted = true + return policyDeleted, c.updateRelatedRoles(key, policyDeleted) + } + log.Warn("Unable to retrieve policy from store", + log.String("namespace", ns), + log.String("name", name), log.Err(err)) + return policyDeleted, err + } + policy = policy.DeepCopy() + policyDeleted = policy.DeletionTimestamp != nil + return policyDeleted, c.updateRelatedRoles(key, policyDeleted) +} + +func (c *Controller) updateRelatedRoles(policyName string, policyDeleted bool) error { + roles := policyrolecache.Cache.GetRolesByPolicy(policyName) + for roleName := range roles { + roleNs, roleName, err := cache.SplitMetaNamespaceKey(roleName) + if err != nil { + return err + } + role, err := c.client.AuthzV1().Roles(roleNs).Get(context.Background(), roleName, metav1.GetOptions{ResourceVersion: "0"}) + if err != nil { + if errors.IsNotFound(err) { + continue + } else { + log.Warn("Unable to retrieve role from store", + log.String("namespace", roleNs), + log.String("name", roleName), log.Err(err)) + return err + } + } + annotations := role.Annotations + if annotations == nil { + annotations = map[string]string{} + } + annotations[constant.UpdatedByPolicyController] = time.Now().Format("2006-01-02T15:04:05") + role.Annotations = annotations + if policyDeleted { + role.Policies = removeItem(role.Policies, policyName) + } + _, err = c.client.AuthzV1().Roles(roleNs).Update(context.Background(), role, metav1.UpdateOptions{}) + if err != nil { + if errors.IsNotFound(err) { + return nil + } + log.Warn("Unable to update role", + log.String("namespace", roleNs), + log.String("name", roleName), log.Err(err)) + return err + } + } + return nil +} + +func removeItem(raw []string, item string) []string { + var result []string + for _, str := range raw { + if str != item { + result = append(result, str) + } + } + return result +} diff --git a/pkg/authz/controller/policyrolecache/policy_role_cache.go b/pkg/authz/controller/policyrolecache/policy_role_cache.go new file mode 100644 index 000000000..b82902b9d --- /dev/null +++ b/pkg/authz/controller/policyrolecache/policy_role_cache.go @@ -0,0 +1,80 @@ +package policyrolecache + +import ( + "fmt" + "k8s.io/apimachinery/pkg/util/sets" + "reflect" + "sync" + apiauthzv1 "tkestack.io/tke/api/authz/v1" +) + +type PolicyRoleCache interface { + GetRolesByPolicy(policyName string) sets.String + PutByRole(role *apiauthzv1.Role) + DeleteRole(role *apiauthzv1.Role) +} + +type policyRoleCache struct { + rw sync.RWMutex + // key: policyName + // value: roleName set + store map[string]sets.String +} + +var Cache = &policyRoleCache{store: map[string]sets.String{}} + +func (c *policyRoleCache) GetRolesByPolicy(policyName string) sets.String { + c.rw.RLocker().Lock() + defer c.rw.RLocker().Unlock() + return c.store[policyName] +} + +func (c *policyRoleCache) UpdateByRole(old, new *apiauthzv1.Role) { + if reflect.DeepEqual(old.Policies, new.Policies) { + return + } + c.rw.Lock() + defer c.rw.Unlock() + roleName := fmt.Sprintf("%s/%s", old.Namespace, old.Name) + for _, oldPolicy := range old.Policies { + delete(c.store[oldPolicy], roleName) + } + for _, newPolicy := range new.Policies { + set := c.store[newPolicy] + if set == nil { + set = sets.String{} + } + set[roleName] = sets.Empty{} + c.store[newPolicy] = set + } +} + +func (c *policyRoleCache) PutByRole(role *apiauthzv1.Role) { + c.rw.Lock() + defer c.rw.Unlock() + roleName := fmt.Sprintf("%s/%s", role.Namespace, role.Name) + policies := role.Policies + for _, policy := range policies { + set := c.store[policy] + if set == nil { + set = sets.String{} + } + set[roleName] = sets.Empty{} + c.store[policy] = set + } +} + +func (c *policyRoleCache) DeleteRole(role *apiauthzv1.Role) { + c.rw.Lock() + defer c.rw.Unlock() + roleName := fmt.Sprintf("%s/%s", role.Namespace, role.Name) + for _, policy := range role.Policies { + delete(c.store[policy], roleName) + } +} + +func (c *policyRoleCache) DeletePolicy(policyName string) { + c.rw.Lock() + defer c.rw.Unlock() + delete(c.store, policyName) +} diff --git a/pkg/authz/controller/role/role_controller.go b/pkg/authz/controller/role/role_controller.go new file mode 100644 index 000000000..cb4710891 --- /dev/null +++ b/pkg/authz/controller/role/role_controller.go @@ -0,0 +1,325 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package role + +import ( + "context" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/tools/cache" + "k8s.io/client-go/util/workqueue" + "reflect" + "time" + apiauthzv1 "tkestack.io/tke/api/authz/v1" + clientset "tkestack.io/tke/api/client/clientset/versioned" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + authzv1informer "tkestack.io/tke/api/client/informers/externalversions/authz/v1" + authzv1 "tkestack.io/tke/api/client/listers/authz/v1" + "tkestack.io/tke/pkg/authz/constant" + "tkestack.io/tke/pkg/authz/controller/policyrolecache" + authzprovider "tkestack.io/tke/pkg/authz/provider" + controllerutil "tkestack.io/tke/pkg/controller" + "tkestack.io/tke/pkg/util/log" + "tkestack.io/tke/pkg/util/metrics" +) + +const ( + appDeletionGracePeriod = 5 * time.Second + controllerName = "role-controller" +) + +type Controller struct { + client clientset.Interface + platformClient platformversionedclient.PlatformV1Interface + queue workqueue.RateLimitingInterface + roleLister authzv1.RoleLister + roleSynced cache.InformerSynced + mcrbLister authzv1.MultiClusterRoleBindingLister + mcrbSynced cache.InformerSynced + stopCh <-chan struct{} +} + +// NewController creates a new Controller object. +func NewController( + client clientset.Interface, + platformClient platformversionedclient.PlatformV1Interface, + roleInformer authzv1informer.RoleInformer, + mcrbInformer authzv1informer.MultiClusterRoleBindingInformer, + resyncPeriod time.Duration) *Controller { + controller := &Controller{ + client: client, + platformClient: platformClient, + queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), controllerName), + } + if client != nil && + client.AuthzV1().RESTClient() != nil && + !reflect.ValueOf(client.AuthzV1().RESTClient()).IsNil() && + client.AuthzV1().RESTClient().GetRateLimiter() != nil { + _ = metrics.RegisterMetricAndTrackRateLimiterUsage(controllerName, client.AuthzV1().RESTClient().GetRateLimiter()) + } + + roleInformer.Informer().AddEventHandlerWithResyncPeriod( + cache.FilteringResourceEventHandler{ + Handler: cache.ResourceEventHandlerFuncs{ + AddFunc: func(obj interface{}) { + role := obj.(*apiauthzv1.Role) + controller.enqueue(obj) + policyrolecache.Cache.PutByRole(role) + }, + UpdateFunc: func(oldObj, newObj interface{}) { + oldRole := oldObj.(*apiauthzv1.Role) + newRole := newObj.(*apiauthzv1.Role) + controller.enqueue(newObj) + policyrolecache.Cache.UpdateByRole(oldRole, newRole) + }, + DeleteFunc: func(obj interface{}) { + role, _ := obj.(*apiauthzv1.Role) + controller.enqueue(obj) + policyrolecache.Cache.DeleteRole(role) + }, + }, + FilterFunc: func(obj interface{}) bool { + role, ok := obj.(*apiauthzv1.Role) + if !ok || role.Scope != apiauthzv1.MultiClusterScope { + return false + } + provider, err := authzprovider.GetProvider(role.Annotations) + if err != nil { + return true + } + return provider.OnFilter(context.TODO(), role.Annotations) + }, + }, + resyncPeriod, + ) + + controller.roleLister = roleInformer.Lister() + controller.roleSynced = roleInformer.Informer().HasSynced + controller.mcrbLister = mcrbInformer.Lister() + controller.mcrbSynced = mcrbInformer.Informer().HasSynced + return controller +} + +func (c *Controller) enqueue(obj interface{}) { + key, err := controllerutil.KeyFunc(obj) + if err != nil { + log.Error("Couldn't get key for object", log.Any("object", obj), log.Err(err)) + return + } + c.queue.AddAfter(key, appDeletionGracePeriod) +} + +// Run will set up the event handlers for types we are interested in, as well +// as syncing informer caches and starting workers. +func (c *Controller) Run(workers int, stopCh <-chan struct{}) { + defer runtime.HandleCrash() + defer c.queue.ShutDown() + + // Start the informer factories to begin populating the informer caches + log.Info("Starting role controller") + defer log.Info("Shutting down role controller") + + if ok := cache.WaitForCacheSync(stopCh, c.roleSynced, c.mcrbSynced); !ok { + log.Error("Failed to wait for role caches to sync") + return + } + + c.stopCh = stopCh + for i := 0; i < workers; i++ { + go wait.Until(c.worker, time.Second, stopCh) + } + + <-stopCh +} + +// worker processes the queue of app objects. +// Each app can be in the queue at most once. +// The system ensures that no two workers can process +// the same app at the same time. +func (c *Controller) worker() { + workFunc := func() bool { + key, quit := c.queue.Get() + if quit { + return true + } + defer c.queue.Done(key) + + err := c.syncItem(key.(string)) + if err == nil { + // no error, forget this entry and return + c.queue.Forget(key) + return false + } + + // rather than wait for a full resync, re-add the app to the queue to be processed + c.queue.AddRateLimited(key) + runtime.HandleError(err) + return false + } + + for { + quit := workFunc() + if quit { + return + } + } +} + +func (c *Controller) syncItem(key string) error { + startTime := time.Now() + defer func() { + log.Info("Finished syncing role", log.String("role", key), log.Duration("processTime", time.Since(startTime))) + }() + var roleDeleted bool + ns, name, err := cache.SplitMetaNamespaceKey(key) + if err != nil { + return err + } + + role, err := c.roleLister.Roles(ns).Get(name) + if err != nil { + if errors.IsNotFound(err) { + log.Info("Role has been deleted. Attempting to cleanup resources", + log.String("namespace", ns), + log.String("name", name)) + // 删除mcrb资源 + roleDeleted = true + mcrbs, err := c.getMultiClusterRoleBindings(ns, name) + if err != nil { + log.Warn("Unable to retrieve MultiClusterRoleBindings from store", + log.String("roleNs", ns), + log.String("roleName", name), log.Err(err)) + return err + } + err = c.updateOrDeleteMultiClusterRoleBindings(mcrbs, roleDeleted) + if err != nil { + log.Warn("Unable to update MultiClusterRoleBindings", + log.String("roleNs", ns), + log.String("roleName", name), log.Err(err)) + } + return err + } + log.Warn("Unable to retrieve role from store", + log.String("namespace", ns), + log.String("name", name), log.Err(err)) + return err + } + roleDeleted = role.DeletionTimestamp != nil + role = role.DeepCopy() + + mcrbs, err := c.getMultiClusterRoleBindings(ns, name) + if err != nil { + log.Warn("Unable to retrieve MultiClusterRoleBindings from store", + log.String("roleNs", ns), + log.String("roleName", name), log.Err(err)) + return err + } + + err = c.updateOrDeleteMultiClusterRoleBindings(mcrbs, roleDeleted) + if err != nil { + log.Warn("Unable to update MultiClusterRoleBindings", + log.String("roleNs", ns), + log.String("roleName", name), log.Err(err)) + return err + } + + if roleDeleted { + if role.Namespace != "default" { + if err := c.deleteClusterRole(role); err != nil { + log.Warnf("Failed to deleteClusterRole for role '%s/%s'", role.Namespace, role.Name) + return err + } + } + roleFinalize := apiauthzv1.Role{} + roleFinalize.ObjectMeta = role.ObjectMeta + roleFinalize.Finalizers = []string{} + if err := c.client.AuthzV1().RESTClient().Put().Resource("roles"). + Namespace(ns). + Name(name). + SubResource("finalize"). + Body(&roleFinalize). + Do(context.Background()). + Into(&roleFinalize); err != nil { + log.Warnf("Unable to finalize role '%s/%s', err: %v", ns, name, err) + return err + } + if err = c.client.AuthzV1().Roles(ns).Delete(context.Background(), name, metav1.DeleteOptions{}); err != nil { + if !errors.IsNotFound(err) { + log.Warnf("Unable to delete role '%s/%s', err: %v", ns, name, err) + return err + } + } + } + return nil +} + +func (c *Controller) deleteClusterRole(role *apiauthzv1.Role) error { + provider, err := authzprovider.GetProvider(role.Annotations) + if err != nil { + return err + } + return provider.DeleteClusterRole(context.Background(), c.platformClient, role) +} + +func (c *Controller) getMultiClusterRoleBindings(roleNs, roleName string) ([]*apiauthzv1.MultiClusterRoleBinding, error) { + var mcrbs []*apiauthzv1.MultiClusterRoleBinding + var err error + selector := labels.SelectorFromSet(map[string]string{ + constant.RoleNamespace: roleNs, + constant.RoleName: roleName, + }) + if roleNs == "" { + mcrbs, err = c.mcrbLister.List(selector) + } else { + mcrbs, err = c.mcrbLister.MultiClusterRoleBindings(roleNs).List(selector) + } + return mcrbs, err +} + +func (c *Controller) updateOrDeleteMultiClusterRoleBindings(mcrbs []*apiauthzv1.MultiClusterRoleBinding, roleDeleted bool) error { + for _, mcrb := range mcrbs { + if mcrb.DeletionTimestamp != nil { + continue + } + if roleDeleted { + deleteOpt := metav1.DeletePropagationBackground + if err := c.client.AuthzV1().MultiClusterRoleBindings(mcrb.Namespace).Delete(context.Background(), mcrb.Name, metav1.DeleteOptions{PropagationPolicy: &deleteOpt}); err != nil && !errors.IsNotFound(err) { + log.Warnf("Unable to delete MultiClusterRoleBinding '%s/%s', err: '%v'", mcrb.Namespace, mcrb.Name, err) + return err + } + } else { + // 触发更新mcrb + deepCopy := mcrb.DeepCopy() + annotations := deepCopy.Annotations + if annotations == nil { + annotations = map[string]string{} + } + annotations[constant.UpdatedByRoleController] = time.Now().Format("2006-01-02T15:04:05") + deepCopy.Annotations = annotations + if _, err := c.client.AuthzV1().MultiClusterRoleBindings(mcrb.Namespace).Update(context.Background(), deepCopy, metav1.UpdateOptions{}); err != nil && !errors.IsNotFound(err) { + log.Warnf("Unable to delete MultiClusterRoleBinding '%s/%s', err: '%v'", mcrb.Namespace, mcrb.Name, err) + return err + } + } + } + return nil +} diff --git a/pkg/authz/provider/interface.go b/pkg/authz/provider/interface.go new file mode 100644 index 000000000..18e672ab3 --- /dev/null +++ b/pkg/authz/provider/interface.go @@ -0,0 +1,97 @@ +package provider + +import ( + "context" + "fmt" + rbacv1 "k8s.io/api/rbac/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + authzv1 "tkestack.io/tke/api/authz/v1" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + apiplatformv1 "tkestack.io/tke/api/platform/v1" + platformv1 "tkestack.io/tke/pkg/platform/types/v1" +) + +type Provider interface { + Name() string + OnFilter(ctx context.Context, annotations map[string]string) bool + Validate(ctx context.Context, obj runtime.Object, platformClient platformversionedclient.PlatformV1Interface) *field.Error + InitContext(param interface{}) context.Context + GetTenantClusters(ctx context.Context, platformClient platformversionedclient.PlatformV1Interface, tenantID string) ([]string, error) + GetSubject(ctx context.Context, userName string, cluster *platformv1.Cluster) (*rbacv1.Subject, error) + DispatchMultiClusterRoleBinding(ctx context.Context, platformClient platformversionedclient.PlatformV1Interface, mcrb *authzv1.MultiClusterRoleBinding, rules []rbacv1.PolicyRule, clusterSubjects map[string]*rbacv1.Subject) error + DeleteUnbindingResources(ctx context.Context, client platformversionedclient.PlatformV1Interface, mcrb *authzv1.MultiClusterRoleBinding, clusterIDs []string) error + DeleteClusterRole(ctx context.Context, platformClient platformversionedclient.PlatformV1Interface, role *authzv1.Role) error + DeleteMultiClusterRoleBindingResources(ctx context.Context, platformClient platformversionedclient.PlatformV1Interface, mcrb *authzv1.MultiClusterRoleBinding) error +} + +var _ Provider = &DelegateProvider{} + +type DelegateProvider struct { + ProviderName string +} + +func (p *DelegateProvider) OnFilter(todo context.Context, annotations map[string]string) bool { + return true +} + +func (p *DelegateProvider) Validate(ctx context.Context, obj runtime.Object, platformClient platformversionedclient.PlatformV1Interface) *field.Error { + return nil +} + +func (p *DelegateProvider) Name() string { + if p.ProviderName == "" { + return "unknown" + } + return p.ProviderName +} + +func (p *DelegateProvider) InitContext(param interface{}) context.Context { + return context.Background() +} + +func (p *DelegateProvider) GetTenantClusters(ctx context.Context, platformClient platformversionedclient.PlatformV1Interface, tenantID string) ([]string, error) { + var clusterIDs []string + + listOptions := metav1.ListOptions{ + ResourceVersion: "0", + FieldSelector: fmt.Sprintf("spec.tenantID=%s", tenantID), + } + clusters, err := platformClient.Clusters().List(context.TODO(), listOptions) + if err != nil { + return nil, err + } + for _, cls := range clusters.Items { + if cls.Spec.TenantID == tenantID && cls.Name != "global" { + if cls.Status.Phase != apiplatformv1.ClusterInitializing && cls.Status.Phase != apiplatformv1.ClusterTerminating { + clusterIDs = append(clusterIDs, cls.Name) + } + } + } + return clusterIDs, nil +} + +func (p *DelegateProvider) GetSubject(ctx context.Context, platformUser string, cluster *platformv1.Cluster) (*rbacv1.Subject, error) { + _, err := cluster.RESTConfig() + if err != nil { + return nil, err + } + return nil, nil +} + +func (p *DelegateProvider) DispatchMultiClusterRoleBinding(ctx context.Context, platformClient platformversionedclient.PlatformV1Interface, mcrb *authzv1.MultiClusterRoleBinding, rules []rbacv1.PolicyRule, clusterSubjects map[string]*rbacv1.Subject) error { + return nil +} + +func (p *DelegateProvider) DeleteUnbindingResources(ctx context.Context, client platformversionedclient.PlatformV1Interface, mcrb *authzv1.MultiClusterRoleBinding, clusterIDs []string) error { + return nil +} + +func (p *DelegateProvider) DeleteClusterRole(ctx context.Context, platformClient platformversionedclient.PlatformV1Interface, role *authzv1.Role) error { + return nil +} + +func (p *DelegateProvider) DeleteMultiClusterRoleBindingResources(ctx context.Context, platformClient platformversionedclient.PlatformV1Interface, mcrb *authzv1.MultiClusterRoleBinding) error { + return nil +} diff --git a/pkg/authz/provider/provider.go b/pkg/authz/provider/provider.go new file mode 100644 index 000000000..f753fe7cc --- /dev/null +++ b/pkg/authz/provider/provider.go @@ -0,0 +1,80 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2021 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the “License”); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an “AS IS” BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package provider + +import ( + "fmt" + "sort" + "sync" +) + +var ( + providersMu sync.RWMutex + providers = defaultProviders() +) + +const AnnotationProviderNameKey = "authz.tkestack.io/provider-name" + +// Register makes a provider available by the provided name. +// If Register is called twice with the same name or if provider is nil, +// it panics. +func Register(name string, provider Provider) { + providersMu.Lock() + defer providersMu.Unlock() + if provider == nil { + panic("authz: Register provider is nil") + } + if _, dup := providers[name]; dup { + panic("authz: Register called twice for provider " + name) + } + providers[name] = provider +} + +// Providers returns a sorted list of the names of the registered providers. +func Providers() []string { + providersMu.RLock() + defer providersMu.RUnlock() + var list []string + for name := range providers { + list = append(list, name) + } + sort.Strings(list) + return list +} + +// GetProvider will get your provider with the application, +// set an annotation with key, application.tkestack.io/provider-name, and value, the provider will work for your application. +func GetProvider(annotation map[string]string) (Provider, error) { + if annotation == nil { + return &DelegateProvider{}, nil + } + providersMu.RLock() + provider, ok := providers[annotation[AnnotationProviderNameKey]] + providersMu.RUnlock() + if !ok { + return nil, fmt.Errorf("authz: unknown provider %q (forgotten import?)", annotation[AnnotationProviderNameKey]) + } + return provider, nil +} + +func defaultProviders() map[string]Provider { + results := make(map[string]Provider) + results[""] = &DelegateProvider{} + return results +} diff --git a/pkg/authz/registry/configmap/storage/storage.go b/pkg/authz/registry/configmap/storage/storage.go new file mode 100644 index 000000000..f18565b1e --- /dev/null +++ b/pkg/authz/registry/configmap/storage/storage.go @@ -0,0 +1,82 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package storage + +import ( + "context" + + metainternal "k8s.io/apimachinery/pkg/apis/meta/internalversion" + "k8s.io/apimachinery/pkg/runtime" + genericregistry "k8s.io/apiserver/pkg/registry/generic" + "k8s.io/apiserver/pkg/registry/generic/registry" + "k8s.io/apiserver/pkg/registry/rest" + "tkestack.io/tke/api/authz" + apiserverutil "tkestack.io/tke/pkg/apiserver/util" + "tkestack.io/tke/pkg/authz/registry/configmap" + "tkestack.io/tke/pkg/util/log" +) + +// Storage includes storage for configmap and all sub resources. +type Storage struct { + ConfigMap *REST +} + +// NewStorage returns a Storage object that will work against configmap. +func NewStorage(optsGetter genericregistry.RESTOptionsGetter) *Storage { + strategy := configmap.NewStrategy() + store := ®istry.Store{ + NewFunc: func() runtime.Object { return &authz.ConfigMap{} }, + NewListFunc: func() runtime.Object { return &authz.ConfigMapList{} }, + DefaultQualifiedResource: authz.Resource("configmaps"), + + CreateStrategy: strategy, + UpdateStrategy: strategy, + DeleteStrategy: strategy, + } + store.TableConvertor = rest.NewDefaultTableConvertor(store.DefaultQualifiedResource) + options := &genericregistry.StoreOptions{ + RESTOptions: optsGetter, + } + + if err := store.CompleteWithOptions(options); err != nil { + log.Panic("Failed to create configmap etcd rest storage", log.Err(err)) + } + + return &Storage{ + ConfigMap: &REST{store}, + } +} + +// REST implements a RESTStorage for configmap against etcd. +type REST struct { + *registry.Store +} + +var _ rest.ShortNamesProvider = &REST{} + +// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource. +func (r *REST) ShortNames() []string { + return []string{"cm"} +} + +// List selects resources in the storage which match to the selector. 'options' can be nil. +func (r *REST) List(ctx context.Context, options *metainternal.ListOptions) (runtime.Object, error) { + wrappedOptions := apiserverutil.PredicateListOptions(ctx, options) + return r.Store.List(ctx, wrappedOptions) +} diff --git a/pkg/authz/registry/configmap/strategy.go b/pkg/authz/registry/configmap/strategy.go new file mode 100644 index 000000000..6f1348048 --- /dev/null +++ b/pkg/authz/registry/configmap/strategy.go @@ -0,0 +1,109 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package configmap + +import ( + "context" + + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/apiserver/pkg/storage/names" + "tkestack.io/tke/api/authz" + namesutil "tkestack.io/tke/pkg/util/names" +) + +// Strategy implements verification logic for configmap. +type Strategy struct { + runtime.ObjectTyper + names.NameGenerator +} + +var _ rest.RESTCreateStrategy = &Strategy{} +var _ rest.RESTUpdateStrategy = &Strategy{} +var _ rest.RESTDeleteStrategy = &Strategy{} + +// NewStrategy creates a strategy that is the default logic that applies when +// creating and updating namespace set objects. +func NewStrategy() *Strategy { + return &Strategy{authz.Scheme, namesutil.Generator} +} + +// DefaultGarbageCollectionPolicy returns the default garbage collection behavior. +func (Strategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy { + return rest.Unsupported +} + +// NamespaceScoped is false for namespaceSets +func (Strategy) NamespaceScoped() bool { + return false +} + +// Export strips fields that can not be set by the user. +func (Strategy) Export(ctx context.Context, obj runtime.Object, exact bool) error { + return nil +} + +// PrepareForCreate is invoked on create before validation to normalize +// the object. +func (Strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) { + +} + +// PrepareForUpdate is invoked on update before validation to normalize the +// object. +func (Strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) { + +} + +// Validate validates a new configmap. +func (Strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList { + return ValidateConfigMap(obj.(*authz.ConfigMap)) +} + +// AllowCreateOnUpdate is false for persistent events +func (Strategy) AllowCreateOnUpdate() bool { + return false +} + +// AllowUnconditionalUpdate returns true if the object can be updated +// unconditionally (irrespective of the latest resource version), when there is +// no resource version specified in the object. +func (Strategy) AllowUnconditionalUpdate() bool { + return false +} + +// WarningsOnCreate returns warnings for the creation of the given object. +func (Strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { + return nil +} + +// Canonicalize normalizes the object after validation. +func (Strategy) Canonicalize(obj runtime.Object) { +} + +// ValidateUpdate is the default update validation for an end namespace set. +func (Strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList { + return ValidateConfigMapUpdate(obj.(*authz.ConfigMap), old.(*authz.ConfigMap)) +} + +// WarningsOnUpdate returns warnings for the given update. +func (Strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string { + return nil +} diff --git a/pkg/authz/registry/configmap/validation.go b/pkg/authz/registry/configmap/validation.go new file mode 100644 index 000000000..e4502fcaf --- /dev/null +++ b/pkg/authz/registry/configmap/validation.go @@ -0,0 +1,45 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package configmap + +import ( + apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" + "k8s.io/apimachinery/pkg/util/validation/field" + "tkestack.io/tke/api/authz" +) + +// ValidateName is a ValidateNameFunc for names that must be a DNS +// subdomain. +var ValidateName = apimachineryvalidation.ValidateNamespaceName + +// ValidateConfigMap tests if required fields in the cluster are set. +func ValidateConfigMap(configmap *authz.ConfigMap) field.ErrorList { + allErrs := apimachineryvalidation.ValidateObjectMeta(&configmap.ObjectMeta, false, ValidateName, field.NewPath("metadata")) + + return allErrs +} + +// ValidateConfigMapUpdate tests if required fields in the namespace set are +// set during an update. +func ValidateConfigMapUpdate(configmap *authz.ConfigMap, old *authz.ConfigMap) field.ErrorList { + allErrs := apimachineryvalidation.ValidateObjectMetaUpdate(&configmap.ObjectMeta, &old.ObjectMeta, field.NewPath("metadata")) + allErrs = append(allErrs, ValidateConfigMap(configmap)...) + + return allErrs +} diff --git a/pkg/authz/registry/multiclusterrolebinding/storage/storage.go b/pkg/authz/registry/multiclusterrolebinding/storage/storage.go new file mode 100644 index 000000000..68a71f4aa --- /dev/null +++ b/pkg/authz/registry/multiclusterrolebinding/storage/storage.go @@ -0,0 +1,239 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package storage + +import ( + "context" + "fmt" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metainternal "k8s.io/apimachinery/pkg/apis/meta/internalversion" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + genericregistry "k8s.io/apiserver/pkg/registry/generic" + "k8s.io/apiserver/pkg/registry/generic/registry" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/apiserver/pkg/storage" + storageerr "k8s.io/apiserver/pkg/storage/errors" + "k8s.io/apiserver/pkg/util/dryrun" + "tkestack.io/tke/api/authz" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + apiserverutil "tkestack.io/tke/pkg/apiserver/util" + "tkestack.io/tke/pkg/authz/registry/multiclusterrolebinding" + "tkestack.io/tke/pkg/util/log" +) + +// Storage includes storage for configmap and all sub resources. +type Storage struct { + MultiClusterRoleBinding *REST + Status *StatusREST + Finalize *FinalizeREST +} + +// NewStorage returns a Storage object that will work against configmap. +func NewStorage(optsGetter genericregistry.RESTOptionsGetter, roleGetter rest.Getter, platformClient platformversionedclient.PlatformV1Interface) *Storage { + strategy := multiclusterrolebinding.NewStrategy(roleGetter, platformClient) + store := ®istry.Store{ + NewFunc: func() runtime.Object { return &authz.MultiClusterRoleBinding{} }, + NewListFunc: func() runtime.Object { return &authz.MultiClusterRoleBindingList{} }, + DefaultQualifiedResource: authz.Resource("multiclusterrolebindings"), + CreateStrategy: strategy, + UpdateStrategy: strategy, + DeleteStrategy: strategy, + ShouldDeleteDuringUpdate: multiclusterrolebinding.ShouldDeleteDuringUpdate, + } + store.TableConvertor = rest.NewDefaultTableConvertor(store.DefaultQualifiedResource) + options := &genericregistry.StoreOptions{ + RESTOptions: optsGetter, + } + + if err := store.CompleteWithOptions(options); err != nil { + log.Panic("Failed to create configmap etcd rest storage", log.Err(err)) + } + statusStore := *store + statusStore.UpdateStrategy = multiclusterrolebinding.NewStatusStrategy(strategy) + finalizeStore := *store + finalizeStore.UpdateStrategy = multiclusterrolebinding.NewFinalizerStrategy(strategy) + return &Storage{ + MultiClusterRoleBinding: &REST{store}, + Status: &StatusREST{&statusStore}, + Finalize: &FinalizeREST{&finalizeStore}, + } +} + +// REST implements a RESTStorage for configmap against etcd. +type REST struct { + *registry.Store +} + +var _ rest.ShortNamesProvider = &REST{} +var _ rest.Creater = &REST{} +var _ rest.ShortNamesProvider = &REST{} +var _ rest.Lister = &REST{} +var _ rest.Getter = &REST{} +var _ rest.Updater = &REST{} +var _ rest.CollectionDeleter = &REST{} +var _ rest.GracefulDeleter = &REST{} + +// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource. +func (r *REST) ShortNames() []string { + return []string{"mcrb"} +} + +// List selects resources in the storage which match to the selector. 'options' can be nil. +func (r *REST) List(ctx context.Context, options *metainternal.ListOptions) (runtime.Object, error) { + return r.Store.List(ctx, options) +} + +// Delete enforces life-cycle rules for policy termination +func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) { + object, err := r.Get(ctx, name, &metav1.GetOptions{}) + if err != nil { + return nil, false, err + } + cpb := object.(*authz.MultiClusterRoleBinding) + + // Ensure we have a UID precondition + if options == nil { + options = metav1.NewDeleteOptions(0) + } + if options.Preconditions == nil { + options.Preconditions = &metav1.Preconditions{} + } + if options.Preconditions.UID == nil { + options.Preconditions.UID = &cpb.UID + } else if *options.Preconditions.UID != cpb.UID { + err = apierrors.NewConflict( + authz.Resource("multiclusterrolebindings"), + name, + fmt.Errorf("precondition failed: UID in precondition: %v, UID in object meta: %v", *options.Preconditions.UID, cpb.UID), + ) + return nil, false, err + } + + // upon first request to delete, we switch the phase to start cpb termination + if cpb.DeletionTimestamp.IsZero() { + key, err := r.Store.KeyFunc(ctx, name) + if err != nil { + return nil, false, err + } + + preconditions := storage.Preconditions{UID: options.Preconditions.UID} + + out := r.Store.NewFunc() + err = r.Store.Storage.GuaranteedUpdate( + ctx, key, out, false, &preconditions, + storage.SimpleUpdate(func(existing runtime.Object) (runtime.Object, error) { + existingMultiClusterRoleBinding, ok := existing.(*authz.MultiClusterRoleBinding) + if !ok { + // wrong type + return nil, fmt.Errorf("expected *auth.MultiClusterRoleBinding, got %v", existing) + } + if err := deleteValidation(ctx, existingMultiClusterRoleBinding); err != nil { + return nil, err + } + // Set the deletion timestamp if needed + if existingMultiClusterRoleBinding.DeletionTimestamp.IsZero() { + now := metav1.Now() + existingMultiClusterRoleBinding.DeletionTimestamp = &now + } + // Set the cpb phase to terminating, if needed + if existingMultiClusterRoleBinding.Status.Phase != authz.BindingTerminating { + existingMultiClusterRoleBinding.Status.Phase = authz.BindingTerminating + } + + // the current finalizers which are on namespace + currentFinalizers := map[string]bool{} + for _, f := range existingMultiClusterRoleBinding.Finalizers { + currentFinalizers[f] = true + } + // the finalizers we should ensure on rule + shouldHaveFinalizers := map[string]bool{ + metav1.FinalizerOrphanDependents: apiserverutil.ShouldHaveOrphanFinalizer(options, currentFinalizers[metav1.FinalizerOrphanDependents]), + metav1.FinalizerDeleteDependents: apiserverutil.ShouldHaveDeleteDependentsFinalizer(options, currentFinalizers[metav1.FinalizerDeleteDependents]), + } + // determine whether there are changes + changeNeeded := false + for finalizer, shouldHave := range shouldHaveFinalizers { + changeNeeded = currentFinalizers[finalizer] != shouldHave || changeNeeded + if shouldHave { + currentFinalizers[finalizer] = true + } else { + delete(currentFinalizers, finalizer) + } + } + // make the changes if needed + if changeNeeded { + var newFinalizers []string + for f := range currentFinalizers { + newFinalizers = append(newFinalizers, f) + } + existingMultiClusterRoleBinding.Finalizers = newFinalizers + } + return existingMultiClusterRoleBinding, nil + }), + dryrun.IsDryRun(options.DryRun), + nil, + ) + + if err != nil { + err = storageerr.InterpretGetError(err, authz.Resource("multiclusterrolebindings"), name) + err = storageerr.InterpretUpdateError(err, authz.Resource("multiclusterrolebindings"), name) + if _, ok := err.(*apierrors.StatusError); !ok { + err = apierrors.NewInternalError(err) + } + return nil, false, err + } + + return out, false, nil + } + + // prior to final deletion, we must ensure that finalizers is empty + if len(cpb.Finalizers) != 0 { + err = apierrors.NewConflict(authz.Resource("multiclusterrolebindings"), cpb.Name, fmt.Errorf("the system is ensuring all content is removed from this cpb. Upon completion, this cpb will automatically be purged by the system")) + return nil, false, err + } + return r.Store.Delete(ctx, name, deleteValidation, options) +} + +// StatusREST implements the GenericREST endpoint for changing the status of a policy request. +type StatusREST struct { + *registry.Store +} + +// StatusREST implements Patcher. +var _ = rest.Patcher(&StatusREST{}) + +// New returns an empty object that can be used with Create and Update after request data has been put into it. +func (r *StatusREST) New() runtime.Object { + return r.Store.New() +} + +// FinalizeREST implements Patcher. +var _ = rest.Patcher(&FinalizeREST{}) + +// FinalizeREST implements the REST endpoint for finalizing a policy. +type FinalizeREST struct { + *registry.Store +} + +// New returns an empty object that can be used with Create and Update after +// request data has been put into it. +func (r *FinalizeREST) New() runtime.Object { + return r.Store.New() +} diff --git a/pkg/authz/registry/multiclusterrolebinding/strategy.go b/pkg/authz/registry/multiclusterrolebinding/strategy.go new file mode 100644 index 000000000..336956f07 --- /dev/null +++ b/pkg/authz/registry/multiclusterrolebinding/strategy.go @@ -0,0 +1,261 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package multiclusterrolebinding + +import ( + "context" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/registry/generic/registry" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/apiserver/pkg/storage/names" + "k8s.io/client-go/tools/cache" + "strings" + "tkestack.io/tke/api/authz" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + "tkestack.io/tke/pkg/apiserver/authentication" + "tkestack.io/tke/pkg/authz/constant" + authzprovider "tkestack.io/tke/pkg/authz/provider" + "tkestack.io/tke/pkg/util/log" + namesutil "tkestack.io/tke/pkg/util/names" +) + +// Strategy implements verification logic for configmap. +type Strategy struct { + runtime.ObjectTyper + names.NameGenerator + roleGetter rest.Getter + platformClient platformversionedclient.PlatformV1Interface +} + +var _ rest.RESTCreateStrategy = &Strategy{} +var _ rest.RESTUpdateStrategy = &Strategy{} +var _ rest.RESTDeleteStrategy = &Strategy{} + +const NamePrefix = "mcrb-" + +// NewStrategy creates a strategy that is the default logic that applies when +// creating and updating namespace set objects. +func NewStrategy(roleGetter rest.Getter, platformClient platformversionedclient.PlatformV1Interface) *Strategy { + return &Strategy{authz.Scheme, namesutil.Generator, roleGetter, platformClient} +} + +// DefaultGarbageCollectionPolicy returns the default garbage collection behavior. +func (Strategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy { + return rest.Unsupported +} + +// NamespaceScoped is false for namespaceSets +func (Strategy) NamespaceScoped() bool { + return true +} + +// Export strips fields that can not be set by the user. +func (Strategy) Export(ctx context.Context, obj runtime.Object, exact bool) error { + return nil +} + +// PrepareForCreate is invoked on create before validation to normalize +// the object. +func (Strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) { + tenantID := request.NamespaceValue(ctx) + if tenantID == "" { + tenantID = "default" + } + mcrb, _ := obj.(*authz.MultiClusterRoleBinding) + mcrb.Spec.TenantID = tenantID + + if mcrb.Name == "" && mcrb.GenerateName == "" { + mcrb.Name = "mcrb-" + mcrb.Spec.Username + "-" + strings.ReplaceAll(mcrb.Spec.RoleName, "/", "-") + mcrb.GenerateName = NamePrefix + } + roleNs, roleName, err := cache.SplitMetaNamespaceKey(mcrb.Spec.RoleName) + if err != nil { + return + } + labels := mcrb.Labels + if labels == nil { + labels = map[string]string{} + } + labels[constant.RoleNamespace] = roleNs + labels[constant.RoleName] = roleName + labels[constant.Username] = mcrb.Spec.Username + if dispatchAllClusters(mcrb.Spec.Clusters) { + labels[constant.DispatchAllClusters] = "true" + } + mcrb.Labels = labels + + annotation := mcrb.Annotations + if annotation == nil { + annotation = map[string]string{} + } + region := authentication.GetExtraValue("region", ctx) + log.Debugf("region '%v'", region) + if len(region) != 0 { + annotation[authz.GroupName+"/region"] = region[0] + } + mcrb.Annotations = annotation + mcrb.Status.Phase = authz.BindingActive + mcrb.ObjectMeta.Finalizers = []string{string(authz.MultiClusterRoleBindingFinalize)} +} + +func dispatchAllClusters(clusterIDs []string) bool { + if len(clusterIDs) == 1 && clusterIDs[0] == "*" { + return true + } + return false +} + +// PrepareForUpdate is invoked on update before validation to normalize the +// object. +func (Strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) { + oldMcrb := old.(*authz.MultiClusterRoleBinding) + mcrb := obj.(*authz.MultiClusterRoleBinding) + if dispatchAllClusters(mcrb.Spec.Clusters) { + mcrb.Labels[constant.DispatchAllClusters] = "true" + } else { + delete(mcrb.Labels, constant.DispatchAllClusters) + } + if mcrb.Spec.TenantID != oldMcrb.Spec.TenantID { + log.Warnf("Unauthorized update mcrb tenantID '%s'", oldMcrb.Spec.TenantID) + mcrb.Spec.TenantID = oldMcrb.Spec.TenantID + } + if mcrb.Spec.RoleName != oldMcrb.Spec.RoleName { + log.Warnf("Unauthorized update mcrb roleName '%s'", oldMcrb.Spec.RoleName) + mcrb.Spec.RoleName = oldMcrb.Spec.RoleName + } +} + +// Validate validates a new configmap. +func (s Strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList { + mcrb := obj.(*authz.MultiClusterRoleBinding) + provider, err := authzprovider.GetProvider(mcrb.Annotations) + if err == nil { + if fieldErr := provider.Validate(context.TODO(), mcrb, s.platformClient); fieldErr != nil { + return field.ErrorList{fieldErr} + } + } + if len(mcrb.Spec.Clusters) == 0 { + return field.ErrorList{field.Required(field.NewPath("spec", "clusters"), "empty clusters")} + } + return ValidateMultiClusterRoleBinding(mcrb, s.roleGetter, s.platformClient) +} + +// AllowCreateOnUpdate is false for persistent events +func (Strategy) AllowCreateOnUpdate() bool { + return false +} + +// AllowUnconditionalUpdate returns true if the object can be updated +// unconditionally (irrespective of the latest resource version), when there is +// no resource version specified in the object. +func (Strategy) AllowUnconditionalUpdate() bool { + return false +} + +// WarningsOnCreate returns warnings for the creation of the given object. +func (Strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { + return nil +} + +// Canonicalize normalizes the object after validation. +func (Strategy) Canonicalize(obj runtime.Object) { +} + +// ValidateUpdate is the default update validation for an end namespace set. +func (s Strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList { + return ValidateMultiClusterRoleBindingUpdate(obj.(*authz.MultiClusterRoleBinding), old.(*authz.MultiClusterRoleBinding), s.roleGetter, s.platformClient) +} + +// WarningsOnUpdate returns warnings for the given update. +func (Strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string { + return nil +} + +func ShouldDeleteDuringUpdate(ctx context.Context, key string, obj, existing runtime.Object) bool { + pol, ok := obj.(*authz.MultiClusterRoleBinding) + if !ok { + log.Errorf("unexpected object, key:%s", key) + return false + } + return len(pol.Finalizers) == 0 && registry.ShouldDeleteDuringUpdate(ctx, key, obj, existing) +} + +// StatusStrategy implements verification logic for status of roletemplate request. +type StatusStrategy struct { + *Strategy +} + +var _ rest.RESTUpdateStrategy = &StatusStrategy{} + +// NewStatusStrategy create the StatusStrategy object by given strategy. +func NewStatusStrategy(strategy *Strategy) *StatusStrategy { + return &StatusStrategy{strategy} +} + +// PrepareForUpdate is invoked on update before validation to normalize +// the object. For example: remove fields that are not to be persisted, +// sort order-insensitive list fields, etc. This should not remove fields +// whose presence would be considered a validation error. +func (StatusStrategy) PrepareForUpdate(_ context.Context, obj, old runtime.Object) { + newMultiClusterRoleBinding := obj.(*authz.MultiClusterRoleBinding) + oldMultiClusterRoleBinding := old.(*authz.MultiClusterRoleBinding) + status := newMultiClusterRoleBinding.Status + newMultiClusterRoleBinding = oldMultiClusterRoleBinding + newMultiClusterRoleBinding.Status = status +} + +// ValidateUpdate is invoked after default fields in the object have been +// filled in before the object is persisted. This method should not mutate +// the object. +func (s *StatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList { + return nil +} + +// FinalizeStrategy implements finalizer logic for Machine. +type FinalizeStrategy struct { + *Strategy +} + +var _ rest.RESTUpdateStrategy = &FinalizeStrategy{} + +// NewFinalizerStrategy create the FinalizeStrategy object by given strategy. +func NewFinalizerStrategy(strategy *Strategy) *FinalizeStrategy { + return &FinalizeStrategy{strategy} +} + +// PrepareForUpdate is invoked on update before validation to normalize +// the object. For example: remove fields that are not to be persisted, +// sort order-insensitive list fields, etc. This should not remove fields +// whose presence would be considered a validation error. +func (FinalizeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) { + newBinding := obj.(*authz.MultiClusterRoleBinding) + oldBinding := old.(*authz.MultiClusterRoleBinding) + finalizers := newBinding.Finalizers + newBinding = oldBinding + newBinding.Finalizers = finalizers +} + +// ValidateUpdate is invoked after default fields in the object have been +// filled in before the object is persisted. This method should not mutate +// the object. +func (s *FinalizeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList { + return nil +} diff --git a/pkg/authz/registry/multiclusterrolebinding/validation.go b/pkg/authz/registry/multiclusterrolebinding/validation.go new file mode 100644 index 000000000..75eb1ed9a --- /dev/null +++ b/pkg/authz/registry/multiclusterrolebinding/validation.go @@ -0,0 +1,86 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package multiclusterrolebinding + +import ( + "context" + "fmt" + apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/client-go/tools/cache" + "tkestack.io/tke/api/authz" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" +) + +var ValidateMultiClusterRoleBindingName = apimachineryvalidation.NameIsDNSLabel + +// ValidateMultiClusterRoleBinding tests if required fields in the cluster are set. +func ValidateMultiClusterRoleBinding(mcrb *authz.MultiClusterRoleBinding, roleGetter rest.Getter, platformClient platformversionedclient.PlatformV1Interface) field.ErrorList { + allErrs := apimachineryvalidation.ValidateObjectMeta(&mcrb.ObjectMeta, true, ValidateMultiClusterRoleBindingName, field.NewPath("metadata")) + if len(mcrb.Spec.TenantID) == 0 { + allErrs = append(allErrs, field.Required(field.NewPath("spec", "tenantID"), "empty tenantID")) + return allErrs + } + if len(mcrb.Spec.Username) == 0 { + allErrs = append(allErrs, field.Required(field.NewPath("spec", "username"), "empty username")) + return allErrs + } + clusters := mcrb.Spec.Clusters + for _, cls := range clusters { + if cls == "*" { + if len(clusters) != 1 { + allErrs = append(allErrs, field.Required(field.NewPath("spec", "clusters"), "cluster '*' is invalidate")) + return allErrs + } + } else { + if _, err := platformClient.Clusters().Get(context.TODO(), cls, metav1.GetOptions{ResourceVersion: "0"}); err != nil { + allErrs = append(allErrs, field.Required(field.NewPath("spec", "clusters"), fmt.Sprintf("get cluster '%s' failed, err '%v'", cls, err))) + return allErrs + } + } + } + roleNs, roleName, err := cache.SplitMetaNamespaceKey(mcrb.Spec.RoleName) + if err != nil { + allErrs = append(allErrs, field.Required(field.NewPath("spec", "roleName"), "roleName invalidate")) + return allErrs + } + if roleNs != "" && roleNs != "default" && roleNs != mcrb.Namespace { + allErrs = append(allErrs, field.Required(field.NewPath("spec", "roleName"), "roleName invalidate")) + return allErrs + } + if roleNs == "" { + roleNs = "default" + } + ctx := request.WithNamespace(request.NewContext(), roleNs) + if _, err := roleGetter.Get(ctx, roleName, &metav1.GetOptions{}); err != nil { + allErrs = append(allErrs, field.Required(field.NewPath("spec", "roleName"), fmt.Sprintf("roleName '%s' not exist", mcrb.Spec.RoleName))) + } + return allErrs +} + +// ValidateMultiClusterRoleBindingUpdate tests if required fields in the namespace set are +// set during an update. +func ValidateMultiClusterRoleBindingUpdate(clusterroletemplatebinding *authz.MultiClusterRoleBinding, old *authz.MultiClusterRoleBinding, roleGetter rest.Getter, platformClient platformversionedclient.PlatformV1Interface) field.ErrorList { + allErrs := apimachineryvalidation.ValidateObjectMetaUpdate(&clusterroletemplatebinding.ObjectMeta, &old.ObjectMeta, field.NewPath("metadata")) + allErrs = append(allErrs, ValidateMultiClusterRoleBinding(clusterroletemplatebinding, roleGetter, platformClient)...) + return allErrs +} diff --git a/pkg/authz/registry/policy/storage/storage.go b/pkg/authz/registry/policy/storage/storage.go new file mode 100644 index 000000000..f4a9eb7c2 --- /dev/null +++ b/pkg/authz/registry/policy/storage/storage.go @@ -0,0 +1,100 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package storage + +import ( + "context" + "fmt" + metainternal "k8s.io/apimachinery/pkg/apis/meta/internalversion" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + genericregistry "k8s.io/apiserver/pkg/registry/generic" + "k8s.io/apiserver/pkg/registry/generic/registry" + "k8s.io/apiserver/pkg/registry/rest" + "tkestack.io/tke/api/authz" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + "tkestack.io/tke/pkg/apiserver/authentication" + "tkestack.io/tke/pkg/authz/registry/policy" + "tkestack.io/tke/pkg/util/log" +) + +// Storage includes storage for configmap and all sub resources. +type Storage struct { + Policy *REST +} + +// NewStorage returns a Storage object that will work against configmap. +func NewStorage(optsGetter genericregistry.RESTOptionsGetter, platformClient platformversionedclient.PlatformV1Interface) *Storage { + strategy := policy.NewStrategy(platformClient) + store := ®istry.Store{ + NewFunc: func() runtime.Object { return &authz.Policy{} }, + NewListFunc: func() runtime.Object { return &authz.PolicyList{} }, + DefaultQualifiedResource: authz.Resource("policies"), + ShouldDeleteDuringUpdate: policy.ShouldDeleteDuringUpdate, + CreateStrategy: strategy, + UpdateStrategy: strategy, + DeleteStrategy: strategy, + } + store.TableConvertor = rest.NewDefaultTableConvertor(store.DefaultQualifiedResource) + options := &genericregistry.StoreOptions{ + RESTOptions: optsGetter, + } + + if err := store.CompleteWithOptions(options); err != nil { + log.Panic("Failed to create configmap etcd rest storage", log.Err(err)) + } + return &Storage{ + Policy: &REST{store}, + } +} + +// REST implements a RESTStorage for configmap against etcd. +type REST struct { + *registry.Store +} + +var _ rest.ShortNamesProvider = &REST{} +var _ rest.Getter = &REST{} + +// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource. +func (r *REST) ShortNames() []string { + return []string{"pol"} +} + +// List selects resources in the storage which match to the selector. 'options' can be nil. +func (r *REST) List(ctx context.Context, options *metainternal.ListOptions) (runtime.Object, error) { + return r.Store.List(ctx, options) +} + +// Delete enforces life-cycle rules for policy termination +func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) { + _, tenantID := authentication.UsernameAndTenantID(ctx) + if tenantID == "" { + tenantID = "default" + } + object, err := r.Get(ctx, name, &metav1.GetOptions{}) + if err != nil { + return nil, false, err + } + pol := object.(*authz.Policy) + if tenantID != "default" && pol.Namespace != tenantID { + return nil, false, fmt.Errorf("tenant '%s' can't delete policy '%s/%s'", tenantID, pol.Namespace, pol.Name) + } + return r.Store.Delete(ctx, name, deleteValidation, options) +} diff --git a/pkg/authz/registry/policy/strategy.go b/pkg/authz/registry/policy/strategy.go new file mode 100644 index 000000000..8f87270dd --- /dev/null +++ b/pkg/authz/registry/policy/strategy.go @@ -0,0 +1,189 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package policy + +import ( + "context" + "encoding/json" + rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/registry/generic/registry" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/apiserver/pkg/storage/names" + "k8s.io/kubectl/pkg/util/rbac" + "tkestack.io/tke/api/authz" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + "tkestack.io/tke/pkg/apiserver/authentication" + authzprovider "tkestack.io/tke/pkg/authz/provider" + "tkestack.io/tke/pkg/util/log" + namesutil "tkestack.io/tke/pkg/util/names" +) + +// Strategy implements verification logic for configmap. +type Strategy struct { + runtime.ObjectTyper + names.NameGenerator + platformClient platformversionedclient.PlatformV1Interface +} + +const ( + NamePrefix = "pol-" +) + +var _ rest.RESTCreateStrategy = &Strategy{} +var _ rest.RESTUpdateStrategy = &Strategy{} +var _ rest.RESTDeleteStrategy = &Strategy{} + +// NewStrategy creates a strategy that is the default logic that applies when +// creating and updating namespace set objects. +func NewStrategy(platformClient platformversionedclient.PlatformV1Interface) *Strategy { + return &Strategy{authz.Scheme, namesutil.Generator, platformClient} +} + +func ShouldDeleteDuringUpdate(ctx context.Context, key string, obj, existing runtime.Object) bool { + pol, ok := obj.(*authz.Policy) + if !ok { + log.Errorf("unexpected object, key:%s", key) + return false + } + return len(pol.Finalizers) == 0 && registry.ShouldDeleteDuringUpdate(ctx, key, obj, existing) +} + +// DefaultGarbageCollectionPolicy returns the default garbage collection behavior. +func (Strategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy { + return rest.Unsupported +} + +// NamespaceScoped is false for namespaceSets +func (Strategy) NamespaceScoped() bool { + return true +} + +// Export strips fields that can not be set by the user. +func (Strategy) Export(ctx context.Context, obj runtime.Object, exact bool) error { + return nil +} + +// PrepareForCreate is invoked on create before validation to normalize +// the object. +func (Strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) { + username, _ := authentication.UsernameAndTenantID(ctx) + tenantID := request.NamespaceValue(ctx) + if tenantID == "" { + tenantID = "default" + } + + policy := obj.(*authz.Policy) + policy.TenantID = tenantID + if policy.Username == "" { + policy.Username = username + } + if policy.Name == "" && policy.GenerateName == "" { + policy.GenerateName = NamePrefix + } + policy.Rules = compactRules(policy.Rules) + region := authentication.GetExtraValue("region", ctx) + log.Debugf("region '%v'", region) + if len(region) != 0 { + annotations := policy.Annotations + if len(annotations) == 0 { + annotations = map[string]string{} + } + annotations[authz.GroupName+"/region"] = region[0] + policy.Annotations = annotations + } +} + +func compactRules(rules []rbacv1.PolicyRule) []rbacv1.PolicyRule { + if len(rules) != 0 { + for _, rule := range rules { + apiGroups := rule.APIGroups + for j := range rule.APIGroups { + if apiGroups[j] == "" || apiGroups[j] == "\"\"" || apiGroups[j] == "'\"\"'" { + apiGroups[j] = "" + } + } + } + compactedRules, err := rbac.CompactRules(rules) + if err != nil { + marshal, _ := json.Marshal(rules) + log.Errorf("unexpected object, rules:%s", marshal) + } else { + return compactedRules + } + } + return rules +} + +// PrepareForUpdate is invoked on update before validation to normalize the +// object. +func (Strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) { + oldPolicy := old.(*authz.Policy) + policy, _ := obj.(*authz.Policy) + if policy.TenantID != oldPolicy.TenantID { + log.Warnf("Unauthorized update policy tenantID '%s'", oldPolicy.TenantID) + policy.TenantID = oldPolicy.TenantID + } + policy.Rules = compactRules(policy.Rules) +} + +// Validate validates a new configmap. +func (s Strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList { + policy := obj.(*authz.Policy) + provider, err := authzprovider.GetProvider(policy.Annotations) + if err == nil { + if fieldErr := provider.Validate(context.TODO(), policy, s.platformClient); fieldErr != nil { + return field.ErrorList{fieldErr} + } + } + return ValidatePolicy(policy, s.platformClient) +} + +// AllowCreateOnUpdate is false for persistent events +func (Strategy) AllowCreateOnUpdate() bool { + return false +} + +// AllowUnconditionalUpdate returns true if the object can be updated +// unconditionally (irrespective of the latest resource version), when there is +// no resource version specified in the object. +func (Strategy) AllowUnconditionalUpdate() bool { + return false +} + +// WarningsOnCreate returns warnings for the creation of the given object. +func (Strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { + return nil +} + +// Canonicalize normalizes the object after validation. +func (Strategy) Canonicalize(obj runtime.Object) { +} + +// ValidateUpdate is the default update validation for an end namespace set. +func (s Strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList { + return ValidatePolicyUpdate(ctx, obj.(*authz.Policy), old.(*authz.Policy), s.platformClient) +} + +// WarningsOnUpdate returns warnings for the given update. +func (Strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string { + return nil +} diff --git a/pkg/authz/registry/policy/validation.go b/pkg/authz/registry/policy/validation.go new file mode 100644 index 000000000..77808f5f2 --- /dev/null +++ b/pkg/authz/registry/policy/validation.go @@ -0,0 +1,70 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package policy + +import ( + "context" + "fmt" + apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" + "k8s.io/apimachinery/pkg/util/validation/field" + "tkestack.io/tke/api/authz" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + "tkestack.io/tke/pkg/apiserver/authentication" +) + +var ValidatePolicyName = apimachineryvalidation.NameIsDNSLabel + +// ValidatePolicy tests if required fields in the cluster are set. +func ValidatePolicy(policy *authz.Policy, platformClient platformversionedclient.PlatformV1Interface) field.ErrorList { + allErrs := apimachineryvalidation.ValidateObjectMeta(&policy.ObjectMeta, true, ValidatePolicyName, field.NewPath("metadata")) + for i, rule := range policy.Rules { + fldPath := field.NewPath("rules").Index(i) + if len(rule.Verbs) == 0 { + allErrs = append(allErrs, field.Required(fldPath.Child("verbs"), "verbs must contain at least one value")) + } + if len(rule.NonResourceURLs) > 0 { + if len(rule.APIGroups) > 0 || len(rule.Resources) > 0 || len(rule.ResourceNames) > 0 { + allErrs = append(allErrs, field.Invalid(fldPath.Child("nonResourceURLs"), rule.NonResourceURLs, "rules cannot apply to both regular resources and non-resource URLs")) + } + return allErrs + } + if len(rule.APIGroups) == 0 { + allErrs = append(allErrs, field.Required(fldPath.Child("apiGroups"), "resource rules must supply at least one api group")) + } + if len(rule.Resources) == 0 { + allErrs = append(allErrs, field.Required(fldPath.Child("resources"), "resource rules must supply at least one resource")) + } + } + return allErrs +} + +// ValidatePolicyUpdate tests if required fields in the namespace set are +// set during an update. +func ValidatePolicyUpdate(ctx context.Context, policy *authz.Policy, old *authz.Policy, platformClient platformversionedclient.PlatformV1Interface) field.ErrorList { + _, tenantID := authentication.UsernameAndTenantID(ctx) + if tenantID == "" { + tenantID = "default" + } + if tenantID != "default" && tenantID != policy.Namespace { + return append(field.ErrorList{}, field.Required(field.NewPath("metadata", "namespace"), fmt.Sprintf("tenant '%s' can't update policy '%s/%s'", tenantID, policy.Namespace, policy.Name))) + } + allErrs := apimachineryvalidation.ValidateObjectMetaUpdate(&policy.ObjectMeta, &old.ObjectMeta, field.NewPath("metadata")) + allErrs = append(allErrs, ValidatePolicy(policy, platformClient)...) + return allErrs +} diff --git a/pkg/authz/registry/rest/rest.go b/pkg/authz/registry/rest/rest.go new file mode 100644 index 000000000..b5dbd15de --- /dev/null +++ b/pkg/authz/registry/rest/rest.go @@ -0,0 +1,81 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package rest + +import ( + "k8s.io/apiserver/pkg/authorization/authorizer" + "k8s.io/apiserver/pkg/registry/generic" + "k8s.io/apiserver/pkg/registry/rest" + genericserver "k8s.io/apiserver/pkg/server" + serverstorage "k8s.io/apiserver/pkg/server/storage" + restclient "k8s.io/client-go/rest" + "tkestack.io/tke/api/authz" + authzv1 "tkestack.io/tke/api/authz/v1" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + "tkestack.io/tke/pkg/apiserver/storage" + configmapstorage "tkestack.io/tke/pkg/authz/registry/configmap/storage" + mcrbstorage "tkestack.io/tke/pkg/authz/registry/multiclusterrolebinding/storage" + policystorage "tkestack.io/tke/pkg/authz/registry/policy/storage" + rolestorage "tkestack.io/tke/pkg/authz/registry/role/storage" +) + +// StorageProvider is a REST type for core resources storage that implement +// RestStorageProvider interface +type StorageProvider struct { + LoopbackClientConfig *restclient.Config + Authorizer authorizer.Authorizer + PlatformClient platformversionedclient.PlatformV1Interface +} + +// Implement RESTStorageProvider +var _ storage.RESTStorageProvider = &StorageProvider{} + +// NewRESTStorage is a factory constructor to creates and returns the APIGroupInfo +func (s *StorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericserver.APIGroupInfo, bool) { + apiGroupInfo := genericserver.NewDefaultAPIGroupInfo(authz.GroupName, authz.Scheme, authz.ParameterCodec, authz.Codecs) + if apiResourceConfigSource.VersionEnabled(authzv1.SchemeGroupVersion) { + apiGroupInfo.VersionedResourcesStorageMap[authzv1.SchemeGroupVersion.Version] = + s.v1Storage(apiResourceConfigSource, restOptionsGetter, s.PlatformClient) + } + return apiGroupInfo, true +} + +// GroupName return the api group name +func (*StorageProvider) GroupName() string { + return authz.GroupName +} + +func (s *StorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter, platformClient platformversionedclient.PlatformV1Interface) map[string]rest.Storage { + storageMap := make(map[string]rest.Storage) + { + configmapREST := configmapstorage.NewStorage(restOptionsGetter) + policyREST := policystorage.NewStorage(restOptionsGetter, platformClient) + rolestorageREST := rolestorage.NewStorage(restOptionsGetter, policyREST.Policy, platformClient) + mcrbREST := mcrbstorage.NewStorage(restOptionsGetter, rolestorageREST.Role, platformClient) + + storageMap["policies"] = policyREST.Policy + storageMap["roles"] = rolestorageREST.Role + storageMap["roles/finalize"] = rolestorageREST.Finalize + storageMap["multiclusterrolebindings"] = mcrbREST.MultiClusterRoleBinding + storageMap["multiclusterrolebindings/status"] = mcrbREST.Status + storageMap["multiclusterrolebindings/finalize"] = mcrbREST.Finalize + storageMap["configmaps"] = configmapREST.ConfigMap + } + return storageMap +} diff --git a/pkg/authz/registry/role/storage/storage.go b/pkg/authz/registry/role/storage/storage.go new file mode 100644 index 000000000..7b420a793 --- /dev/null +++ b/pkg/authz/registry/role/storage/storage.go @@ -0,0 +1,222 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package storage + +import ( + "context" + "fmt" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metainternal "k8s.io/apimachinery/pkg/apis/meta/internalversion" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + genericregistry "k8s.io/apiserver/pkg/registry/generic" + "k8s.io/apiserver/pkg/registry/generic/registry" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/apiserver/pkg/storage" + storageerr "k8s.io/apiserver/pkg/storage/errors" + "k8s.io/apiserver/pkg/util/dryrun" + "tkestack.io/tke/api/authz" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + "tkestack.io/tke/pkg/apiserver/authentication" + apiserverutil "tkestack.io/tke/pkg/apiserver/util" + "tkestack.io/tke/pkg/authz/registry/role" + "tkestack.io/tke/pkg/util/log" +) + +// Storage includes storage for configmap and all sub resources. +type Storage struct { + Role *REST + Finalize *FinalizeREST +} + +// NewStorage returns a Storage object that will work against configmap. +func NewStorage(optsGetter genericregistry.RESTOptionsGetter, policyGetter rest.Getter, platformClient platformversionedclient.PlatformV1Interface) *Storage { + strategy := role.NewStrategy(policyGetter, platformClient) + store := ®istry.Store{ + NewFunc: func() runtime.Object { return &authz.Role{} }, + NewListFunc: func() runtime.Object { return &authz.RoleList{} }, + DefaultQualifiedResource: authz.Resource("roles"), + ShouldDeleteDuringUpdate: role.ShouldDeleteDuringUpdate, + + CreateStrategy: strategy, + UpdateStrategy: strategy, + DeleteStrategy: strategy, + } + store.TableConvertor = rest.NewDefaultTableConvertor(store.DefaultQualifiedResource) + options := &genericregistry.StoreOptions{ + RESTOptions: optsGetter, + } + + if err := store.CompleteWithOptions(options); err != nil { + log.Panic("Failed to create configmap etcd rest storage", log.Err(err)) + } + + finalizeStore := *store + finalizeStore.UpdateStrategy = role.NewFinalizerStrategy(strategy) + + return &Storage{ + Role: &REST{store}, + Finalize: &FinalizeREST{&finalizeStore}, + } +} + +// REST implements a RESTStorage for configmap against etcd. +type REST struct { + *registry.Store +} + +var _ rest.ShortNamesProvider = &REST{} + +// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource. +func (r *REST) ShortNames() []string { + return []string{"rol"} +} + +// List selects resources in the storage which match to the selector. 'options' can be nil. +func (r *REST) List(ctx context.Context, options *metainternal.ListOptions) (runtime.Object, error) { + return r.Store.List(ctx, options) +} + +// Delete enforces life-cycle rules for policy termination +func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) { + _, tenantID := authentication.UsernameAndTenantID(ctx) + if tenantID == "" { + tenantID = "default" + } + object, err := r.Get(ctx, name, &metav1.GetOptions{}) + if err != nil { + return nil, false, err + } + role := object.(*authz.Role) + if tenantID != "default" && role.Namespace != tenantID { + return nil, false, fmt.Errorf("tenant '%s' can't delete role '%s/%s'", tenantID, role.Namespace, role.Name) + } + + // Ensure we have a UID precondition + if options == nil { + options = metav1.NewDeleteOptions(0) + } + if options.Preconditions == nil { + options.Preconditions = &metav1.Preconditions{} + } + if options.Preconditions.UID == nil { + options.Preconditions.UID = &role.UID + } else if *options.Preconditions.UID != role.UID { + err = apierrors.NewConflict( + authz.Resource("roles"), + name, + fmt.Errorf("precondition failed: UID in precondition: %v, UID in object meta: %v", *options.Preconditions.UID, role.UID), + ) + return nil, false, err + } + + // upon first request to delete, we switch the phase to start role termination + if role.DeletionTimestamp.IsZero() { + key, err := r.Store.KeyFunc(ctx, name) + if err != nil { + return nil, false, err + } + + preconditions := storage.Preconditions{UID: options.Preconditions.UID} + + out := r.Store.NewFunc() + err = r.Store.Storage.GuaranteedUpdate( + ctx, key, out, false, &preconditions, + storage.SimpleUpdate(func(existing runtime.Object) (runtime.Object, error) { + existingRole, ok := existing.(*authz.Role) + if !ok { + // wrong type + return nil, fmt.Errorf("expected *auth.Role, got %v", existing) + } + if err := deleteValidation(ctx, existingRole); err != nil { + return nil, err + } + // Set the deletion timestamp if needed + if existingRole.DeletionTimestamp.IsZero() { + now := metav1.Now() + existingRole.DeletionTimestamp = &now + } + + // the current finalizers which are on namespace + currentFinalizers := map[string]bool{} + for _, f := range existingRole.Finalizers { + currentFinalizers[f] = true + } + // the finalizers we should ensure on rule + shouldHaveFinalizers := map[string]bool{ + metav1.FinalizerOrphanDependents: apiserverutil.ShouldHaveOrphanFinalizer(options, currentFinalizers[metav1.FinalizerOrphanDependents]), + metav1.FinalizerDeleteDependents: apiserverutil.ShouldHaveDeleteDependentsFinalizer(options, currentFinalizers[metav1.FinalizerDeleteDependents]), + } + // determine whether there are changes + changeNeeded := false + for finalizer, shouldHave := range shouldHaveFinalizers { + changeNeeded = currentFinalizers[finalizer] != shouldHave || changeNeeded + if shouldHave { + currentFinalizers[finalizer] = true + } else { + delete(currentFinalizers, finalizer) + } + } + // make the changes if needed + if changeNeeded { + var newFinalizers []string + for f := range currentFinalizers { + newFinalizers = append(newFinalizers, f) + } + existingRole.Finalizers = newFinalizers + } + return existingRole, nil + }), + dryrun.IsDryRun(options.DryRun), + nil, + ) + + if err != nil { + err = storageerr.InterpretGetError(err, authz.Resource("roles"), name) + err = storageerr.InterpretUpdateError(err, authz.Resource("roles"), name) + if _, ok := err.(*apierrors.StatusError); !ok { + err = apierrors.NewInternalError(err) + } + return nil, false, err + } + + return out, false, nil + } + + // prior to final deletion, we must ensure that finalizers is empty + if len(role.Finalizers) != 0 { + err = apierrors.NewConflict(authz.Resource("roles"), role.Name, fmt.Errorf("the system is ensuring all content is removed from this role. Upon completion, this role will automatically be purged by the system")) + return nil, false, err + } + return r.Store.Delete(ctx, name, deleteValidation, options) +} + +// FinalizeREST implements Patcher. +var _ = rest.Patcher(&FinalizeREST{}) + +// FinalizeREST implements the REST endpoint for finalizing a policy. +type FinalizeREST struct { + *registry.Store +} + +// New returns an empty object that can be used with Create and Update after +// request data has been put into it. +func (r *FinalizeREST) New() runtime.Object { + return r.Store.New() +} diff --git a/pkg/authz/registry/role/strategy.go b/pkg/authz/registry/role/strategy.go new file mode 100644 index 000000000..cad275462 --- /dev/null +++ b/pkg/authz/registry/role/strategy.go @@ -0,0 +1,194 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package role + +import ( + "context" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/registry/generic/registry" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/apiserver/pkg/storage/names" + "tkestack.io/tke/api/authz" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + "tkestack.io/tke/pkg/apiserver/authentication" + authzprovider "tkestack.io/tke/pkg/authz/provider" + "tkestack.io/tke/pkg/util/log" + namesutil "tkestack.io/tke/pkg/util/names" +) + +// Strategy implements verification logic for configmap. +type Strategy struct { + runtime.ObjectTyper + names.NameGenerator + policyGetter rest.Getter + platformClient platformversionedclient.PlatformV1Interface +} + +const NamePrefix = "rol-" + +var _ rest.RESTCreateStrategy = &Strategy{} +var _ rest.RESTUpdateStrategy = &Strategy{} +var _ rest.RESTDeleteStrategy = &Strategy{} + +func ShouldDeleteDuringUpdate(ctx context.Context, key string, obj, existing runtime.Object) bool { + pol, ok := obj.(*authz.Role) + if !ok { + log.Errorf("unexpected object, key:%s", key) + return false + } + return len(pol.Finalizers) == 0 && registry.ShouldDeleteDuringUpdate(ctx, key, obj, existing) +} + +// NewStrategy creates a strategy that is the default logic that applies when +// creating and updating namespace set objects. +func NewStrategy(policyGetter rest.Getter, platformClient platformversionedclient.PlatformV1Interface) *Strategy { + return &Strategy{authz.Scheme, namesutil.Generator, policyGetter, platformClient} +} + +// DefaultGarbageCollectionPolicy returns the default garbage collection behavior. +func (Strategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy { + return rest.Unsupported +} + +// NamespaceScoped is false for namespaceSets +func (Strategy) NamespaceScoped() bool { + return true +} + +// Export strips fields that can not be set by the user. +func (Strategy) Export(ctx context.Context, obj runtime.Object, exact bool) error { + return nil +} + +// PrepareForCreate is invoked on create before validation to normalize +// the object. +func (Strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) { + username, _ := authentication.UsernameAndTenantID(ctx) + tenantID := request.NamespaceValue(ctx) + if tenantID == "" { + tenantID = "default" + } + + role, _ := obj.(*authz.Role) + role.TenantID = tenantID + if role.Username == "" { + role.Username = username + } + if role.Name == "" && role.GenerateName == "" { + role.GenerateName = NamePrefix + } + region := authentication.GetExtraValue("region", ctx) + log.Debugf("region '%v'", region) + if len(region) != 0 { + annotations := role.Annotations + if len(annotations) == 0 { + annotations = map[string]string{} + } + annotations[authz.GroupName+"/region"] = region[0] + role.Annotations = annotations + } + role.Finalizers = []string{string(authz.RoleFinalize)} +} + +// PrepareForUpdate is invoked on update before validation to normalize the +// object. +func (Strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) { + oldRole := old.(*authz.Role) + role, _ := obj.(*authz.Role) + if role.TenantID != oldRole.TenantID { + log.Warnf("Unauthorized update role tenantID '%s'", oldRole.TenantID) + role.TenantID = oldRole.TenantID + } +} + +// Validate validates a new configmap. +func (s Strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList { + role := obj.(*authz.Role) + provider, err := authzprovider.GetProvider(role.Annotations) + if err == nil { + if fieldErr := provider.Validate(context.TODO(), role, s.platformClient); fieldErr != nil { + return field.ErrorList{fieldErr} + } + } + return ValidateRole(role, s.policyGetter, s.platformClient) +} + +// AllowCreateOnUpdate is false for persistent events +func (Strategy) AllowCreateOnUpdate() bool { + return false +} + +// AllowUnconditionalUpdate returns true if the object can be updated +// unconditionally (irrespective of the latest resource version), when there is +// no resource version specified in the object. +func (Strategy) AllowUnconditionalUpdate() bool { + return false +} + +// WarningsOnCreate returns warnings for the creation of the given object. +func (Strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { + return nil +} + +// Canonicalize normalizes the object after validation. +func (Strategy) Canonicalize(obj runtime.Object) { +} + +// ValidateUpdate is the default update validation for an end namespace set. +func (s Strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList { + return ValidateRoleUpdate(ctx, obj.(*authz.Role), old.(*authz.Role), s.policyGetter, s.platformClient) +} + +// WarningsOnUpdate returns warnings for the given update. +func (Strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string { + return nil +} + +// FinalizeStrategy implements finalizer logic for Machine. +type FinalizeStrategy struct { + *Strategy +} + +var _ rest.RESTUpdateStrategy = &FinalizeStrategy{} + +// NewFinalizerStrategy create the FinalizeStrategy object by given strategy. +func NewFinalizerStrategy(strategy *Strategy) *FinalizeStrategy { + return &FinalizeStrategy{strategy} +} + +// PrepareForUpdate is invoked on update before validation to normalize +// the object. For example: remove fields that are not to be persisted, +// sort order-insensitive list fields, etc. This should not remove fields +// whose presence would be considered a validation error. +func (FinalizeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) { + newRole := obj.(*authz.Role) + oldRole := old.(*authz.Role) + finalizers := newRole.Finalizers + newRole = oldRole + newRole.Finalizers = finalizers +} + +// ValidateUpdate is invoked after default fields in the object have been +// filled in before the object is persisted. This method should not mutate +// the object. +func (s *FinalizeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList { + return nil +} diff --git a/pkg/authz/registry/role/validation.go b/pkg/authz/registry/role/validation.go new file mode 100644 index 000000000..9a084c124 --- /dev/null +++ b/pkg/authz/registry/role/validation.go @@ -0,0 +1,75 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package role + +import ( + "context" + "fmt" + apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/client-go/tools/cache" + "tkestack.io/tke/api/authz" + platformversionedclient "tkestack.io/tke/api/client/clientset/versioned/typed/platform/v1" + "tkestack.io/tke/pkg/apiserver/authentication" +) + +var ValidateRoleName = apimachineryvalidation.NameIsDNSLabel + +func ValidateRole(role *authz.Role, policyGetter rest.Getter, platformClient platformversionedclient.PlatformV1Interface) field.ErrorList { + allErrs := apimachineryvalidation.ValidateObjectMeta(&role.ObjectMeta, true, ValidateRoleName, field.NewPath("metadata")) + if role.Scope != authz.MultiClusterScope { + allErrs = append(allErrs, field.Invalid(field.NewPath("scope"), &role.ObjectMeta, "only support multicluster scope")) + } + for _, pol := range role.Policies { + polNs, polName, err := cache.SplitMetaNamespaceKey(pol) + if err != nil { + allErrs = append(allErrs, field.Required(field.NewPath("spec", "policies"), fmt.Sprintf("police '%s' invalidate", pol))) + return allErrs + } + if polNs != "" && polNs != "default" && polNs != role.Namespace { + allErrs = append(allErrs, field.Required(field.NewPath("spec", "policies"), fmt.Sprintf("police '%s' invalidate", pol))) + } + if polNs == "" { + polNs = "default" + } + ctx := request.WithNamespace(request.NewContext(), polNs) + if _, err := policyGetter.Get(ctx, polName, &metav1.GetOptions{}); err != nil { + allErrs = append(allErrs, field.Required(field.NewPath("spec", "policies"), fmt.Sprintf("police '%s' not exist", pol))) + } + } + return allErrs +} + +// ValidateRoleUpdate tests if required fields in the namespace set are +// set during an update. +func ValidateRoleUpdate(ctx context.Context, role *authz.Role, old *authz.Role, policyGetter rest.Getter, platformClient platformversionedclient.PlatformV1Interface) field.ErrorList { + _, tenantID := authentication.UsernameAndTenantID(ctx) + if tenantID == "" { + tenantID = "default" + } + if tenantID != "default" && tenantID != role.Namespace { + return append(field.ErrorList{}, field.Required(field.NewPath("metadata", "namespace"), fmt.Sprintf("tenant '%s' can't update role '%s/%s'", tenantID, role.Namespace, role.Name))) + } + allErrs := apimachineryvalidation.ValidateObjectMetaUpdate(&role.ObjectMeta, &old.ObjectMeta, field.NewPath("metadata")) + allErrs = append(allErrs, ValidateRole(role, policyGetter, platformClient)...) + return allErrs +} diff --git a/pkg/util/jwt/parse.go b/pkg/util/jwt/parse.go new file mode 100644 index 000000000..f26d79661 --- /dev/null +++ b/pkg/util/jwt/parse.go @@ -0,0 +1,19 @@ +package jwt + +import ( + "fmt" + "github.com/dgrijalva/jwt-go" +) + +var parser = &jwt.Parser{} + +func Parse(tokenStr string) (jwt.MapClaims, error) { + token, _, err := parser.ParseUnverified(tokenStr, jwt.MapClaims{}) + if err != nil { + return nil, err + } + if claims, ok := token.Claims.(jwt.MapClaims); ok { + return claims, nil + } + return nil, fmt.Errorf("convert to MapClaims failed") +} diff --git a/pkg/util/leaderelection/resourcelock/authz_lock.go b/pkg/util/leaderelection/resourcelock/authz_lock.go new file mode 100644 index 000000000..1d5f2fd24 --- /dev/null +++ b/pkg/util/leaderelection/resourcelock/authz_lock.go @@ -0,0 +1,103 @@ +/* + * Tencent is pleased to support the open source community by making TKEStack + * available. + * + * Copyright (C) 2012-2019 Tencent. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * https://opensource.org/licenses/Apache-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package resourcelock + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + v1 "tkestack.io/tke/api/authz/v1" + authzv1client "tkestack.io/tke/api/client/clientset/versioned/typed/authz/v1" +) + +// AuthzConfigMapLock defines the structure of using configmap resources to implement +// distributed locks. +type AuthzConfigMapLock struct { + // ConfigMapMeta should contain a Name and a Namespace of a + // ConfigMapMeta object that the LeaderElector will attempt to lead. + ConfigMapMeta metav1.ObjectMeta + Client authzv1client.ConfigMapsGetter + LockConfig Config + cm *v1.ConfigMap +} + +// Get returns the election record from a ConfigMap Annotation +func (cml *AuthzConfigMapLock) Get(ctx context.Context) (*LeaderElectionRecord, error) { + var record LeaderElectionRecord + var err error + cml.cm, err = cml.Client.ConfigMaps().Get(ctx, cml.ConfigMapMeta.Name, metav1.GetOptions{}) + if err != nil { + return nil, err + } + if cml.cm.Annotations == nil { + cml.cm.Annotations = make(map[string]string) + } + if recordBytes, found := cml.cm.Annotations[LeaderElectionRecordAnnotationKey]; found { + if err := json.Unmarshal([]byte(recordBytes), &record); err != nil { + return nil, err + } + } + return &record, nil +} + +// Create attempts to create a LeaderElectionRecord annotation +func (cml *AuthzConfigMapLock) Create(ctx context.Context, ler LeaderElectionRecord) error { + recordBytes, err := json.Marshal(ler) + if err != nil { + return err + } + cml.cm, err = cml.Client.ConfigMaps().Create(ctx, &v1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{ + Name: cml.ConfigMapMeta.Name, + Namespace: cml.ConfigMapMeta.Namespace, + Annotations: map[string]string{ + LeaderElectionRecordAnnotationKey: string(recordBytes), + }, + }, + }, metav1.CreateOptions{}) + return err +} + +// Update will update an existing annotation on a given resource. +func (cml *AuthzConfigMapLock) Update(ctx context.Context, ler LeaderElectionRecord) error { + if cml.cm == nil { + return errors.New("endpoint not initialized, call get or create first") + } + recordBytes, err := json.Marshal(ler) + if err != nil { + return err + } + cml.cm.Annotations[LeaderElectionRecordAnnotationKey] = string(recordBytes) + cml.cm, err = cml.Client.ConfigMaps().Update(ctx, cml.cm, metav1.UpdateOptions{}) + return err +} + +// Describe is used to convert details on current resource lock +// into a string +func (cml *AuthzConfigMapLock) Describe() string { + return fmt.Sprintf("%v/%v", cml.ConfigMapMeta.Namespace, cml.ConfigMapMeta.Name) +} + +// Identity returns the Identity of the lock +func (cml *AuthzConfigMapLock) Identity() string { + return cml.LockConfig.Identity +} diff --git a/pkg/util/leaderelection/resourcelock/resourcelock.go b/pkg/util/leaderelection/resourcelock/resourcelock.go index 6781a7234..b27ee06ef 100644 --- a/pkg/util/leaderelection/resourcelock/resourcelock.go +++ b/pkg/util/leaderelection/resourcelock/resourcelock.go @@ -22,6 +22,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" applicationv1 "tkestack.io/tke/api/client/clientset/versioned/typed/application/v1" authv1 "tkestack.io/tke/api/client/clientset/versioned/typed/auth/v1" + authzv1 "tkestack.io/tke/api/client/clientset/versioned/typed/authz/v1" businessv1 "tkestack.io/tke/api/client/clientset/versioned/typed/business/v1" logagentv1 "tkestack.io/tke/api/client/clientset/versioned/typed/logagent/v1" meshv1 "tkestack.io/tke/api/client/clientset/versioned/typed/mesh/v1" @@ -140,6 +141,17 @@ func NewApplication(name string, client applicationv1.ApplicationV1Interface, rl } } +// NewAuthz will create a lock of a given type according to the input parameters +func NewAuthz(name string, client authzv1.AuthzV1Interface, rlc Config) Interface { + return &AuthzConfigMapLock{ + ConfigMapMeta: metav1.ObjectMeta{ + Name: name, + }, + Client: client, + LockConfig: rlc, + } +} + // NewMesh will create a lock of a given type according to the input parameters func NewMesh(name string, client meshv1.MeshV1Interface, rlc Config) Interface { return &MeshConfigMapLock{ diff --git a/pkg/util/x509/parse.go b/pkg/util/x509/parse.go new file mode 100644 index 000000000..f83f686e0 --- /dev/null +++ b/pkg/util/x509/parse.go @@ -0,0 +1,21 @@ +package x509 + +import ( + "crypto/x509" + "encoding/base64" + "encoding/pem" +) + +func ParseBase64Encoded(encoded string) (*x509.Certificate, error) { + decodedBytes, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return nil, err + } + + decode, _ := pem.Decode(decodedBytes) + certificate, err := x509.ParseCertificate(decode.Bytes) + if err != nil { + return nil, err + } + return certificate, nil +}