namespace_controller.go 10.8 KB
Newer Older
H
hongming 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*

 Copyright 2019 The KubeSphere Authors.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

*/

package namespace

import (
	"context"
	"fmt"
H
hongming 已提交
24
	"github.com/golang/protobuf/ptypes/wrappers"
J
Jeff 已提交
25
	appsv1 "k8s.io/api/apps/v1"
H
hongming 已提交
26 27 28 29 30
	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"
31
	"k8s.io/klog"
H
hongming 已提交
32 33 34
	"kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
	"kubesphere.io/kubesphere/pkg/constants"
	"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
H
hongming 已提交
35
	"kubesphere.io/kubesphere/pkg/utils/sliceutil"
H
hongming 已提交
36
	"openpitrix.io/openpitrix/pkg/pb"
H
hongming 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
	"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.
53 54
func Add(mgr manager.Manager, openpitrixClient openpitrix.Client) error {
	return add(mgr, newReconciler(mgr, openpitrixClient))
H
hongming 已提交
55 56 57
}

// newReconciler returns a new reconcile.Reconciler
58 59 60 61 62 63
func newReconciler(mgr manager.Manager, openpitrixClient openpitrix.Client) reconcile.Reconciler {
	return &ReconcileNamespace{
		Client:           mgr.GetClient(),
		scheme:           mgr.GetScheme(),
		openpitrixClient: openpitrixClient,
	}
H
hongming 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
}

// 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
H
hongming 已提交
88
	openpitrixClient openpitrix.Client
Z
zryfish 已提交
89
	scheme           *runtime.Scheme
H
hongming 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103
}

// 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 已提交
104 105
			// The object is being deleted
			// our finalizer is present, so lets handle our external dependency
H
hongming 已提交
106 107 108 109 110 111
			return reconcile.Result{}, nil
		}
		// Error reading the object - requeue the request.
		return reconcile.Result{}, err
	}

H
hongming 已提交
112 113
	// name of your custom finalizer
	finalizer := "finalizers.kubesphere.io/namespaces"
J
Jeff 已提交
114

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

H
hongming 已提交
135 136 137 138
			// delete runtime
			if err = r.deleteRuntime(instance); err != nil {
				return reconcile.Result{}, err
			}
H
hongming 已提交
139 140 141 142 143 144 145 146 147

			// 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 已提交
148 149
		}

H
hongming 已提交
150
		// Our finalizer has finished, so the reconciler can do nothing.
H
hongming 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164
		return reconcile.Result{}, nil
	}

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

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

	return reconcile.Result{}, nil
}

165 166 167 168 169 170 171 172 173 174 175 176
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 已提交
177 178 179 180 181 182 183
// Create openpitrix runtime
func (r *ReconcileNamespace) checkAndCreateRuntime(namespace *corev1.Namespace) error {

	if runtimeId := namespace.Annotations[constants.OpenPitrixRuntimeAnnotationKey]; runtimeId != "" {
		return nil
	}

H
hongming 已提交
184 185
	adminKubeConfigName := fmt.Sprintf("kubeconfig-%s", constants.AdminUserName)

H
hongming 已提交
186
	runtimeCredentials, err := r.openpitrixClient.DescribeRuntimeCredentials(openpitrix.SystemContext(), &pb.DescribeRuntimeCredentialsRequest{SearchWord: &wrappers.StringValue{Value: adminKubeConfigName}, Limit: 1})
H
hongming 已提交
187 188

	if err != nil {
H
hongming 已提交
189
		klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
H
hongming 已提交
190 191 192
		return err
	}

H
hongming 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206
	var kubesphereRuntimeCredentialId string

	// runtime credential exist
	if len(runtimeCredentials.GetRuntimeCredentialSet()) > 0 {
		kubesphereRuntimeCredentialId = runtimeCredentials.GetRuntimeCredentialSet()[0].GetRuntimeCredentialId().GetValue()
	} else {
		adminKubeConfig := corev1.ConfigMap{}
		err := r.Get(context.TODO(), types.NamespacedName{Namespace: constants.KubeSphereControlNamespace, Name: adminKubeConfigName}, &adminKubeConfig)

		if err != nil {
			klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
			return err
		}

H
hongming 已提交
207
		resp, err := r.openpitrixClient.CreateRuntimeCredential(openpitrix.SystemContext(), &pb.CreateRuntimeCredentialRequest{
H
hongming 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
			Name:                     &wrappers.StringValue{Value: adminKubeConfigName},
			Provider:                 &wrappers.StringValue{Value: "kubernetes"},
			Description:              &wrappers.StringValue{Value: "kubeconfig"},
			RuntimeUrl:               &wrappers.StringValue{Value: "kubesphere"},
			RuntimeCredentialContent: &wrappers.StringValue{Value: adminKubeConfig.Data["config"]},
		})

		if err != nil {
			klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
			return err
		}

		kubesphereRuntimeCredentialId = resp.GetRuntimeCredentialId().GetValue()
	}

H
hongming 已提交
223
	// TODO runtime id is invalid when recreate runtime
H
hongming 已提交
224
	runtimeId, err := r.openpitrixClient.CreateRuntime(openpitrix.SystemContext(), &pb.CreateRuntimeRequest{
H
hongming 已提交
225 226 227 228 229
		Name:                &wrappers.StringValue{Value: namespace.Name},
		RuntimeCredentialId: &wrappers.StringValue{Value: kubesphereRuntimeCredentialId},
		Provider:            &wrappers.StringValue{Value: openpitrix.KubernetesProvider},
		Zone:                &wrappers.StringValue{Value: namespace.Name},
	})
H
hongming 已提交
230

H
hongming 已提交
231 232
	if err != nil {
		klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
H
hongming 已提交
233 234 235
		return err
	}

H
hongming 已提交
236 237
	klog.V(4).Infof("runtime created successfully, namespace: %s, runtime id: %s", namespace.Name, runtimeId)

H
hongming 已提交
238 239 240 241 242 243 244
	return nil
}

