namespace_controller.go 16.5 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 24
/*

 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"
	"github.com/golang/glog"
J
Jeff 已提交
25
	appsv1 "k8s.io/api/apps/v1"
H
hongming 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
	corev1 "k8s.io/api/core/v1"
	rbac "k8s.io/api/rbac/v1"
	"k8s.io/api/storage/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"
	"k8s.io/kubernetes/pkg/apis/core"
	"kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
	"kubesphere.io/kubesphere/pkg/constants"
	"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
	"kubesphere.io/kubesphere/pkg/utils/k8sutil"
	"reflect"
	"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"
	logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
	"sigs.k8s.io/controller-runtime/pkg/source"
)

H
hongming 已提交
49 50 51 52 53 54
const (
	adminDescription    = "Allows admin access to perform any action on any resource, it gives full control over every resource in the namespace."
	operatorDescription = "The maintainer of the namespace who can manage resources other than users and roles in the namespace."
	viewerDescription   = "Allows viewer access to view all resources in the namespace."
)

H
hongming 已提交
55
var (
H
hongming 已提交
56
	log          = logf.Log.WithName("namespace-controller")
H
hongming 已提交
57
	defaultRoles = []rbac.Role{
H
hongming 已提交
58 59
		{ObjectMeta: metav1.ObjectMeta{Name: "admin", Annotations: map[string]string{constants.DescriptionAnnotationKey: adminDescription, constants.CreatorAnnotationKey: constants.System}}, Rules: []rbac.PolicyRule{{Verbs: []string{"*"}, APIGroups: []string{"*"}, Resources: []string{"*"}}}},
		{ObjectMeta: metav1.ObjectMeta{Name: "operator", Annotations: map[string]string{constants.DescriptionAnnotationKey: operatorDescription, constants.CreatorAnnotationKey: constants.System}}, Rules: []rbac.PolicyRule{{Verbs: []string{"get", "list", "watch"}, APIGroups: []string{"*"}, Resources: []string{"*"}},
不羁 已提交
60
			{Verbs: []string{"*"}, APIGroups: []string{"", "apps", "extensions", "batch", "logging.kubesphere.io", "monitoring.kubesphere.io", "iam.kubesphere.io", "resources.kubesphere.io", "autoscaling", "alerting.kubesphere.io", "app.k8s.io", "servicemesh.kubesphere.io"}, Resources: []string{"*"}}}},
H
hongming 已提交
61
		{ObjectMeta: metav1.ObjectMeta{Name: "viewer", Annotations: map[string]string{constants.DescriptionAnnotationKey: viewerDescription, constants.CreatorAnnotationKey: constants.System}}, Rules: []rbac.PolicyRule{{Verbs: []string{"get", "list", "watch"}, APIGroups: []string{"*"}, Resources: []string{"*"}}}},
H
hongming 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
	}
)

/**
* 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.
func Add(mgr manager.Manager) error {
	return add(mgr, newReconciler(mgr))
}

// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager) reconcile.Reconciler {
	return &ReconcileNamespace{Client: mgr.GetClient(), scheme: mgr.GetScheme()}
}

// 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
	scheme *runtime.Scheme
}

// 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.
			return reconcile.Result{}, nil
		}
		// Error reading the object - requeue the request.
		return reconcile.Result{}, err
	}

	if !instance.ObjectMeta.DeletionTimestamp.IsZero() {
		// The object is being deleted
J
Jeff 已提交
126 127 128 129 130

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

H
hongming 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
		if err := r.deleteRuntime(instance); err != nil {
			// if fail to delete the external dependency here, return with error
			// so that it can be retried
			return reconcile.Result{}, err
		}

		return reconcile.Result{}, nil
	}

	workspaceName := instance.Labels[constants.WorkspaceLabelKey]

	// delete default role bindings
	if workspaceName == "" {
		adminBinding := &rbac.RoleBinding{}
		adminBinding.Name = "admin"
		adminBinding.Namespace = instance.Name
		log.Info("Deleting default role binding", "namespace", instance.Name, "name", adminBinding.Name)
		err := r.Delete(context.TODO(), adminBinding)
		if err != nil && !errors.IsNotFound(err) {
			return reconcile.Result{}, err
		}
		viewerBinding := &rbac.RoleBinding{}
		viewerBinding.Name = "viewer"
		viewerBinding.Namespace = instance.Name
		log.Info("Deleting default role binding", "namespace", instance.Name, "name", viewerBinding.Name)
		err = r.Delete(context.TODO(), viewerBinding)
		if err != nil && !errors.IsNotFound(err) {
			return reconcile.Result{}, err
		}
		return reconcile.Result{}, nil
	}

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

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

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

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

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

	return reconcile.Result{}, nil
}

// Create default roles
func (r *ReconcileNamespace) checkAndCreateRoles(namespace *corev1.Namespace) error {
	for _, role := range defaultRoles {
		found := &rbac.Role{}
		err := r.Get(context.TODO(), types.NamespacedName{Namespace: namespace.Name, Name: role.Name}, found)
		if err != nil {
			if errors.IsNotFound(err) {
				role := role.DeepCopy()
				role.Namespace = namespace.Name
				log.Info("Creating default role", "namespace", namespace.Name, "role", role.Name)
				err = r.Create(context.TODO(), role)
				if err != nil {
H
hongming 已提交
198
					log.Info("Creating default role failed", "namespace", namespace.Name, "role", role.Name)
H
hongming 已提交
199 200
					return err
				}
H
hongming 已提交
201 202 203
			} else {
				log.Info("Get default role failed", "namespace", namespace.Name, "role", role.Name)
				return err
H
hongming 已提交
204 205 206 207 208 209 210 211 212
			}
		}
	}
	return nil
}

func (r *ReconcileNamespace) checkAndCreateRoleBindings(namespace *corev1.Namespace) error {

	workspaceName := namespace.Labels[constants.WorkspaceLabelKey]
H
hongming 已提交
213
	creatorName := namespace.Annotations[constants.CreatorAnnotationKey]
H
hongming 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249

	creator := rbac.Subject{APIGroup: "rbac.authorization.k8s.io", Kind: "User", Name: creatorName}

	workspaceAdminBinding := &rbac.ClusterRoleBinding{}

	err := r.Get(context.TODO(), types.NamespacedName{Name: fmt.Sprintf("workspace:%s:admin", workspaceName)}, workspaceAdminBinding)

	if err != nil {
		return err
	}

	adminBinding := &rbac.RoleBinding{}
	adminBinding.Name = "admin"
	adminBinding.Namespace = namespace.Name
	adminBinding.RoleRef = rbac.RoleRef{Name: "admin", APIGroup: "rbac.authorization.k8s.io", Kind: "Role"}
	adminBinding.Subjects = workspaceAdminBinding.Subjects

	if creator.Name != "" {
		if adminBinding.Subjects == nil {
			adminBinding.Subjects = make([]rbac.Subject, 0)
		}
		if !k8sutil.ContainsUser(adminBinding.Subjects, creatorName) {
			adminBinding.Subjects = append(adminBinding.Subjects, creator)
		}
	}

	found := &rbac.RoleBinding{}

	err = r.Get(context.TODO(), types.NamespacedName{Namespace: namespace.Name, Name: adminBinding.Name}, found)

	if errors.IsNotFound(err) {
		log.Info("Creating default role binding", "namespace", namespace.Name, "name", adminBinding.Name)
		err = r.Create(context.TODO(), adminBinding)
		if err != nil {
			return err
		}
H
hongming 已提交
250
		found = adminBinding
H
hongming 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 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
	} else if err != nil {
		return err
	}

	if !reflect.DeepEqual(found.RoleRef, adminBinding.RoleRef) {
		log.Info("Deleting conflict role binding", "namespace", namespace.Name, "name", adminBinding.Name)
		err = r.Delete(context.TODO(), found)
		if err != nil {
			return err
		}
		return fmt.Errorf("conflict role binding %s.%s, waiting for recreate", namespace.Name, adminBinding.Name)
	}

	if !reflect.DeepEqual(found.Subjects, adminBinding.Subjects) {
		found.Subjects = adminBinding.Subjects
		log.Info("Updating role binding", "namespace", namespace.Name, "name", adminBinding.Name)
		err = r.Update(context.TODO(), found)
		if err != nil {
			return err
		}
	}

	workspaceViewerBinding := &rbac.ClusterRoleBinding{}

	err = r.Get(context.TODO(), types.NamespacedName{Name: fmt.Sprintf("workspace:%s:viewer", workspaceName)}, workspaceViewerBinding)

	if err != nil {
		return err
	}

	viewerBinding := &rbac.RoleBinding{}
	viewerBinding.Name = "viewer"
	viewerBinding.Namespace = namespace.Name
	viewerBinding.RoleRef = rbac.RoleRef{Name: "viewer", APIGroup: "rbac.authorization.k8s.io", Kind: "Role"}
	viewerBinding.Subjects = workspaceViewerBinding.Subjects

	err = r.Get(context.TODO(), types.NamespacedName{Namespace: namespace.Name, Name: viewerBinding.Name}, found)

	if errors.IsNotFound(err) {
		log.Info("Creating default role binding", "namespace", namespace.Name, "name", viewerBinding.Name)
		err = r.Create(context.TODO(), viewerBinding)
		if err != nil {
			return err
		}
H
hongming 已提交
295
		found = viewerBinding
H
hongming 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
	} else if err != nil {
		return err
	}

	if !reflect.DeepEqual(found.RoleRef, viewerBinding.RoleRef) {
		log.Info("Deleting conflict role binding", "namespace", namespace.Name, "name", viewerBinding.Name)
		err = r.Delete(context.TODO(), found)
		if err != nil {
			return err
		}
		return fmt.Errorf("conflict role binding %s.%s, waiting for recreate", namespace.Name, viewerBinding.Name)
	}

	if !reflect.DeepEqual(found.Subjects, viewerBinding.Subjects) {
		found.Subjects = viewerBinding.Subjects
		log.Info("Updating role binding", "namespace", namespace.Name, "name", viewerBinding.Name)
		err = r.Update(context.TODO(), found)
		if err != nil {
			return err
		}
	}

	return nil
}

// Create openpitrix runtime
func (r *ReconcileNamespace) checkAndCreateRuntime(namespace *corev1.Namespace) error {

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

	cm := &corev1.ConfigMap{}
H
hongming 已提交
329 330
	configName := fmt.Sprintf("kubeconfig-%s", constants.AdminUserName)
	err := r.Get(context.TODO(), types.NamespacedName{Namespace: constants.KubeSphereControlNamespace, Name: configName}, cm)
H
hongming 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

	if err != nil {
		return err
	}

	runtime := &openpitrix.RunTime{Name: namespace.Name, Zone: namespace.Name, Provider: "kubernetes", RuntimeCredential: cm.Data["config"]}

	log.Info("Creating openpitrix runtime", "namespace", namespace.Name)
	if err := openpitrix.Client().CreateRuntime(runtime); err != nil {
		return err
	}

	return nil
}

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

	if runtimeId := namespace.Annotations[constants.OpenPitrixRuntimeAnnotationKey]; runtimeId != "" {
		log.Info("Deleting openpitrix runtime", "namespace", namespace.Name, "runtime", runtimeId)
		if err := openpitrix.Client().DeleteRuntime(runtimeId); err != nil {
			return err
		}
	}

	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 {
		if errors.IsNotFound(err) {
H
hongming 已提交
374 375
			log.Error(err, fmt.Sprintf("namespace %s bind workspace %s but not found", namespace.Name, workspaceName))
			return nil
H
hongming 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
		}
		return err
	}

	if !metav1.IsControlledBy(namespace, workspace) {
		if err := controllerutil.SetControllerReference(workspace, namespace, r.scheme); err != nil {
			return err
		}
		log.Info("Bind workspace", "namespace", namespace.Name, "workspace", workspaceName)
		err = r.Update(context.TODO(), namespace)
		if err != nil {
			return err
		}
	}

	return nil
}

//Create Ceph secret in the new namespace
func (r *ReconcileNamespace) checkAndCreateCephSecret(namespace *corev1.Namespace) error {

	newNsName := namespace.Name
	scList := &v1.StorageClassList{}
	err := r.List(context.TODO(), &client.ListOptions{}, scList)
	if err != nil {
		return err
	}
	for _, sc := range scList.Items {
		if sc.Provisioner == "kubernetes.io/rbd" {
			log.Info("would create Ceph user secret in storage class %s at namespace %s", sc.GetName(), newNsName)
			if secretName, ok := sc.Parameters["userSecretName"]; ok {
				secret := &corev1.Secret{}
				r.Get(context.TODO(), types.NamespacedName{Namespace: core.NamespaceSystem, Name: secretName}, secret)
				if err != nil {
					if errors.IsNotFound(err) {
						log.Error(err, "cannot find secret in namespace %s, error: %s", core.NamespaceSystem, secretName)
						continue
					}
					log.Error(err, fmt.Sprintf("failed to find secret in namespace %s", core.NamespaceSystem))
					continue
				}
				glog.Infof("succeed to find secret %s in namespace %s", secret.GetName(), secret.GetNamespace())

				newSecret := &corev1.Secret{
					TypeMeta: metav1.TypeMeta{
						Kind:       secret.Kind,
						APIVersion: secret.APIVersion,
					},
					ObjectMeta: metav1.ObjectMeta{
						Name:                       secret.GetName(),
						Namespace:                  newNsName,
						Labels:                     secret.GetLabels(),
						Annotations:                secret.GetAnnotations(),
						DeletionGracePeriodSeconds: secret.GetDeletionGracePeriodSeconds(),
						ClusterName:                secret.GetClusterName(),
					},
					Data:       secret.Data,
					StringData: secret.StringData,
					Type:       secret.Type,
				}
				log.Info(fmt.Sprintf("creating secret %s in namespace %s...", newSecret.GetName(), newSecret.GetNamespace()))

				err = r.Create(context.TODO(), newSecret)
				if err != nil {
					log.Error(err, fmt.Sprintf("failed to create secret in namespace %s", newSecret.GetNamespace()))
					continue
				}
			} else {
				log.Error(err, fmt.Sprintf("failed to find user secret name in storage class %s", sc.GetName()))
			}
		}
	}

	return nil
}
J
Jeff 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490

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
		}
		log.V(2).Info("get router service failed", err)
	}

	err = r.Delete(context.TODO(), &found)
	if err != nil {
		log.Error(err, "delete router failed")
		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
		}
		log.V(2).Info("get router deployment failed", err)
		return err
	}

	err = r.Delete(context.TODO(), &deploy)
	if err != nil {
		log.Error(err, "delete router deployment failed")
		return err
	}

	return nil

}