workspaces.go 11.8 KB
Newer Older
H
hongming 已提交
1
/*
H
hongming 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * Copyright 2020 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.
 * /
 */
H
hongming 已提交
18 19 20
package tenant

import (
H
hongming 已提交
21 22
	"fmt"
	core "k8s.io/api/core/v1"
H
hongming 已提交
23
	rbacv1 "k8s.io/api/rbac/v1"
H
hongming 已提交
24 25 26 27
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/klog"
H
hongming 已提交
28
	"kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
H
hongming 已提交
29
	"kubesphere.io/kubesphere/pkg/client/informers/externalversions"
H
hongming 已提交
30
	"kubesphere.io/kubesphere/pkg/constants"
H
hongming 已提交
31 32
	"kubesphere.io/kubesphere/pkg/db"
	"kubesphere.io/kubesphere/pkg/models/devops"
H
hongming 已提交
33
	"kubesphere.io/kubesphere/pkg/models/iam"
Z
zryfish 已提交
34
	"kubesphere.io/kubesphere/pkg/models/resources/v1alpha2"
J
Jeff 已提交
35
	"kubesphere.io/kubesphere/pkg/server/params"
H
hongming 已提交
36 37
	clientset "kubesphere.io/kubesphere/pkg/simple/client"
	"kubesphere.io/kubesphere/pkg/simple/client/mysql"
H
hongming 已提交
38
	"kubesphere.io/kubesphere/pkg/utils/sliceutil"
H
hongming 已提交
39 40
	"sort"
	"strings"
H
hongming 已提交
41 42 43 44 45

	"k8s.io/api/rbac/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
H
hongming 已提交
46 47
)

H
hongming 已提交
48 49 50 51 52
type InWorkspaceUser struct {
	*iam.User
	WorkspaceRole string `json:"workspaceRole"`
}

H
hongming 已提交
53 54 55 56 57 58
type WorkspaceInterface interface {
	GetWorkspace(workspace string) (*v1alpha1.Workspace, error)
	SearchWorkspace(username string, conditions *params.Conditions, orderBy string, reverse bool) ([]*v1alpha1.Workspace, error)
	ListNamespaces(workspace string) ([]*core.Namespace, error)
	DeleteNamespace(workspace, namespace string) error
	RemoveUser(user, workspace string) error
H
hongming 已提交
59
	AddUser(workspace string, user *InWorkspaceUser) error
H
hongming 已提交
60 61 62 63 64 65 66 67 68 69 70
	CountDevopsProjectsInWorkspace(workspace string) (int, error)
	CountUsersInWorkspace(workspace string) (int, error)
	CountOrgRoles() (int, error)
	CountWorkspaces() (int, error)
	CountNamespacesInWorkspace(workspace string) (int, error)
}

type workspaceOperator struct {
	client      kubernetes.Interface
	informers   informers.SharedInformerFactory
	ksInformers externalversions.SharedInformerFactory
H
hongming 已提交
71
	am          iam.AccessManagementInterface
H
hongming 已提交
72 73 74 75 76 77

	// TODO: use db interface instead of mysql client
	// we can refactor this after rewrite devops using crd
	db *mysql.Database
}

H
hongming 已提交
78
func newWorkspaceOperator(client kubernetes.Interface, informers informers.SharedInformerFactory, ksinformers externalversions.SharedInformerFactory, am iam.AccessManagementInterface, db *mysql.Database) WorkspaceInterface {
H
hongming 已提交
79 80 81 82
	return &workspaceOperator{
		client:      client,
		informers:   informers,
		ksInformers: ksinformers,
H
hongming 已提交
83
		am:          am,
H
hongming 已提交
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
		db:          db,
	}
}

func (w *workspaceOperator) ListNamespaces(workspace string) ([]*core.Namespace, error) {
	namespaces, err := w.informers.Core().V1().Namespaces().Lister().List(labels.SelectorFromSet(labels.Set{constants.WorkspaceLabelKey: workspace}))

	if err != nil {
		return nil, err
	}

	return namespaces, nil
}

