namespace_controller.go 10.3 KB
Newer Older
H
hongming 已提交
1
/*
H
hongming 已提交
2
Copyright 2019 The KubeSphere Authors.
H
hongming 已提交
3

H
hongming 已提交
4 5 6
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
H
hongming 已提交
7

H
hongming 已提交
8
    http://www.apache.org/licenses/LICENSE-2.0
H
hongming 已提交
9

H
hongming 已提交
10 11 12 13 14
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
H
hongming 已提交
15 16 17 18 19
*/

package namespace

import (
20
	"bytes"
H
hongming 已提交
21
	"context"
22
	"fmt"
J
Jeff 已提交
23
	appsv1 "k8s.io/api/apps/v1"
H
hongming 已提交
24
	corev1 "k8s.io/api/core/v1"
25
	rbacv1 "k8s.io/api/rbac/v1"
H
hongming 已提交
26 27
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
28
	"k8s.io/apimachinery/pkg/labels"
H
hongming 已提交
29 30
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
31
	"k8s.io/apimachinery/pkg/util/yaml"
32
	"k8s.io/klog"
33 34
	iamv1alpha2 "kubesphere.io/kubesphere/pkg/apis/iam/v1alpha2"
	tenantv1alpha1 "kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
H
hongming 已提交
35
	"kubesphere.io/kubesphere/pkg/constants"
H
hongming 已提交
36
	"kubesphere.io/kubesphere/pkg/utils/sliceutil"
37
	"reflect"
H
hongming 已提交
38 39 40 41 42 43 44 45 46 47 48
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/controller"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
	"sigs.k8s.io/controller-runtime/pkg/handler"
	"sigs.k8s.io/controller-runtime/pkg/manager"
	"sigs.k8s.io/controller-runtime/pkg/reconcile"
	"sigs.k8s.io/controller-runtime/pkg/source"
)

// Add creates a new Namespace Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
Z
Zhengyi Lai 已提交
49 50
func Add(mgr manager.Manager) error {
	return add(mgr, newReconciler(mgr))
H
hongming 已提交
51 52 53
}

// newReconciler returns a new reconcile.Reconciler
Z
Zhengyi Lai 已提交
54
func newReconciler(mgr manager.Manager) reconcile.Reconciler {
55
	return &ReconcileNamespace{
Z
Zhengyi Lai 已提交
56 57
		Client: mgr.GetClient(),
		scheme: mgr.GetScheme(),
58
	}
H
hongming 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
}

// add adds a new Controller to mgr with r as the reconcile.Reconciler
func add(mgr manager.Manager, r reconcile.Reconciler) error {
	// Create a new controller
	c, err := controller.New("namespace-controller", mgr, controller.Options{Reconciler: r})
	if err != nil {
		return err
	}

	// Watch for changes to Namespace
	err = c.Watch(&source.Kind{Type: &corev1.Namespace{}}, &handler.EnqueueRequestForObject{})
	if err != nil {
		return err
	}

	return nil
}

var _ reconcile.Reconciler = &ReconcileNamespace{}

// ReconcileNamespace reconciles a Namespace object
type ReconcileNamespace struct {
	client.Client
Z
Zhengyi Lai 已提交
83
	scheme *runtime.Scheme
H
hongming 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97
}

