namespace_controller.go 7.1 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 namespace

import (
	"context"
J
Jeff 已提交
21
	appsv1 "k8s.io/api/apps/v1"
H
hongming 已提交
22 23 24 25 26
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
27
	"k8s.io/klog"
H
hongming 已提交
28 29
	"kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
	"kubesphere.io/kubesphere/pkg/constants"
H
hongming 已提交
30
	"kubesphere.io/kubesphere/pkg/utils/sliceutil"
H
hongming 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
	"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"
)

/**
* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller
* business logic.  Delete these comments after modifying this file.*
 */

// 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 已提交
47 48
func Add(mgr manager.Manager) error {
	return add(mgr, newReconciler(mgr))
H
hongming 已提交
49 50 51
}

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

// 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 已提交
81
	scheme *runtime.Scheme
H
hongming 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95
}

// 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 已提交
96 97
			// The object is being deleted
			// our finalizer is present, so lets handle our external dependency
H
hongming 已提交
98 99 100 101 102 103
			return reconcile.Result{}, nil
		}
		// Error reading the object - requeue the request.
		return reconcile.Result{}, err
	}

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

H
hongming 已提交
107 108 109 110 111
	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 已提交
112 113 114 115
			if instance.Labels == nil {
				instance.Labels = make(map[string]string)
			}
			instance.Labels[constants.NamespaceLabelKey] = instance.Name
H
hongming 已提交
116 117 118
			if err := r.Update(context.Background(), instance); err != nil {
				return reconcile.Result{}, err
			}
J
Jeff 已提交
119
		}
H
hongming 已提交
120 121 122
	} else {
		// The object is being deleted
		if sliceutil.HasString(instance.ObjectMeta.Finalizers, finalizer) {
H
hongming 已提交
123
			if err = r.deleteRouter(instance.Name); err != nil {
H
hongming 已提交
124 125
				return reconcile.Result{}, err
			}
J
Jeff 已提交
126

H
hongming 已提交
127 128 129 130 131 132 133 134
			// 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 已提交
135 136
		}

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

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

	return reconcile.Result{}, nil
}

148 149 150 151 152 153 154 155 156 157 158 159
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
}

H
hongming 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172
func (r *ReconcileNamespace) checkAndBindWorkspace(namespace *corev1.Namespace) error {

	workspaceName := namespace.Labels[constants.WorkspaceLabelKey]

	if workspaceName == "" {
		return nil
	}

	workspace := &v1alpha1.Workspace{}

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

	if err != nil {
173
		// skip if workspace not found
H
hongming 已提交
174
		if errors.IsNotFound(err) {
H
hongming 已提交
175
			return nil
H
hongming 已提交
176
		}
177
		klog.Errorf("bind workspace namespace: %s, workspace: %s, error: %s", namespace.Name, workspaceName, err)
H
hongming 已提交
178 179 180 181 182
		return err
	}

	if !metav1.IsControlledBy(namespace, workspace) {
		if err := controllerutil.SetControllerReference(workspace, namespace, r.scheme); err != nil {
183
			klog.Errorf("bind workspace namespace: %s, workspace: %s, error: %s", namespace.Name, workspaceName, err)
H
hongming 已提交
184 185 186 187
			return err
		}
		err = r.Update(context.TODO(), namespace)
		if err != nil {
188
			klog.Errorf("bind workspace namespace: %s, workspace: %s, error: %s", namespace.Name, workspaceName, err)
H
hongming 已提交
189 190 191 192 193 194 195
			return err
		}
	}

	return nil
}

J
Jeff 已提交
196 197 198 199 200 201 202 203 204 205
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 已提交
206
		klog.Error(err)
J
Jeff 已提交
207 208 209 210
	}

	err = r.Delete(context.TODO(), &found)
	if err != nil {
H
hongming 已提交
211
		klog.Error(err)
J
Jeff 已提交
212 213 214 215 216 217 218 219 220 221
		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 已提交
222
		klog.Error(err)
J
Jeff 已提交
223 224 225 226 227
		return err
	}

	err = r.Delete(context.TODO(), &deploy)
	if err != nil {
H
hongming 已提交
228
		klog.Error(err)
J
Jeff 已提交
229 230 231 232 233 234
		return err
	}

	return nil

}