func (w *workspaceOperator) DeleteNamespace(workspace string, namespace string) error {
	ns, err := w.informers.Core().V1().Namespaces().Lister().Get(namespace)
	if err != nil {
		return err
	}

	if ns.Labels[constants.WorkspaceLabelKey] == workspace {
		deletePolicy := metav1.DeletePropagationBackground
		return w.client.CoreV1().Namespaces().Delete(namespace, &metav1.DeleteOptions{PropagationPolicy: &deletePolicy})
	} else {
		return apierrors.NewNotFound(schema.GroupResource{Group: "", Resource: "workspace"}, workspace)
	}
H
hongming 已提交
110 111
}

H
hongming 已提交
112
func (w *workspaceOperator) RemoveUser(workspace string, username string) error {
H
hongming 已提交
113
	workspaceRole, err := w.am.GetWorkspaceRole(workspace, username)
H
hongming 已提交
114 115 116 117 118 119 120 121 122 123 124 125
	if err != nil {
		return err
	}

	err = w.deleteWorkspaceRoleBinding(workspace, username, workspaceRole.Annotations[constants.DisplayNameAnnotationKey])
	if err != nil {
		return err
	}

	return nil
}

H
hongming 已提交
126
func (w *workspaceOperator) AddUser(workspaceName string, user *InWorkspaceUser) error {
H
hongming 已提交
127

H
hongming 已提交
128
	workspaceRole, err := w.am.GetWorkspaceRole(workspaceName, user.Username)
H
hongming 已提交
129 130 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

	if err != nil && !apierrors.IsNotFound(err) {
		klog.Errorf("get workspace role failed: %+v", err)
		return err
	}

	workspaceRoleName := fmt.Sprintf("workspace:%s:%s", workspaceName, strings.TrimPrefix(user.WorkspaceRole, "workspace-"))
	var currentWorkspaceRoleName string
	if workspaceRole != nil {
		currentWorkspaceRoleName = workspaceRole.Name
	}

	if currentWorkspaceRoleName != workspaceRoleName && currentWorkspaceRoleName != "" {
		err := w.deleteWorkspaceRoleBinding(workspaceName, user.Username, workspaceRole.Annotations[constants.DisplayNameAnnotationKey])
		if err != nil {
			klog.Errorf("delete workspace role binding failed: %+v", err)
			return err
		}
	} else if currentWorkspaceRoleName != "" {
		return nil
	}

	return w.createWorkspaceRoleBinding(workspaceName, user.Username, user.WorkspaceRole)
}

func (w *workspaceOperator) createWorkspaceRoleBinding(workspace, username string, role string) error {

	if !sliceutil.HasString(constants.WorkSpaceRoles, role) {
		return apierrors.NewNotFound(schema.GroupResource{Resource: "workspace role"}, role)
	}

	roleBindingName := fmt.Sprintf("workspace:%s:%s", workspace, strings.TrimPrefix(role, "workspace-"))
	workspaceRoleBinding, err := w.informers.Rbac().V1().ClusterRoleBindings().Lister().Get(roleBindingName)
	if err != nil {
		return err
	}

H
hongming 已提交
166
	if !iam.ContainsUser(workspaceRoleBinding.Subjects, username) {
H
hongming 已提交
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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
		workspaceRoleBinding = workspaceRoleBinding.DeepCopy()
		workspaceRoleBinding.Subjects = append(workspaceRoleBinding.Subjects, v1.Subject{APIGroup: "rbac.authorization.k8s.io", Kind: "User", Name: username})
		_, err = w.client.RbacV1().ClusterRoleBindings().Update(workspaceRoleBinding)
		if err != nil {
			klog.Errorf("update workspace role binding failed: %+v", err)
			return err
		}
	}

	return nil
}