// Reconcile reads that state of the cluster for a Namespace object and makes changes based on the state read
// and what is in the Namespace.Spec
// +kubebuilder:rbac:groups=core.kubesphere.io,resources=namespaces,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core.kubesphere.io,resources=namespaces/status,verbs=get;update;patch
func (r *ReconcileNamespace) Reconcile(request reconcile.Request) (reconcile.Result, error) {
	// Fetch the Namespace instance
	instance := &corev1.Namespace{}
	err := r.Get(context.TODO(), request.NamespacedName, instance)
	if err != nil {
		if errors.IsNotFound(err) {
			// Object not found, return.  Created objects are automatically garbage collected.
			// For additional cleanup logic use finalizers.
H
hongming 已提交
98 99
			// The object is being deleted
			// our finalizer is present, so lets handle our external dependency
H
hongming 已提交
100 101 102 103 104 105
			return reconcile.Result{}, nil
		}
		// Error reading the object - requeue the request.
		return reconcile.Result{}, err
	}

H
hongming 已提交
106 107
	// name of your custom finalizer
	finalizer := "finalizers.kubesphere.io/namespaces"
J
Jeff 已提交
108

H
hongming 已提交
109 110 111 112 113
	if instance.ObjectMeta.DeletionTimestamp.IsZero() {
		// The object is not being deleted, so if it does not have our finalizer,
		// then lets add the finalizer and update the object.
		if !sliceutil.HasString(instance.ObjectMeta.Finalizers, finalizer) {
			instance.ObjectMeta.Finalizers = append(instance.ObjectMeta.Finalizers, finalizer)
D
Duan Jiong 已提交
114 115 116 117
			if instance.Labels == nil {
				instance.Labels = make(map[string]string)
			}
			instance.Labels[constants.NamespaceLabelKey] = instance.Name
H
hongming 已提交
118 119 120
			if err := r.Update(context.Background(), instance); err != nil {
				return reconcile.Result{}, err
			}
J
Jeff 已提交
121
		}
H
hongming 已提交
122 123 124
	} else {
		// The object is being deleted
		if sliceutil.HasString(instance.ObjectMeta.Finalizers, finalizer) {
H
hongming 已提交
125
			if err = r.deleteRouter(instance.Name); err != nil {
H
hongming 已提交
126 127
				return reconcile.Result{}, err
			}
J
Jeff 已提交
128

H
hongming 已提交
129 130 131 132 133 134 135 136
			// remove our finalizer from the list and update it.
			instance.ObjectMeta.Finalizers = sliceutil.RemoveString(instance.ObjectMeta.Finalizers, func(item string) bool {
				return item == finalizer
			})

			if err := r.Update(context.Background(), instance); err != nil {
				return reconcile.Result{}, err
			}
H
hongming 已提交
137 138
		}

H
hongming 已提交
139
		// Our finalizer has finished, so the reconciler can do nothing.
H
hongming 已提交
140 141 142
		return reconcile.Result{}, nil
	}

143 144 145 146 147 148 149 150 151
	if err = r.bindWorkspace(instance); err != nil {
		return reconcile.Result{}, err
	}

	if err = r.initRoles(instance); err != nil {
		return reconcile.Result{}, err
	}

	if err = r.initCreatorRoleBinding(instance); err != nil {
H
hongming 已提交
152 153 154 155 156 157
		return reconcile.Result{}, err
	}

	return reconcile.Result{}, nil
}

158 159 160 161 162 163 164 165 166 167 168 169
func (r *ReconcileNamespace) isControlledByWorkspace(namespace *corev1.Namespace) (bool, error) {

	workspaceName := namespace.Labels[constants.WorkspaceLabelKey]

	// without workspace label
	if workspaceName == "" {
		return false, nil
	}

	return true, nil
}

170
func (r *ReconcileNamespace) bindWorkspace(namespace *corev1.Namespace) error {
H
hongming 已提交
171 172 173 174 175 176 177

	workspaceName := namespace.Labels[constants.WorkspaceLabelKey]

	if workspaceName == "" {
		return nil
	}

178
	workspace := &tenantv1alpha1.Workspace{}
H
hongming 已提交
179 180 181 182

	err := r.Get(context.TODO(), types.NamespacedName{Name: workspaceName}, workspace)

	if err != nil {
183
		// skip if workspace not found
H
hongming 已提交
184
		if errors.IsNotFound(err) {
H
hongming 已提交
185
			return nil
H
hongming 已提交
186
		}
187
		klog.Error(err)
H
hongming 已提交
188 189 190
		return err
	}

191 192
	// federated namespace not controlled by workspace
	if namespace.Labels[constants.KubefedManagedLabel] != "true" && !metav1.IsControlledBy(namespace, workspace) {
H
hongming 已提交
193
		namespace.OwnerReferences = nil
H
hongming 已提交
194
		if err := controllerutil.SetControllerReference(workspace, namespace, r.scheme); err != nil {
195
			klog.Error(err)
H
hongming 已提交
196 197 198 199
			return err
		}
		err = r.Update(context.TODO(), namespace)
		if err != nil {
200
			klog.Error(err)
H
hongming 已提交
201 202 203 204 205 206 207
			return err
		}
	}

	return nil
}

J
Jeff 已提交
208 209 210 211 212 213 214 215 216
func (r *ReconcileNamespace) deleteRouter(namespace string) error {
	routerName := constants.IngressControllerPrefix + namespace
	// delete service first
	found := corev1.Service{}
	err := r.Get(context.TODO(), types.NamespacedName{Namespace: constants.IngressControllerNamespace, Name: routerName}, &found)
	if err != nil {
		if errors.IsNotFound(err) {
			return nil
		}
H
hongming 已提交
217
		klog.Error(err)
J
Jeff 已提交
218 219 220 221
	}

	err = r.Delete(context.TODO(), &found)
	if err != nil {
H
hongming 已提交
222
		klog.Error(err)
J
Jeff 已提交
223 224 225 226 227 228 229 230 231 232
		return err
	}

	// delete deployment
	deploy := appsv1.Deployment{}
	err = r.Get(context.TODO(), types.NamespacedName{Namespace: constants.IngressControllerNamespace, Name: routerName}, &deploy)
	if err != nil {
		if errors.IsNotFound(err) {
			return nil
		}
H
hongming 已提交
233
		klog.Error(err)
J
Jeff 已提交
234 235 236 237 238
		return err
	}

	err = r.Delete(context.TODO(), &deploy)
	if err != nil {
H
hongming 已提交
239
		klog.Error(err)
J
Jeff 已提交
240 241 242 243
		return err
	}

	return nil
244 245 246 247 248
}

