tenant.go 13.6 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
/*

 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 tenant

import (
H
hongming 已提交
21
	"fmt"
H
update  
hongming 已提交
22 23
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
H
hongming 已提交
24
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
H
hongming 已提交
25
	"k8s.io/apimachinery/pkg/runtime"
H
hongming 已提交
26
	"k8s.io/apiserver/pkg/authentication/user"
H
hongming 已提交
27
	"k8s.io/client-go/kubernetes"
H
update  
hongming 已提交
28 29
	"k8s.io/klog"
	"kubesphere.io/kubesphere/pkg/api"
J
junotx 已提交
30
	eventsv1alpha1 "kubesphere.io/kubesphere/pkg/api/events/v1alpha1"
H
hongming 已提交
31
	clusterv1alpha1 "kubesphere.io/kubesphere/pkg/apis/cluster/v1alpha1"
H
update  
hongming 已提交
32
	tenantv1alpha1 "kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
H
hongming 已提交
33 34

	tenantv1alpha2 "kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha2"
H
hongming 已提交
35 36
	"kubesphere.io/kubesphere/pkg/apiserver/authorization/authorizer"
	"kubesphere.io/kubesphere/pkg/apiserver/authorization/authorizerfactory"
H
hongming 已提交
37
	"kubesphere.io/kubesphere/pkg/apiserver/query"
H
hongming 已提交
38
	kubesphere "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
H
update  
hongming 已提交
39
	"kubesphere.io/kubesphere/pkg/informers"
J
junotx 已提交
40
	"kubesphere.io/kubesphere/pkg/models/events"
H
update  
hongming 已提交
41
	"kubesphere.io/kubesphere/pkg/models/iam/am"
H
hongming 已提交
42 43
	resources "kubesphere.io/kubesphere/pkg/models/resources/v1alpha3"
	resourcesv1alpha3 "kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/resource"
J
junotx 已提交
44 45 46 47
	eventsclient "kubesphere.io/kubesphere/pkg/simple/client/events"
	"kubesphere.io/kubesphere/pkg/utils/stringutils"
	"strings"
	"time"
H
hongming 已提交
48 49
)

H
hongming 已提交
50
type Interface interface {
H
hongming 已提交
51 52
	ListWorkspaces(user user.Info, query *query.Query) (*api.ListResult, error)
	ListNamespaces(user user.Info, workspace string, query *query.Query) (*api.ListResult, error)
H
hongming 已提交
53 54 55 56 57 58 59
	CreateNamespace(workspace string, namespace *corev1.Namespace) (*corev1.Namespace, error)
	CreateWorkspace(workspace *tenantv1alpha2.WorkspaceTemplate) (*tenantv1alpha2.WorkspaceTemplate, error)
	DeleteWorkspace(workspace string) error
	UpdateWorkspace(workspace *tenantv1alpha2.WorkspaceTemplate) (*tenantv1alpha2.WorkspaceTemplate, error)
	DescribeWorkspace(workspace string) (*tenantv1alpha2.WorkspaceTemplate, error)
	ListWorkspaceClusters(workspace string) (*api.ListResult, error)

J
junotx 已提交
60
	Events(user user.Info, queryParam *eventsv1alpha1.Query) (*eventsv1alpha1.APIResponse, error)
H
hongming 已提交
61
}
H
hongming 已提交
62

H
hongming 已提交
63
type tenantOperator struct {
H
hongming 已提交
64 65
	am             am.AccessManagementInterface
	authorizer     authorizer.Authorizer
H
hongming 已提交
66 67
	k8sclient      kubernetes.Interface
	ksclient       kubesphere.Interface
H
hongming 已提交
68
	resourceGetter *resourcesv1alpha3.ResourceGetter
J
junotx 已提交
69
	events         events.Interface
H
hongming 已提交
70 71
}

H
hongming 已提交
72 73 74
func New(informers informers.InformerFactory, k8sclient kubernetes.Interface, ksclient kubesphere.Interface, evtsClient eventsclient.Client) Interface {
	amOperator := am.NewReadOnlyOperator(informers)
	authorizer := authorizerfactory.NewRBACAuthorizer(amOperator)
H
update  
hongming 已提交
75
	return &tenantOperator{
H
hongming 已提交
76
		am:             amOperator,
H
hongming 已提交
77
		authorizer:     authorizer,
H
hongming 已提交
78
		resourceGetter: resourcesv1alpha3.NewResourceGetter(informers),
H
hongming 已提交
79 80
		k8sclient:      k8sclient,
		ksclient:       ksclient,
J
junotx 已提交
81
		events:         events.NewEventsOperator(evtsClient),
H
update  
hongming 已提交
82
	}
H
hongming 已提交
83 84
}

H
hongming 已提交
85
func (t *tenantOperator) ListWorkspaces(user user.Info, queryParam *query.Query) (*api.ListResult, error) {
H
hongming 已提交
86 87

	listWS := authorizer.AttributesRecord{
H
hongming 已提交
88 89 90 91 92 93
		User:            user,
		Verb:            "list",
		APIGroup:        "tenant.kubesphere.io",
		APIVersion:      "v1alpha2",
		Resource:        "workspaces",
		ResourceRequest: true,
H
hongming 已提交
94 95 96
	}

	decision, _, err := t.authorizer.Authorize(listWS)
H
hongming 已提交
97

H
update  
hongming 已提交
98 99 100 101
	if err != nil {
		klog.Error(err)
		return nil, err
	}
H
hongming 已提交
102

H
hongming 已提交
103
	if decision == authorizer.DecisionAllow {
H
update  
hongming 已提交
104

H
hongming 已提交
105
		result, err := t.resourceGetter.List(tenantv1alpha2.ResourcePluralWorkspaceTemplate, "", queryParam)
H
hongming 已提交
106

H
update  
hongming 已提交
107 108 109 110
		if err != nil {
			klog.Error(err)
			return nil, err
		}
H
hongming 已提交
111

H
hongming 已提交
112 113 114 115 116 117 118 119 120
		return result, nil
	}

	workspaceRoleBindings, err := t.am.ListWorkspaceRoleBindings(user.GetName(), "")

	if err != nil {
		klog.Error(err)
		return nil, err
	}
H
hongming 已提交
121

H
hongming 已提交
122
	workspaces := make([]runtime.Object, 0)
H
hongming 已提交
123

H
hongming 已提交
124
	for _, roleBinding := range workspaceRoleBindings {
H
hongming 已提交
125

H
hongming 已提交
126
		workspaceName := roleBinding.Labels[tenantv1alpha1.WorkspaceLabel]
H
hongming 已提交
127
		workspace, err := t.resourceGetter.Get(tenantv1alpha2.ResourcePluralWorkspaceTemplate, "", workspaceName)
H
hongming 已提交
128

H
hongming 已提交
129
		if errors.IsNotFound(err) {
H
hongming 已提交
130
			klog.Warningf("workspace role binding: %+v found but workspace not exist", roleBinding.ObjectMeta.String())
H
hongming 已提交
131 132 133 134 135 136 137 138 139 140
			continue
		}

		if err != nil {
			klog.Error(err)
			return nil, err
		}

		if !contains(workspaces, workspace) {
			workspaces = append(workspaces, workspace)
H
update  
hongming 已提交
141
		}
H
hongming 已提交
142
	}
H
hongming 已提交
143

H
hongming 已提交
144 145 146 147 148 149 150
	result := resources.DefaultList(workspaces, queryParam, func(left runtime.Object, right runtime.Object, field query.Field) bool {
		return resources.DefaultObjectMetaCompare(left.(*tenantv1alpha1.Workspace).ObjectMeta, right.(*tenantv1alpha1.Workspace).ObjectMeta, field)
	}, func(workspace runtime.Object, filter query.Filter) bool {
		return resources.DefaultObjectMetaFilter(workspace.(*tenantv1alpha1.Workspace).ObjectMeta, filter)
	})

	return result, nil
H
hongming 已提交
151 152
}

H
hongming 已提交
153
func (t *tenantOperator) ListNamespaces(user user.Info, workspace string, queryParam *query.Query) (*api.ListResult, error) {
H
hongming 已提交
154 155

	listNSInWS := authorizer.AttributesRecord{
H
hongming 已提交
156 157 158 159 160 161 162
		User:            user,
		Verb:            "list",
		APIGroup:        "",
		APIVersion:      "v1",
		Workspace:       workspace,
		Resource:        "namespaces",
		ResourceRequest: true,
H
hongming 已提交
163
	}
H
update  
hongming 已提交
164

H
hongming 已提交
165
	decision, _, err := t.authorizer.Authorize(listNSInWS)
H
hongming 已提交
166 167

	if err != nil {
H
update  
hongming 已提交
168
		klog.Error(err)
H
hongming 已提交
169 170 171
		return nil, err
	}

H
hongming 已提交
172
	if decision == authorizer.DecisionAllow {
H
hongming 已提交
173

H
hongming 已提交
174
		queryParam.Filters[query.FieldLabel] = query.Value(fmt.Sprintf("%s=%s", tenantv1alpha1.WorkspaceLabel, workspace))
H
hongming 已提交
175 176

		result, err := t.resourceGetter.List("namespaces", "", queryParam)
H
hongming 已提交
177

H
update  
hongming 已提交
178 179 180 181
		if err != nil {
			klog.Error(err)
			return nil, err
		}
H
hongming 已提交
182

H
hongming 已提交
183 184 185 186
		return result, nil
	}

	roleBindings, err := t.am.ListRoleBindings(user.GetName(), "")
H
hongming 已提交
187

H
hongming 已提交
188 189 190 191
	if err != nil {
		klog.Error(err)
		return nil, err
	}
H
hongming 已提交
192

H
hongming 已提交
193
	namespaces := make([]runtime.Object, 0)
H
hongming 已提交
194

H
hongming 已提交
195
	for _, roleBinding := range roleBindings {
H
hongming 已提交
196
		namespace, err := t.resourceGetter.Get("namespaces", "", roleBinding.Namespace)
H
update  
hongming 已提交
197

H
hongming 已提交
198 199 200 201
		if err != nil {
			klog.Error(err)
			return nil, err
		}
H
update  
hongming 已提交
202

H
hongming 已提交
203 204 205 206 207
		// skip if not controlled by the specified workspace
		if ns := namespace.(*corev1.Namespace); ns.Labels[tenantv1alpha1.WorkspaceLabel] != workspace {
			continue
		}

H
hongming 已提交
208 209
		if !contains(namespaces, namespace) {
			namespaces = append(namespaces, namespace)
H
update  
hongming 已提交
210
		}
H
hongming 已提交
211 212
	}

H
hongming 已提交
213 214 215 216 217 218
	result := resources.DefaultList(namespaces, queryParam, func(left runtime.Object, right runtime.Object, field query.Field) bool {
		return resources.DefaultObjectMetaCompare(left.(*corev1.Namespace).ObjectMeta, right.(*corev1.Namespace).ObjectMeta, field)
	}, func(object runtime.Object, filter query.Filter) bool {
		namespace := object.(*corev1.Namespace).ObjectMeta
		if workspaceLabel, ok := namespace.Labels[tenantv1alpha1.WorkspaceLabel]; !ok || workspaceLabel != workspace {
			return false
H
hongming 已提交
219
		}
H
hongming 已提交
220 221
		return resources.DefaultObjectMetaFilter(namespace, filter)
	})
H
hongming 已提交
222

H
hongming 已提交
223
	return result, nil
H
update  
hongming 已提交
224 225
}

H
hongming 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 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
func (t *tenantOperator) CreateNamespace(workspace string, namespace *corev1.Namespace) (*corev1.Namespace, error) {

	_, err := t.resourceGetter.Get(tenantv1alpha1.ResourcePluralWorkspace, "", workspace)

	if err != nil {
		return nil, err
	}

	if namespace.Annotations == nil {
		namespace.Annotations = make(map[string]string, 0)
	}

	namespace.Annotations[tenantv1alpha1.WorkspaceLabel] = workspace

	return t.k8sclient.CoreV1().Namespaces().Create(namespace)
}

func (t *tenantOperator) CreateWorkspace(workspace *tenantv1alpha2.WorkspaceTemplate) (*tenantv1alpha2.WorkspaceTemplate, error) {
	return t.ksclient.TenantV1alpha2().WorkspaceTemplates().Create(workspace)
}

func (t *tenantOperator) UpdateWorkspace(workspace *tenantv1alpha2.WorkspaceTemplate) (*tenantv1alpha2.WorkspaceTemplate, error) {
	return t.ksclient.TenantV1alpha2().WorkspaceTemplates().Update(workspace)
}

func (t *tenantOperator) DescribeWorkspace(workspace string) (*tenantv1alpha2.WorkspaceTemplate, error) {
	obj, err := t.resourceGetter.Get(tenantv1alpha2.ResourcePluralWorkspaceTemplate, "", workspace)
	if err != nil {
		klog.Error(err)
		return nil, err
	}
	return obj.(*tenantv1alpha2.WorkspaceTemplate), nil
}
func (t *tenantOperator) ListWorkspaceClusters(workspaceName string) (*api.ListResult, error) {
	workspace, err := t.DescribeWorkspace(workspaceName)
	if err != nil {
		klog.Error(err)
		return nil, err
	}
	clusters := make([]interface{}, 0)
	for _, cluster := range workspace.Spec.Clusters {
		obj, err := t.resourceGetter.Get(clusterv1alpha1.ResourcesPluralCluster, "", cluster)
		if err != nil {
			klog.Error(err)
			if errors.IsNotFound(err) {
				continue
			}
			return nil, err
		}
		cluster := obj.(*clusterv1alpha1.Cluster)
		clusters = append(clusters, cluster)
	}
	return &api.ListResult{Items: clusters, TotalItems: len(clusters)}, nil
}

func (t *tenantOperator) DeleteWorkspace(workspace string) error {
	return t.ksclient.TenantV1alpha2().WorkspaceTemplates().Delete(workspace, metav1.NewDeleteOptions(0))
}

J
junotx 已提交
285 286 287 288 289 290 291 292 293 294 295 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 329 330 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 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 400 401 402 403 404 405 406 407 408 409
// listIntersectedNamespaces lists the namespaces which meet all the following conditions at the same time
// 1. the namespace which belongs to user.
// 2. the namespace in workspace which is in workspaces when workspaces is not empty.
// 3. the namespace in workspace which contains one of workspaceSubstrs when workspaceSubstrs is not empty.
// 4. the namespace which is in namespaces when namespaces is not empty.
// 5. the namespace which contains one of namespaceSubstrs when namespaceSubstrs is not empty.
func (t *tenantOperator) listIntersectedNamespaces(user user.Info,
	workspaces, workspaceSubstrs, namespaces, namespaceSubstrs []string) ([]*corev1.Namespace, error) {
	var (
		namespaceSet = stringSet(namespaces)
		workspaceSet = stringSet(workspaces)

		iNamespaces []*corev1.Namespace
	)

	// When user can list all namespaces, the namespaces which do not belong to any workspace should be considered
	listNs := authorizer.AttributesRecord{
		User:            user,
		Verb:            "list",
		APIGroup:        "",
		APIVersion:      "v1",
		Resource:        "namespaces",
		ResourceRequest: true,
	}
	decision, _, err := t.authorizer.Authorize(listNs)
	if err != nil {
		return nil, err
	}
	includeNsWithoutWs := len(workspaceSet) == 0 && len(workspaceSubstrs) == 0 && decision == authorizer.DecisionAllow

	roleBindings, err := t.am.ListRoleBindings(user.GetName(), "")
	if err != nil {
		return nil, err
	}
	for _, rb := range roleBindings {
		if len(namespaceSet) > 0 {
			if _, ok := namespaceSet[rb.Namespace]; !ok {
				continue
			}
		}
		if len(namespaceSubstrs) > 0 && !stringContains(rb.Namespace, namespaceSubstrs) {
			continue
		}
		ns, err := t.resourceGetter.Get("namespaces", "", rb.Namespace)
		if err != nil {
			return nil, err
		}
		if ns, ok := ns.(*corev1.Namespace); ok {
			if ws := ns.Labels[tenantv1alpha1.WorkspaceLabel]; ws != "" {
				if len(workspaceSet) > 0 {
					if _, ok := workspaceSet[ws]; !ok {
						continue
					}
				}
				if len(workspaceSubstrs) > 0 && !stringContains(ws, workspaceSubstrs) {
					continue
				}
			} else if !includeNsWithoutWs {
				continue
			}
			iNamespaces = append(iNamespaces, ns)
		}
	}
	return iNamespaces, nil
}

func (t *tenantOperator) Events(user user.Info, queryParam *eventsv1alpha1.Query) (*eventsv1alpha1.APIResponse, error) {
	iNamespaces, err := t.listIntersectedNamespaces(user,
		stringutils.Split(queryParam.WorkspaceFilter, ","),
		stringutils.Split(queryParam.WorkspaceSearch, ","),
		stringutils.Split(queryParam.InvolvedObjectNamespaceFilter, ","),
		stringutils.Split(queryParam.InvolvedObjectNamespaceSearch, ","))
	if err != nil {
		klog.Error(err)
		return nil, err
	}

	namespaceCreateTimeMap := make(map[string]time.Time)

	for _, ns := range iNamespaces {
		listEvts := authorizer.AttributesRecord{
			User:            user,
			Verb:            "list",
			APIGroup:        "",
			APIVersion:      "v1",
			Namespace:       ns.Name,
			Resource:        "events",
			ResourceRequest: true,
		}
		decision, _, err := t.authorizer.Authorize(listEvts)
		if err != nil {
			klog.Error(err)
			return nil, err
		}
		if decision == authorizer.DecisionAllow {
			namespaceCreateTimeMap[ns.Name] = ns.CreationTimestamp.Time
		}
	}
	// If there are no ns and ws query conditions,
	// those events with empty `involvedObject.namespace` will also be listed when user can list all events
	if len(queryParam.WorkspaceFilter) == 0 && len(queryParam.InvolvedObjectNamespaceFilter) == 0 &&
		len(queryParam.WorkspaceSearch) == 0 && len(queryParam.InvolvedObjectNamespaceSearch) == 0 {
		listEvts := authorizer.AttributesRecord{
			User:            user,
			Verb:            "list",
			APIGroup:        "",
			APIVersion:      "v1",
			Resource:        "events",
			ResourceRequest: true,
		}
		decision, _, err := t.authorizer.Authorize(listEvts)
		if err != nil {
			klog.Error(err)
			return nil, err
		}
		if decision == authorizer.DecisionAllow {
			namespaceCreateTimeMap[""] = time.Time{}
		}
	}

	return t.events.Events(queryParam, func(filter *eventsclient.Filter) {
		filter.InvolvedObjectNamespaceMap = namespaceCreateTimeMap
	})
}

H
hongming 已提交
410 411 412 413 414
func contains(objects []runtime.Object, object runtime.Object) bool {
	for _, item := range objects {
		if item == object {
			return true
		}
H
update  
hongming 已提交
415
	}
H
hongming 已提交
416
	return false
H
hongming 已提交
417
}
J
junotx 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

func stringSet(strs []string) map[string]struct{} {
	m := make(map[string]struct{})
	for _, str := range strs {
		m[str] = struct{}{}
	}
	return m
}

func stringContains(str string, subStrs []string) bool {
	for _, sub := range subStrs {
		if strings.Contains(str, sub) {
			return true
		}
	}
	return false
}