func (w *workspaceOperator) deleteWorkspaceRoleBinding(workspace, username string, role string) error {

	if !sliceutil.HasString(constants.WorkSpaceRoles, role) {
		return apierrors.NewNotFound(schema.GroupResource{Resource: "workspace role"}, role)
	}

	roleBindingName := fmt.Sprintf("workspace:%s:%s", workspace, strings.TrimPrefix(role, "workspace-"))

	workspaceRoleBinding, err := w.informers.Rbac().V1().ClusterRoleBindings().Lister().Get(roleBindingName)
	if err != nil {
		return err
	}
	workspaceRoleBinding = workspaceRoleBinding.DeepCopy()

	for i, v := range workspaceRoleBinding.Subjects {
		if v.Kind == v1.UserKind && v.Name == username {
			workspaceRoleBinding.Subjects = append(workspaceRoleBinding.Subjects[:i], workspaceRoleBinding.Subjects[i+1:]...)
			i--
		}
	}

	workspaceRoleBinding, err = w.client.RbacV1().ClusterRoleBindings().Update(workspaceRoleBinding)

	return err
}

func (w *workspaceOperator) CountDevopsProjectsInWorkspace(workspaceName string) (int, error) {
	if w.db == nil {
		return 0, clientset.ErrClientSetNotEnabled
	}

	query := w.db.Select(devops.DevOpsProjectIdColumn).
		From(devops.DevOpsProjectTableName).
		Where(db.And(db.Eq(devops.DevOpsProjectWorkSpaceColumn, workspaceName),
			db.Eq(devops.StatusColumn, devops.StatusActive)))

	devOpsProjects := make([]string, 0)

	if _, err := query.Load(&devOpsProjects); err != nil {
		return 0, err
	}
	return len(devOpsProjects), nil
}

func (w *workspaceOperator) CountUsersInWorkspace(workspace string) (int, error) {
H
hongming 已提交
224
	count, err := w.CountUsersInWorkspace(workspace)
H
hongming 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
	if err != nil {
		return 0, err
	}
	return count, nil
}

func (w *workspaceOperator) CountOrgRoles() (int, error) {
	return len(constants.WorkSpaceRoles), nil
}

func (w *workspaceOperator) CountNamespacesInWorkspace(workspace string) (int, error) {
	ns, err := w.ListNamespaces(workspace)
	if err != nil {
		return 0, err
	}

	return len(ns), nil
}

func (*workspaceOperator) match(match map[string]string, item *v1alpha1.Workspace) bool {
H
hongming 已提交
245 246
	for k, v := range match {
		switch k {
Z
zryfish 已提交
247
		case v1alpha2.Name:
H
hongming 已提交
248 249
			names := strings.Split(v, "|")
			if !sliceutil.HasString(names, item.Name) {
H
hongming 已提交
250 251
				return false
			}
Z
zryfish 已提交
252
		case v1alpha2.Keyword:
H
hongming 已提交
253 254 255
			if !strings.Contains(item.Name, v) && !contains(item.Labels, "", v) && !contains(item.Annotations, "", v) {
				return false
			}
H
hongming 已提交
256
		default:
H
hongming 已提交
257 258
			// label not exist or value not equal
			if val, ok := item.Labels[k]; !ok || val != v {
H
hongming 已提交
259 260 261 262 263 264 265
				return false
			}
		}
	}
	return true
}

H
hongming 已提交
266
func (*workspaceOperator) fuzzy(fuzzy map[string]string, item *v1alpha1.Workspace) bool {
H
hongming 已提交
267 268 269

	for k, v := range fuzzy {
		switch k {
Z
zryfish 已提交
270
		case v1alpha2.Name:
H
hongming 已提交
271
			if !strings.Contains(item.Name, v) && !strings.Contains(item.Annotations[constants.DisplayNameAnnotationKey], v) {
H
hongming 已提交
272 273 274 275 276 277 278 279 280 281
				return false
			}
		default:
			return false
		}
	}

	return true
}

H
hongming 已提交
282
func (*workspaceOperator) compare(a, b *v1alpha1.Workspace, orderBy string) bool {
H
hongming 已提交
283
	switch orderBy {
Z
zryfish 已提交
284
	case v1alpha2.CreateTime:
H
hongming 已提交
285
		return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
Z
zryfish 已提交
286
	case v1alpha2.Name:
H
hongming 已提交
287 288 289 290 291 292
		fallthrough
	default:
		return strings.Compare(a.Name, b.Name) <= 0
	}
}

