namespace_controller.go 18.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 31
	corev1 "k8s.io/api/core/v1"
	rbac "k8s.io/api/rbac/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"
32
	"k8s.io/klog"
H
hongming 已提交
33 34
	"kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
	"kubesphere.io/kubesphere/pkg/constants"
H
hongming 已提交
35
	"kubesphere.io/kubesphere/pkg/models/iam"
H
hongming 已提交
36
	"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
H
hongming 已提交
37
	"kubesphere.io/kubesphere/pkg/utils/sliceutil"
H
hongming 已提交
38
	"openpitrix.io/openpitrix/pkg/pb"
H
hongming 已提交
39 40 41 42 43 44 45 46 47 48
	"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"
	"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 (
56 57
	admin    = rbac.Role{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{"*"}}}}
	operator = rbac.Role{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{"*"}},
H
hongming 已提交
58 59 60
		{Verbs: []string{"*"}, APIGroups: []string{"apps", "extensions", "batch", "logging.kubesphere.io", "monitoring.kubesphere.io", "iam.kubesphere.io", "autoscaling", "alerting.kubesphere.io", "openpitrix.io", "app.k8s.io", "servicemesh.kubesphere.io", "operations.kubesphere.io", "devops.kubesphere.io"}, Resources: []string{"*"}},
		{Verbs: []string{"*"}, APIGroups: []string{"", "resources.kubesphere.io"}, Resources: []string{"jobs", "cronjobs", "daemonsets", "deployments", "horizontalpodautoscalers", "ingresses", "endpoints", "configmaps", "events", "persistentvolumeclaims", "pods", "podtemplates", "pods", "secrets", "services"}},
	}}
61 62
	viewer       = rbac.Role{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{"*"}}}}
	defaultRoles = []rbac.Role{admin, operator, viewer}
H
hongming 已提交
63 64 65 66 67 68 69 70 71
)