// Delete openpitrix runtime
func (r *ReconcileNamespace) deleteRuntime(namespace *corev1.Namespace) error {

	if runtimeId := namespace.Annotations[constants.OpenPitrixRuntimeAnnotationKey]; runtimeId != "" {
H
hongming 已提交
245
		_, err := r.openpitrixClient.DeleteRuntimes(openpitrix.SystemContext(), &pb.DeleteRuntimesRequest{RuntimeId: []string{runtimeId}, Force: &wrappers.BoolValue{Value: true}})
H
hongming 已提交
246

H
hongming 已提交
247 248 249 250 251
		if err == nil || openpitrix.IsNotFound(err) || openpitrix.IsDeleted(err) {
			return nil
		} else {
			klog.Errorf("delete openpitrix runtime: %s, error: %s", runtimeId, err)
			return err
H
hongming 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
		}
	}

	return nil
}

// Create openpitrix runtime
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 {
272
		// skip if workspace not found
H
hongming 已提交
273
		if errors.IsNotFound(err) {
H
hongming 已提交
274
			return nil
H
hongming 已提交
275
		}
276
		klog.Errorf("bind workspace namespace: %s, workspace: %s, error: %s", namespace.Name, workspaceName, err)
H
hongming 已提交
277 278 279 280 281
		return err
	}

	if !metav1.IsControlledBy(namespace, workspace) {
		if err := controllerutil.SetControllerReference(workspace, namespace, r.scheme); err != nil {
282
			klog.Errorf("bind workspace namespace: %s, workspace: %s, error: %s", namespace.Name, workspaceName, err)
H
hongming 已提交
283 284 285 286
			return err
		}
		err = r.Update(context.TODO(), namespace)
		if err != nil {
287
			klog.Errorf("bind workspace namespace: %s, workspace: %s, error: %s", namespace.Name, workspaceName, err)
H
hongming 已提交
288 289 290 291 292 293 294
			return err
		}
	}

	return nil
}

J
Jeff 已提交
295 296 297 298 299 300 301 302 303 304
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 已提交
305
		klog.Error(err)
J
Jeff 已提交
306 307 308 309
	}

	err = r.Delete(context.TODO(), &found)
	if err != nil {
H
hongming 已提交
310
		klog.Error(err)
J
Jeff 已提交
311 312 313 314 315 316 317 318 319 320
		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 已提交
321
		klog.Error(err)
J
Jeff 已提交
322 323 324 325 326
		return err
	}

	err = r.Delete(context.TODO(), &deploy)
	if err != nil {
H
hongming 已提交
327
		klog.Error(err)
J
Jeff 已提交
328 329 330 331 332 333
		return err
	}

	return nil

}