H
hongming 已提交
293
func (w *workspaceOperator) SearchWorkspace(username string, conditions *params.Conditions, orderBy string, reverse bool) ([]*v1alpha1.Workspace, error) {
H
hongming 已提交
294
	rules, err := w.am.GetClusterPolicyRules(username)
H
hongming 已提交
295 296 297 298 299 300 301 302

	if err != nil {
		return nil, err
	}

	workspaces := make([]*v1alpha1.Workspace, 0)

	if iam.RulesMatchesRequired(rules, rbacv1.PolicyRule{Verbs: []string{"list"}, APIGroups: []string{"tenant.kubesphere.io"}, Resources: []string{"workspaces"}}) {
H
hongming 已提交
303
		workspaces, err = w.ksInformers.Tenant().V1alpha1().Workspaces().Lister().List(labels.Everything())
H
hongming 已提交
304 305 306 307
		if err != nil {
			return nil, err
		}
	} else {
H
hongming 已提交
308
		workspaceRoles, err := w.am.GetWorkspaceRoleMap(username)
H
hongming 已提交
309 310 311 312
		if err != nil {
			return nil, err
		}
		for k := range workspaceRoles {
H
hongming 已提交
313
			workspace, err := w.ksInformers.Tenant().V1alpha1().Workspaces().Lister().Get(k)
H
hongming 已提交
314 315 316 317 318 319 320 321 322 323
			if err != nil {
				return nil, err
			}
			workspaces = append(workspaces, workspace)
		}
	}

	result := make([]*v1alpha1.Workspace, 0)

	for _, workspace := range workspaces {
H
hongming 已提交
324
		if w.match(conditions.Match, workspace) && w.fuzzy(conditions.Fuzzy, workspace) {
H
hongming 已提交
325 326 327 328 329 330 331
			result = append(result, workspace)
		}
	}

	// order & reverse
	sort.Slice(result, func(i, j int) bool {
		if reverse {
H
hongming 已提交
332
			i, j = j, i
H
hongming 已提交
333
		}
H
hongming 已提交
334
		return w.compare(result[i], result[j], orderBy)
H
hongming 已提交
335 336 337 338 339
	})

	return result, nil
}

H
hongming 已提交
340 341
func (w *workspaceOperator) GetWorkspace(workspaceName string) (*v1alpha1.Workspace, error) {
	return w.ksInformers.Tenant().V1alpha1().Workspaces().Lister().Get(workspaceName)
H
hongming 已提交
342
}
H
hongming 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355

func contains(m map[string]string, key, value string) bool {
	for k, v := range m {
		if key == "" {
			if strings.Contains(k, value) || strings.Contains(v, value) {
				return true
			}
		} else if k == key && strings.Contains(v, value) {
			return true
		}
	}
	return false
}
H
hongming 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399

/*
// TODO: move to metrics package
func GetAllProjectNums() (int, error) {
	namespaceLister := informers.SharedInformerFactory().Core().V1().Namespaces().Lister()
	list, err := namespaceLister.List(labels.Everything())
	if err != nil {
		return 0, err
	}
	return len(list), nil
}

func GetAllDevOpsProjectsNums() (int, error) {
	_, err := clientset.ClientSets().Devops()
	if _, notEnabled := err.(clientset.ClientSetNotEnabledError); notEnabled {
		return 0, err
	}

	dbconn, err := clientset.ClientSets().MySQL()
	if err != nil {
		return 0, err
	}

	query := dbconn.Select(devops.DevOpsProjectIdColumn).
		From(devops.DevOpsProjectTableName).
		Where(db.Eq(devops.StatusColumn, devops.StatusActive))

	devOpsProjects := make([]string, 0)

	if _, err := query.Load(&devOpsProjects); err != nil {
		return 0, err
	}
	return len(devOpsProjects), nil
}
*/

func (w *workspaceOperator) CountWorkspaces() (int, error) {
	ws, err := w.ksInformers.Tenant().V1alpha1().Workspaces().Lister().List(labels.Everything())
	if err != nil {
		return 0, err
	}

	return len(ws), nil
}