func (r *ReconcileNamespace) initRoles(namespace *corev1.Namespace) error {
	var roleBases iamv1alpha2.RoleBaseList

249 250 251 252 253 254 255 256 257 258
	var labelKey string
	// filtering initial roles by label
	if namespace.Labels[constants.DevOpsProjectLabelKey] != "" {
		// scope.kubesphere.io/devops: ""
		labelKey = fmt.Sprintf(iamv1alpha2.ScopeLabelFormat, iamv1alpha2.ScopeDevOps)
	} else {
		// scope.kubesphere.io/namespace: ""
		labelKey = fmt.Sprintf(iamv1alpha2.ScopeLabelFormat, iamv1alpha2.ScopeNamespace)
	}
	err := r.List(context.Background(), &roleBases, client.MatchingLabelsSelector{Selector: labels.SelectorFromSet(labels.Set{labelKey: ""})})
259 260 261 262
	if err != nil {
		klog.Error(err)
		return err
	}
J
Jeff 已提交
263

264 265
	for _, roleBase := range roleBases.Items {
		var role rbacv1.Role
H
hongming 已提交
266
		if err = yaml.NewYAMLOrJSONDecoder(bytes.NewBuffer(roleBase.Role.Raw), 1024).Decode(&role); err == nil && role.Kind == iamv1alpha2.ResourceKindRole {
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
			var old rbacv1.Role
			err := r.Client.Get(context.Background(), types.NamespacedName{Namespace: namespace.Name, Name: role.Name}, &old)
			if err != nil {
				if errors.IsNotFound(err) {
					role.Namespace = namespace.Name
					err = r.Client.Create(context.Background(), &role)
					if err != nil {
						klog.Error(err)
						return err
					}
					continue
				}
			}

			if !reflect.DeepEqual(role.Labels, old.Labels) ||
				!reflect.DeepEqual(role.Annotations, old.Annotations) ||
				!reflect.DeepEqual(role.Rules, old.Rules) {

				old.Labels = role.Labels
				old.Annotations = role.Annotations
				old.Rules = role.Rules

				return r.Update(context.Background(), &old)
			}
		}
	}
	return nil
}

H
hongming 已提交
296 297 298 299 300 301 302 303
func (r *ReconcileNamespace) resetNamespaceOwner(namespace *corev1.Namespace) error {
	namespace = namespace.DeepCopy()
	delete(namespace.Annotations, constants.CreatorAnnotationKey)
	err := r.Update(context.Background(), namespace)
	klog.V(4).Infof("update namespace after creator has been deleted")
	return err
}

304
func (r *ReconcileNamespace) initCreatorRoleBinding(namespace *corev1.Namespace) error {
H
hongming 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
	creator := namespace.Annotations[constants.CreatorAnnotationKey]
	if creator == "" {
		return nil
	}

	var user iamv1alpha2.User
	err := r.Get(context.Background(), types.NamespacedName{Name: creator}, &user)
	if err != nil {
		// skip if user has been deleted
		if errors.IsNotFound(err) {
			return r.resetNamespaceOwner(namespace)
		}
		klog.Error(err)
		return err
	}

	// skip if user has been deleted
	if !user.DeletionTimestamp.IsZero() {
		return r.resetNamespaceOwner(namespace)
	}

	creatorRoleBinding := &rbacv1.RoleBinding{
		ObjectMeta: metav1.ObjectMeta{
			Name:      fmt.Sprintf("%s-%s", creator, iamv1alpha2.NamespaceAdmin),
			Labels:    map[string]string{iamv1alpha2.UserReferenceLabel: creator},
			Namespace: namespace.Name,
		},
		RoleRef: rbacv1.RoleRef{
			APIGroup: rbacv1.GroupName,
			Kind:     iamv1alpha2.ResourceKindRole,
			Name:     iamv1alpha2.NamespaceAdmin,
		},
		Subjects: []rbacv1.Subject{
			{
				Name:     creator,
				Kind:     iamv1alpha2.ResourceKindUser,
341 342
				APIGroup: rbacv1.GroupName,
			},
H
hongming 已提交
343 344 345 346 347 348
		},
	}
	err = r.Client.Create(context.Background(), creatorRoleBinding)
	if err != nil {
		if errors.IsAlreadyExists(err) {
			return nil
349
		}
H
hongming 已提交
350 351
		klog.Error(err)
		return err
352 353 354
	}

	return nil
J
Jeff 已提交
355
}