workspace_controller.go 5.9 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 20
*/

package workspace

import (
	"context"
Z
zryfish 已提交
21

H
hongming 已提交
22 23 24 25
	"github.com/go-logr/logr"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes/scheme"
H
hongming 已提交
26
	"k8s.io/client-go/tools/record"
Z
zryfish 已提交
27 28 29 30 31
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/controller"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"

H
hongming 已提交
32
	tenantv1alpha1 "kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
H
hongming 已提交
33 34 35
	"kubesphere.io/kubesphere/pkg/constants"
	controllerutils "kubesphere.io/kubesphere/pkg/controller/utils/controller"
	"kubesphere.io/kubesphere/pkg/utils/k8sutil"
H
hongming 已提交
36 37 38
	"kubesphere.io/kubesphere/pkg/utils/sliceutil"
)

H
hongming 已提交
39 40 41
const (
	controllerName = "workspace-controller"
)
H
hongming 已提交
42

H
hongming 已提交
43 44 45 46 47 48
// Reconciler reconciles a Workspace object
type Reconciler struct {
	client.Client
	Logger                  logr.Logger
	Recorder                record.EventRecorder
	MaxConcurrentReconciles int
H
hongming 已提交
49 50
}

H
hongming 已提交
51 52 53
func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error {
	if r.Client == nil {
		r.Client = mgr.GetClient()
H
hongming 已提交
54
	}
H
hongming 已提交
55 56
	if r.Logger == nil {
		r.Logger = ctrl.Log.WithName("controllers").WithName(controllerName)
H
hongming 已提交
57
	}
H
hongming 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70
	if r.Recorder == nil {
		r.Recorder = mgr.GetEventRecorderFor(controllerName)
	}
	if r.MaxConcurrentReconciles <= 0 {
		r.MaxConcurrentReconciles = 1
	}
	return ctrl.NewControllerManagedBy(mgr).
		Named(controllerName).
		WithOptions(controller.Options{
			MaxConcurrentReconciles: r.MaxConcurrentReconciles,
		}).
		For(&tenantv1alpha1.Workspace{}).
		Complete(r)
H
hongming 已提交
71 72 73 74
}

// +kubebuilder:rbac:groups=tenant.kubesphere.io,resources=workspaces,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=tenant.kubesphere.io,resources=workspaces/status,verbs=get;update;patch
H
hongming 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
// +kubebuilder:rbac:groups=iam.kubesphere.io,resources=users,verbs=get;list;watch
// +kubebuilder:rbac:groups=iam.kubesphere.io,resources=rolebases,verbs=get;list;watch
// +kubebuilder:rbac:groups=iam.kubesphere.io,resources=workspaceroles,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=iam.kubesphere.io,resources=workspacerolebindings,verbs=get;list;watch;create;update;patch;delete
func (r *Reconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
	logger := r.Logger.WithValues("workspace", req.NamespacedName)
	rootCtx := context.Background()
	workspace := &tenantv1alpha1.Workspace{}
	if err := r.Get(rootCtx, req.NamespacedName, workspace); err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}

	// controlled kubefed-controller-manager
	if workspace.Labels[constants.KubefedManagedLabel] == "true" {
		return ctrl.Result{}, nil
H
hongming 已提交
90 91 92 93 94
	}

	// name of your custom finalizer
	finalizer := "finalizers.tenant.kubesphere.io"

H
hongming 已提交
95
	if workspace.ObjectMeta.DeletionTimestamp.IsZero() {
H
hongming 已提交
96 97
		// The object is not being deleted, so if it does not have our finalizer,
		// then lets add the finalizer and update the object.
H
hongming 已提交
98 99 100 101
		if !sliceutil.HasString(workspace.ObjectMeta.Finalizers, finalizer) {
			workspace.ObjectMeta.Finalizers = append(workspace.ObjectMeta.Finalizers, finalizer)
			if err := r.Update(rootCtx, workspace); err != nil {
				return ctrl.Result{}, err
H
hongming 已提交
102
			}
L
LiHui 已提交
103
			workspaceOperation.WithLabelValues("create", workspace.Name).Inc()
H
hongming 已提交
104 105 106
		}
	} else {
		// The object is being deleted
H
hongming 已提交
107
		if sliceutil.HasString(workspace.ObjectMeta.Finalizers, finalizer) {
H
hongming 已提交
108
			// remove our finalizer from the list and update it.
H
hongming 已提交
109
			workspace.ObjectMeta.Finalizers = sliceutil.RemoveString(workspace.ObjectMeta.Finalizers, func(item string) bool {
H
hongming 已提交
110 111
				return item == finalizer
			})
H
hongming 已提交
112 113 114 115
			logger.V(4).Info("update workspace")
			if err := r.Update(rootCtx, workspace); err != nil {
				logger.Error(err, "update workspace failed")
				return ctrl.Result{}, err
H
hongming 已提交
116
			}
L
LiHui 已提交
117
			workspaceOperation.WithLabelValues("delete", workspace.Name).Inc()
H
hongming 已提交
118 119
		}
		// Our finalizer has finished, so the reconciler can do nothing.
H
hongming 已提交
120 121 122 123 124 125 126 127 128
		return ctrl.Result{}, nil
	}

	var namespaces corev1.NamespaceList
	if err := r.List(rootCtx, &namespaces, client.MatchingLabels{tenantv1alpha1.WorkspaceLabel: req.Name}); err != nil {
		logger.Error(err, "list namespaces failed")
		return ctrl.Result{}, err
	} else {
		for _, namespace := range namespaces.Items {
H
hongming 已提交
129 130 131 132 133 134
			// managed by kubefed-controller-manager
			kubefedManaged := namespace.Labels[constants.KubefedManagedLabel] == "true"
			if kubefedManaged {
				continue
			}
			// managed by workspace
H
hongming 已提交
135 136 137 138
			if err := r.bindWorkspace(rootCtx, logger, &namespace, workspace); err != nil {
				return ctrl.Result{}, err
			}
		}
H
hongming 已提交
139 140
	}

H
hongming 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
	r.Recorder.Event(workspace, corev1.EventTypeNormal, controllerutils.SuccessSynced, controllerutils.MessageResourceSynced)
	return ctrl.Result{}, nil
}

func (r *Reconciler) bindWorkspace(ctx context.Context, logger logr.Logger, namespace *corev1.Namespace, workspace *tenantv1alpha1.Workspace) error {
	// owner reference not match workspace label
	if !metav1.IsControlledBy(namespace, workspace) {
		namespace := namespace.DeepCopy()
		namespace.OwnerReferences = k8sutil.RemoveWorkspaceOwnerReference(namespace.OwnerReferences)
		if err := controllerutil.SetControllerReference(workspace, namespace, scheme.Scheme); err != nil {
			logger.Error(err, "set controller reference failed")
			return err
		}
		logger.V(4).Info("update namespace owner reference", "workspace", workspace.Name)
		if err := r.Update(ctx, namespace); err != nil {
			logger.Error(err, "update namespace failed")
			return err
		}
	}
	return nil
H
hongming 已提交
161
}