/**
* 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.
72 73
func Add(mgr manager.Manager, openpitrixClient openpitrix.Client) error {
	return add(mgr, newReconciler(mgr, openpitrixClient))
H
hongming 已提交
74 75 76
}

// newReconciler returns a new reconcile.Reconciler
77 78 79 80 81 82
func newReconciler(mgr manager.Manager, openpitrixClient openpitrix.Client) reconcile.Reconciler {
	return &ReconcileNamespace{
		Client:           mgr.GetClient(),
		scheme:           mgr.GetScheme(),
		openpitrixClient: openpitrixClient,
	}
H
hongming 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
}

// 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 已提交
107
	openpitrixClient openpitrix.Client
Z
zryfish 已提交
108
	scheme           *runtime.Scheme
H
hongming 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122
}

// 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 已提交
123 124
			// The object is being deleted
			// our finalizer is present, so lets handle our external dependency
H
hongming 已提交
125 126 127 128 129 130
			return reconcile.Result{}, nil
		}
		// Error reading the object - requeue the request.
		return reconcile.Result{}, err
	}

H
hongming 已提交
131 132
	// name of your custom finalizer
	finalizer := "finalizers.kubesphere.io/namespaces"
J
Jeff 已提交
133

H
hongming 已提交
134 135 136 137 138 139 140 141
	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 已提交
142
		}
H
hongming 已提交
143 144 145
	} else {
		// The object is being deleted
		if sliceutil.HasString(instance.ObjectMeta.Finalizers, finalizer) {
H
hongming 已提交
146
			if err = r.deleteRouter(instance.Name); err != nil {
H
hongming 已提交
147 148
				return reconcile.Result{}, err
			}
J
Jeff 已提交
149

H
hongming 已提交
150 151 152 153
			// delete runtime
			if err = r.deleteRuntime(instance); err != nil {
				return reconcile.Result{}, err
			}
H
hongming 已提交
154 155 156 157 158 159 160 161 162

			// 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 已提交
163 164
		}

H
hongming 已提交
165
		// Our finalizer has finished, so the reconciler can do nothing.
H
hongming 已提交
166 167 168
		return reconcile.Result{}, nil
	}

169
	controlledByWorkspace, err := r.isControlledByWorkspace(instance)
H
hongming 已提交
170

171 172 173 174 175 176 177 178 179
	if err != nil {
		return reconcile.Result{}, err
	}

	if !controlledByWorkspace {

		err = r.deleteRoleBindings(instance)

		return reconcile.Result{}, err
H
hongming 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
	}

	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.checkAndCreateRuntime(instance); err != nil {
		return reconcile.Result{}, err
	}

	return reconcile.Result{}, nil
}

201 202 203 204 205 206 207 208 209 210 211 212
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 已提交
213 214 215 216 217 218 219 220 221 222 223
// 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
				err = r.Create(context.TODO(), role)
				if err != nil {
H
hongming 已提交
224
					klog.Error(err)
H
hongming 已提交
225
					return err
H
hongming 已提交
226
				}
H
hongming 已提交
227
			} else {
H
hongming 已提交
228
				klog.Error(err)
229 230 231 232 233
				return err
			}
		}
		if !reflect.DeepEqual(found.Rules, role.Rules) {
			found.Rules = role.Rules
H
hongming 已提交
234
			if err := r.Update(context.TODO(), found); err != nil {
H
hongming 已提交
235
				klog.Error(err)
H
hongming 已提交
236
				return err
H
hongming 已提交
237 238 239 240 241 242 243 244 245
			}
		}
	}
	return nil
}

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

	workspaceName := namespace.Labels[constants.WorkspaceLabelKey]
H
hongming 已提交
246
	creatorName := namespace.Annotations[constants.CreatorAnnotationKey]
H
hongming 已提交
247 248 249 250 251 252 253 254 255 256 257 258

	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{}
259
	adminBinding.Name = admin.Name
H
hongming 已提交
260
	adminBinding.Namespace = namespace.Name
261
	adminBinding.RoleRef = rbac.RoleRef{Name: admin.Name, APIGroup: "rbac.authorization.k8s.io", Kind: "Role"}
H
hongming 已提交
262 263 264 265 266 267
	adminBinding.Subjects = workspaceAdminBinding.Subjects

	if creator.Name != "" {
		if adminBinding.Subjects == nil {
			adminBinding.Subjects = make([]rbac.Subject, 0)
		}
H
hongming 已提交
268
		if !iam.ContainsUser(adminBinding.Subjects, creatorName) {
H
hongming 已提交
269 270 271 272 273 274 275 276 277 278 279
			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) {
		err = r.Create(context.TODO(), adminBinding)
		if err != nil {
280
			klog.Errorf("creating role binding namespace: %s,role binding: %s, error: %s", namespace.Name, adminBinding.Name, err)
H
hongming 已提交
281 282
			return err
		}
H
hongming 已提交
283
		found = adminBinding
H
hongming 已提交
284
	} else if err != nil {
285
		klog.Errorf("get role binding namespace: %s,role binding: %s, error: %s", namespace.Name, adminBinding.Name, err)
H
hongming 已提交
286 287 288 289 290 291
		return err
	}

	if !reflect.DeepEqual(found.RoleRef, adminBinding.RoleRef) {
		err = r.Delete(context.TODO(), found)
		if err != nil {
292
			klog.Errorf("deleting role binding namespace: %s, role binding: %s, error: %s", namespace.Name, adminBinding.Name, err)
H
hongming 已提交
293 294
			return err
		}
295 296 297
		err = fmt.Errorf("conflict role binding %s.%s, waiting for recreate", namespace.Name, adminBinding.Name)
		klog.Errorf("conflict role binding namespace: %s, role binding: %s, error: %s", namespace.Name, adminBinding.Name, err)
		return err
H
hongming 已提交
298 299 300 301 302 303
	}

	if !reflect.DeepEqual(found.Subjects, adminBinding.Subjects) {
		found.Subjects = adminBinding.Subjects
		err = r.Update(context.TODO(), found)
		if err != nil {
304
			klog.Errorf("updating role binding namespace: %s, role binding: %s, error: %s", namespace.Name, adminBinding.Name, err)
H
hongming 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317
			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{}
318
	viewerBinding.Name = viewer.Name
H
hongming 已提交
319
	viewerBinding.Namespace = namespace.Name
320
	viewerBinding.RoleRef = rbac.RoleRef{Name: viewer.Name, APIGroup: "rbac.authorization.k8s.io", Kind: "Role"}
H
hongming 已提交
321 322 323 324 325 326 327
	viewerBinding.Subjects = workspaceViewerBinding.Subjects

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

	if errors.IsNotFound(err) {
		err = r.Create(context.TODO(), viewerBinding)
		if err != nil {
328
			klog.Errorf("creating role binding namespace: %s, role binding: %s, error: %s", namespace.Name, viewerBinding.Name, err)
H
hongming 已提交
329 330
			return err
		}
H
hongming 已提交
331
		found = viewerBinding
H
hongming 已提交
332 333 334 335 336 337 338
	} else if err != nil {
		return err
	}

	if !reflect.DeepEqual(found.RoleRef, viewerBinding.RoleRef) {
		err = r.Delete(context.TODO(), found)
		if err != nil {
339
			klog.Errorf("deleting conflict role binding namespace: %s, role binding: %s, %s", namespace.Name, viewerBinding.Name, err)
H
hongming 已提交
340 341
			return err
		}
342 343 344
		err = fmt.Errorf("conflict role binding %s.%s, waiting for recreate", namespace.Name, viewerBinding.Name)
		klog.Errorf("conflict role binding namespace: %s, role binding: %s, error: %s", namespace.Name, viewerBinding.Name, err)
		return err
H
hongming 已提交
345 346 347 348 349 350
	}

	if !reflect.DeepEqual(found.Subjects, viewerBinding.Subjects) {
		found.Subjects = viewerBinding.Subjects
		err = r.Update(context.TODO(), found)
		if err != nil {
351
			klog.Errorf("updating role binding namespace: %s, role binding: %s, error: %s", namespace.Name, viewerBinding.Name, err)
H
hongming 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365
			return err
		}
	}

	return nil
}

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

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

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

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

	if err != nil {
H
hongming 已提交
371
		klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
H
hongming 已提交
372 373 374
		return err
	}

H
hongming 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388
	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 已提交
389
		resp, err := r.openpitrixClient.CreateRuntimeCredential(openpitrix.SystemContext(), &pb.CreateRuntimeCredentialRequest{
H
hongming 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
			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 已提交
405
	// TODO runtime id is invalid when recreate runtime
H
hongming 已提交
406
	runtimeId, err := r.openpitrixClient.CreateRuntime(openpitrix.SystemContext(), &pb.CreateRuntimeRequest{
H
hongming 已提交
407 408 409 410 411
		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 已提交
412

H
hongming 已提交
413 414
	if err != nil {
		klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
H
hongming 已提交
415 416 417
		return err
	}

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

H
hongming 已提交
420 421 422 423 424 425 426
	return nil
}

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

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

H
hongming 已提交
429 430 431 432 433
		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 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
		}
	}

	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 {
454
		// skip if workspace not found
H
hongming 已提交
455
		if errors.IsNotFound(err) {
H
hongming 已提交
456
			return nil
H
hongming 已提交
457
		}
458
		klog.Errorf("bind workspace namespace: %s, workspace: %s, error: %s", namespace.Name, workspaceName, err)
H
hongming 已提交
459 460 461 462 463
		return err
	}

	if !metav1.IsControlledBy(namespace, workspace) {
		if err := controllerutil.SetControllerReference(workspace, namespace, r.scheme); err != nil {
464
			klog.Errorf("bind workspace namespace: %s, workspace: %s, error: %s", namespace.Name, workspaceName, err)
H
hongming 已提交
465 466 467 468
			return err
		}
		err = r.Update(context.TODO(), namespace)
		if err != nil {
469
			klog.Errorf("bind workspace namespace: %s, workspace: %s, error: %s", namespace.Name, workspaceName, err)
H
hongming 已提交
470 471 472 473 474 475 476
			return err
		}
	}

	return nil
}

J
Jeff 已提交
477 478 479 480 481 482 483 484 485 486
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 已提交
487
		klog.Error(err)
J
Jeff 已提交
488 489 490 491
	}

	err = r.Delete(context.TODO(), &found)
	if err != nil {
H
hongming 已提交
492
		klog.Error(err)
J
Jeff 已提交
493 494 495 496 497 498 499 500 501 502
		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 已提交
503
		klog.Error(err)
J
Jeff 已提交
504 505 506 507 508
		return err
	}

	err = r.Delete(context.TODO(), &deploy)
	if err != nil {
H
hongming 已提交
509
		klog.Error(err)
J
Jeff 已提交
510 511 512 513 514 515
		return err
	}

	return nil

}
516 517

func (r *ReconcileNamespace) deleteRoleBindings(namespace *corev1.Namespace) error {
H
hongming 已提交
518
	klog.V(4).Info("deleting role bindings namespace: ", namespace.Name)
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
	adminBinding := &rbac.RoleBinding{}
	adminBinding.Name = admin.Name
	adminBinding.Namespace = namespace.Name
	err := r.Delete(context.TODO(), adminBinding)
	if err != nil && !errors.IsNotFound(err) {
		klog.Errorf("deleting role binding namespace: %s, role binding: %s,error: %s", namespace.Name, adminBinding.Name, err)
		return err
	}
	viewerBinding := &rbac.RoleBinding{}
	viewerBinding.Name = viewer.Name
	viewerBinding.Namespace = namespace.Name
	err = r.Delete(context.TODO(), viewerBinding)
	if err != nil && !errors.IsNotFound(err) {
		klog.Errorf("deleting role binding namespace: %s,role binding: %s,error: %s", namespace.Name, viewerBinding.Name, err)
		return err
	}
	return nil
}