namespace_controller.go 10.7 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 120 121 122
	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)
			if err := r.Update(context.Background(), instance); err != nil {
				return reconcile.Result{}, err
			}
J
Jeff 已提交
123
		}
H
hongming 已提交
124 125 126
	} else {
		// The object is being deleted
		if sliceutil.HasString(instance.ObjectMeta.Finalizers, finalizer) {
H
hongming 已提交
127
			if err = r.deleteRouter(instance.Name); err != nil {
H
hongming 已提交
128 129
				return reconcile.Result{}, err
			}
J
Jeff 已提交
130

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

			// 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 已提交
144 145
		}

H
hongming 已提交
146
		// Our finalizer has finished, so the reconciler can do nothing.
H
hongming 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160
		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
}

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

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

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

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

	if err != nil {
H
hongming 已提交
185
		klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
H
hongming 已提交
186 187 188
		return err
	}

H
hongming 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202
	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 已提交
203
		resp, err := r.openpitrixClient.CreateRuntimeCredential(openpitrix.SystemContext(), &pb.CreateRuntimeCredentialRequest{
H
hongming 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
			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 已提交
219
	// TODO runtime id is invalid when recreate runtime
H
hongming 已提交
220
	runtimeId, err := r.openpitrixClient.CreateRuntime(openpitrix.SystemContext(), &pb.CreateRuntimeRequest{
H
hongming 已提交
221 222 223 224 225
		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 已提交
226

H
hongming 已提交
227 228
	if err != nil {
		klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
H
hongming 已提交
229 230 231
		return err
	}

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

H
hongming 已提交
234 235 236 237 238 239 240
	return nil
}

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

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

H
hongming 已提交
243 244 245 246 247
		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 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
		}
	}

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

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

	return nil
}

J
Jeff 已提交
291 292 293 294 295 296 297 298 299 300
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 已提交
301
		klog.Error(err)
J
Jeff 已提交
302 303 304 305
	}

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

	err = r.Delete(context.TODO(), &deploy)
	if err != nil {
H
hongming 已提交
323
		klog.Error(err)
J
Jeff 已提交
324 325 326 327 328 329
		return err
	}

	return nil

}