tenant.go 32.8 KB
Newer Older
H
hongming 已提交
1
/*
H
hongming 已提交
2
Copyright 2019 The KubeSphere Authors.
H
hongming 已提交
3

H
hongming 已提交
4 5 6
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
H
hongming 已提交
7

H
hongming 已提交
8
    http://www.apache.org/licenses/LICENSE-2.0
H
hongming 已提交
9

H
hongming 已提交
10 11 12 13 14
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 已提交
15
*/
H
hongming 已提交
16

H
hongming 已提交
17 18 19
package tenant

import (
H
hongming 已提交
20
	"encoding/json"
H
hongming 已提交
21
	"fmt"
H
huanggze 已提交
22
	"io"
23 24 25
	"strings"
	"time"

H
update  
hongming 已提交
26 27
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
H
hongming 已提交
28
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
29
	"k8s.io/apimachinery/pkg/labels"
H
hongming 已提交
30
	"k8s.io/apimachinery/pkg/runtime"
H
hongming 已提交
31
	"k8s.io/apimachinery/pkg/types"
H
hongming 已提交
32
	"k8s.io/apiserver/pkg/authentication/user"
H
hongming 已提交
33
	"k8s.io/client-go/kubernetes"
H
update  
hongming 已提交
34 35
	"k8s.io/klog"
	"kubesphere.io/kubesphere/pkg/api"
R
root 已提交
36
	auditingv1alpha1 "kubesphere.io/kubesphere/pkg/api/auditing/v1alpha1"
J
junotx 已提交
37
	eventsv1alpha1 "kubesphere.io/kubesphere/pkg/api/events/v1alpha1"
H
huanggze 已提交
38
	loggingv1alpha2 "kubesphere.io/kubesphere/pkg/api/logging/v1alpha2"
H
hongming 已提交
39
	clusterv1alpha1 "kubesphere.io/kubesphere/pkg/apis/cluster/v1alpha1"
H
update  
hongming 已提交
40
	tenantv1alpha1 "kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
H
hongming 已提交
41
	tenantv1alpha2 "kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha2"
H
hongming 已提交
42
	typesv1beta1 "kubesphere.io/kubesphere/pkg/apis/types/v1beta1"
H
hongming 已提交
43
	"kubesphere.io/kubesphere/pkg/apiserver/authorization/authorizer"
H
hongming 已提交
44
	"kubesphere.io/kubesphere/pkg/apiserver/query"
H
hongming 已提交
45
	"kubesphere.io/kubesphere/pkg/apiserver/request"
H
hongming 已提交
46
	kubesphere "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
H
update  
hongming 已提交
47
	"kubesphere.io/kubesphere/pkg/informers"
R
root 已提交
48
	"kubesphere.io/kubesphere/pkg/models/auditing"
J
junotx 已提交
49
	"kubesphere.io/kubesphere/pkg/models/events"
H
update  
hongming 已提交
50
	"kubesphere.io/kubesphere/pkg/models/iam/am"
H
huanggze 已提交
51
	"kubesphere.io/kubesphere/pkg/models/logging"
H
hongming 已提交
52 53
	resources "kubesphere.io/kubesphere/pkg/models/resources/v1alpha3"
	resourcesv1alpha3 "kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/resource"
R
root 已提交
54
	auditingclient "kubesphere.io/kubesphere/pkg/simple/client/auditing"
J
junotx 已提交
55
	eventsclient "kubesphere.io/kubesphere/pkg/simple/client/events"
H
huanggze 已提交
56
	loggingclient "kubesphere.io/kubesphere/pkg/simple/client/logging"
J
junotx 已提交
57
	"kubesphere.io/kubesphere/pkg/utils/stringutils"
H
hongming 已提交
58 59
)

H
hongming 已提交
60
type Interface interface {
H
hongming 已提交
61 62
	ListWorkspaces(user user.Info, query *query.Query) (*api.ListResult, error)
	ListNamespaces(user user.Info, workspace string, query *query.Query) (*api.ListResult, error)
H
hongming 已提交
63
	ListDevOpsProjects(user user.Info, workspace string, query *query.Query) (*api.ListResult, error)
H
hongming 已提交
64
	ListFederatedNamespaces(info user.Info, workspace string, param *query.Query) (*api.ListResult, error)
H
hongming 已提交
65 66 67 68 69 70
	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 已提交
71
	Events(user user.Info, queryParam *eventsv1alpha1.Query) (*eventsv1alpha1.APIResponse, error)
H
huanggze 已提交
72 73
	QueryLogs(user user.Info, query *loggingv1alpha2.Query) (*loggingv1alpha2.APIResponse, error)
	ExportLogs(user user.Info, query *loggingv1alpha2.Query, writer io.Writer) error
R
root 已提交
74
	Auditing(user user.Info, queryParam *auditingv1alpha1.Query) (*auditingv1alpha1.APIResponse, error)
H
hongming 已提交
75 76 77 78
	DescribeNamespace(workspace, namespace string) (*corev1.Namespace, error)
	DeleteNamespace(workspace, namespace string) error
	UpdateNamespace(workspace string, namespace *corev1.Namespace) (*corev1.Namespace, error)
	PatchNamespace(workspace string, namespace *corev1.Namespace) (*corev1.Namespace, error)
79
	PatchWorkspace(workspace string, data json.RawMessage) (*tenantv1alpha2.WorkspaceTemplate, error)
80
	ListClusters(info user.Info) (*api.ListResult, error)
H
hongming 已提交
81
}
H
hongming 已提交
82

H
hongming 已提交
83
type tenantOperator struct {
H
hongming 已提交
84 85
	am             am.AccessManagementInterface
	authorizer     authorizer.Authorizer
H
hongming 已提交
86 87
	k8sclient      kubernetes.Interface
	ksclient       kubesphere.Interface
H
hongming 已提交
88
	resourceGetter *resourcesv1alpha3.ResourceGetter
J
junotx 已提交
89
	events         events.Interface
H
huanggze 已提交
90
	lo             logging.LoggingOperator
R
root 已提交
91
	auditing       auditing.Interface
H
hongming 已提交
92 93
}

H
hongming 已提交
94
func New(informers informers.InformerFactory, k8sclient kubernetes.Interface, ksclient kubesphere.Interface, evtsClient eventsclient.Client, loggingClient loggingclient.Interface, auditingclient auditingclient.Client, am am.AccessManagementInterface, authorizer authorizer.Authorizer) Interface {
H
update  
hongming 已提交
95
	return &tenantOperator{
H
hongming 已提交
96
		am:             am,
H
hongming 已提交
97
		authorizer:     authorizer,
H
hongming 已提交
98
		resourceGetter: resourcesv1alpha3.NewResourceGetter(informers),
H
hongming 已提交
99 100
		k8sclient:      k8sclient,
		ksclient:       ksclient,
J
junotx 已提交
101
		events:         events.NewEventsOperator(evtsClient),
H
huanggze 已提交
102
		lo:             logging.NewLoggingOperator(loggingClient),
R
root 已提交
103
		auditing:       auditing.NewEventsOperator(auditingclient),
H
update  
hongming 已提交
104
	}
H
hongming 已提交
105 106
}

H
hongming 已提交
107
func (t *tenantOperator) ListWorkspaces(user user.Info, queryParam *query.Query) (*api.ListResult, error) {
H
hongming 已提交
108 109

	listWS := authorizer.AttributesRecord{
H
hongming 已提交
110 111
		User:            user,
		Verb:            "list",
H
hongming 已提交
112
		APIGroup:        "*",
H
hongming 已提交
113 114
		Resource:        "workspaces",
		ResourceRequest: true,
H
hongming 已提交
115
		ResourceScope:   request.GlobalScope,
H
hongming 已提交
116 117 118
	}

	decision, _, err := t.authorizer.Authorize(listWS)
H
update  
hongming 已提交
119 120 121 122
	if err != nil {
		klog.Error(err)
		return nil, err
	}
H
hongming 已提交
123

H
hongming 已提交
124
	// allowed to list all workspaces
H
hongming 已提交
125
	if decision == authorizer.DecisionAllow {
H
hongming 已提交
126
		result, err := t.resourceGetter.List(tenantv1alpha2.ResourcePluralWorkspaceTemplate, "", queryParam)
H
update  
hongming 已提交
127 128 129 130
		if err != nil {
			klog.Error(err)
			return nil, err
		}
H
hongming 已提交
131 132 133
		return result, nil
	}

H
hongming 已提交
134
	// retrieving associated resources through role binding
135
	workspaceRoleBindings, err := t.am.ListWorkspaceRoleBindings(user.GetName(), user.GetGroups(), "")
H
hongming 已提交
136 137 138 139
	if err != nil {
		klog.Error(err)
		return nil, err
	}
H
hongming 已提交
140

H
hongming 已提交
141 142 143
	workspaces := make([]runtime.Object, 0)
	for _, roleBinding := range workspaceRoleBindings {
		workspaceName := roleBinding.Labels[tenantv1alpha1.WorkspaceLabel]
H
hongming 已提交
144
		obj, err := t.resourceGetter.Get(tenantv1alpha2.ResourcePluralWorkspaceTemplate, "", workspaceName)
H
hongming 已提交
145
		if errors.IsNotFound(err) {
H
hongming 已提交
146
			klog.Warningf("workspace role binding: %+v found but workspace not exist", roleBinding.Name)
H
hongming 已提交
147 148 149 150 151 152
			continue
		}
		if err != nil {
			klog.Error(err)
			return nil, err
		}
H
hongming 已提交
153 154 155 156
		workspace := obj.(*tenantv1alpha2.WorkspaceTemplate)
		// label matching selector, remove duplicate entity
		if queryParam.Selector().Matches(labels.Set(workspace.Labels)) &&
			!contains(workspaces, workspace) {
H
hongming 已提交
157
			workspaces = append(workspaces, workspace)
H
update  
hongming 已提交
158
		}
H
hongming 已提交
159
	}
H
hongming 已提交
160

H
hongming 已提交
161
	// use default pagination search logic
H
hongming 已提交
162
	result := resources.DefaultList(workspaces, queryParam, func(left runtime.Object, right runtime.Object, field query.Field) bool {
H
hongming 已提交
163
		return resources.DefaultObjectMetaCompare(left.(*tenantv1alpha2.WorkspaceTemplate).ObjectMeta, right.(*tenantv1alpha2.WorkspaceTemplate).ObjectMeta, field)
H
hongming 已提交
164
	}, func(workspace runtime.Object, filter query.Filter) bool {
H
hongming 已提交
165
		return resources.DefaultObjectMetaFilter(workspace.(*tenantv1alpha2.WorkspaceTemplate).ObjectMeta, filter)
H
hongming 已提交
166 167 168
	})

	return result, nil
H
hongming 已提交
169 170
}

H
hongming 已提交
171
func (t *tenantOperator) ListFederatedNamespaces(user user.Info, workspace string, queryParam *query.Query) (*api.ListResult, error) {
H
hongming 已提交
172

H
hongming 已提交
173 174 175
	nsScope := request.ClusterScope
	if workspace != "" {
		nsScope = request.WorkspaceScope
H
hongming 已提交
176 177
		// filter by workspace
		queryParam.Filters[query.FieldLabel] = query.Value(fmt.Sprintf("%s=%s", tenantv1alpha1.WorkspaceLabel, workspace))
H
hongming 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
	}

	listNS := authorizer.AttributesRecord{
		User:            user,
		Verb:            "list",
		Workspace:       workspace,
		Resource:        "namespaces",
		ResourceRequest: true,
		ResourceScope:   nsScope,
	}

	decision, _, err := t.authorizer.Authorize(listNS)
	if err != nil {
		klog.Error(err)
		return nil, err
	}

H
hongming 已提交
195
	// allowed to list all namespaces in the specified scope
H
hongming 已提交
196
	if decision == authorizer.DecisionAllow {
Z
zryfish 已提交
197
		result, err := t.resourceGetter.List(typesv1beta1.ResourcePluralFederatedNamespace, "", queryParam)
H
hongming 已提交
198 199 200 201 202 203 204
		if err != nil {
			klog.Error(err)
			return nil, err
		}
		return result, nil
	}

H
hongming 已提交
205
	// retrieving associated resources through role binding
206
	roleBindings, err := t.am.ListRoleBindings(user.GetName(), user.GetGroups(), "")
H
hongming 已提交
207 208 209 210 211 212 213
	if err != nil {
		klog.Error(err)
		return nil, err
	}

	namespaces := make([]runtime.Object, 0)
	for _, roleBinding := range roleBindings {
H
hongming 已提交
214
		obj, err := t.resourceGetter.Get(typesv1beta1.ResourcePluralFederatedNamespace, roleBinding.Namespace, roleBinding.Namespace)
H
hongming 已提交
215
		if err != nil {
H
hongming 已提交
216 217 218
			if errors.IsNotFound(err) {
				continue
			}
H
hongming 已提交
219 220 221
			klog.Error(err)
			return nil, err
		}
H
hongming 已提交
222 223 224 225
		namespace := obj.(*typesv1beta1.FederatedNamespace)
		// label matching selector, remove duplicate entity
		if queryParam.Selector().Matches(labels.Set(namespace.Labels)) &&
			!contains(namespaces, namespace) {
H
hongming 已提交
226 227 228 229
			namespaces = append(namespaces, namespace)
		}
	}

H
hongming 已提交
230
	// use default pagination search logic
H
hongming 已提交
231
	result := resources.DefaultList(namespaces, queryParam, func(left runtime.Object, right runtime.Object, field query.Field) bool {
H
hongming 已提交
232
		return resources.DefaultObjectMetaCompare(left.(*typesv1beta1.FederatedNamespace).ObjectMeta, right.(*typesv1beta1.FederatedNamespace).ObjectMeta, field)
H
hongming 已提交
233
	}, func(object runtime.Object, filter query.Filter) bool {
H
hongming 已提交
234
		return resources.DefaultObjectMetaFilter(object.(*typesv1beta1.FederatedNamespace).ObjectMeta, filter)
H
hongming 已提交
235
	})
H
hongming 已提交
236

H
hongming 已提交
237 238 239
	return result, nil
}

H
hongming 已提交
240
func (t *tenantOperator) ListNamespaces(user user.Info, workspace string, queryParam *query.Query) (*api.ListResult, error) {
241 242 243
	nsScope := request.ClusterScope
	if workspace != "" {
		nsScope = request.WorkspaceScope
H
hongming 已提交
244 245
		// filter by workspace
		queryParam.Filters[query.FieldLabel] = query.Value(fmt.Sprintf("%s=%s", tenantv1alpha1.WorkspaceLabel, workspace))
246
	}
H
hongming 已提交
247

248
	listNS := authorizer.AttributesRecord{
H
hongming 已提交
249 250 251 252 253
		User:            user,
		Verb:            "list",
		Workspace:       workspace,
		Resource:        "namespaces",
		ResourceRequest: true,
254
		ResourceScope:   nsScope,
H
hongming 已提交
255
	}
H
update  
hongming 已提交
256

257
	decision, _, err := t.authorizer.Authorize(listNS)
H
hongming 已提交
258
	if err != nil {
H
update  
hongming 已提交
259
		klog.Error(err)
H
hongming 已提交
260 261 262
		return nil, err
	}

H
hongming 已提交
263
	// allowed to list all namespaces in the specified scope
H
hongming 已提交
264
	if decision == authorizer.DecisionAllow {
H
hongming 已提交
265
		result, err := t.resourceGetter.List("namespaces", "", queryParam)
H
update  
hongming 已提交
266 267 268 269
		if err != nil {
			klog.Error(err)
			return nil, err
		}
H
hongming 已提交
270 271 272
		return result, nil
	}

H
hongming 已提交
273
	// retrieving associated resources through role binding
274
	roleBindings, err := t.am.ListRoleBindings(user.GetName(), user.GetGroups(), "")
H
hongming 已提交
275 276 277 278
	if err != nil {
		klog.Error(err)
		return nil, err
	}
H
hongming 已提交
279

H
hongming 已提交
280 281
	namespaces := make([]runtime.Object, 0)
	for _, roleBinding := range roleBindings {
H
hongming 已提交
282
		obj, err := t.resourceGetter.Get("namespaces", "", roleBinding.Namespace)
H
hongming 已提交
283 284 285 286
		if err != nil {
			klog.Error(err)
			return nil, err
		}
H
hongming 已提交
287 288 289 290
		namespace := obj.(*corev1.Namespace)
		// label matching selector, remove duplicate entity
		if queryParam.Selector().Matches(labels.Set(namespace.Labels)) &&
			!contains(namespaces, namespace) {
H
hongming 已提交
291
			namespaces = append(namespaces, namespace)
H
update  
hongming 已提交
292
		}
H
hongming 已提交
293 294
	}

H
hongming 已提交
295
	// use default pagination search logic
H
hongming 已提交
296 297 298
	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 {
H
hongming 已提交
299
		return resources.DefaultObjectMetaFilter(object.(*corev1.Namespace).ObjectMeta, filter)
H
hongming 已提交
300
	})
H
hongming 已提交
301

H
hongming 已提交
302
	return result, nil
H
update  
hongming 已提交
303 304
}

305 306 307
// CreateNamespace adds a workspace label to namespace which indicates namespace is under the workspace
// The reason here why don't check the existence of workspace anymore is this function is only executed in host cluster.
// but if the host cluster is not authorized to workspace, there will be no workspace in host cluster.
H
hongming 已提交
308
func (t *tenantOperator) CreateNamespace(workspace string, namespace *corev1.Namespace) (*corev1.Namespace, error) {
309
	return t.k8sclient.CoreV1().Namespaces().Create(labelNamespaceWithWorkspaceName(namespace, workspace))
H
hongming 已提交
310 311
}

312 313 314
// labelNamespaceWithWorkspaceName adds a kubesphere.io/workspace=[workspaceName] label to namespace which
// indicates namespace is under the workspace
func labelNamespaceWithWorkspaceName(namespace *corev1.Namespace, workspaceName string) *corev1.Namespace {
H
hongming 已提交
315 316 317
	if namespace.Labels == nil {
		namespace.Labels = make(map[string]string, 0)
	}
318 319 320

	namespace.Labels[tenantv1alpha1.WorkspaceLabel] = workspaceName // label namespace with workspace name

H
hongming 已提交
321 322
	return namespace
}
H
hongming 已提交
323

H
hongming 已提交
324 325
func (t *tenantOperator) DescribeNamespace(workspace, namespace string) (*corev1.Namespace, error) {
	obj, err := t.resourceGetter.Get("namespaces", "", namespace)
H
hongming 已提交
326 327 328
	if err != nil {
		return nil, err
	}
H
hongming 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
	ns := obj.(*corev1.Namespace)
	if ns.Labels[tenantv1alpha1.WorkspaceLabel] != workspace {
		err := errors.NewNotFound(corev1.Resource("namespace"), namespace)
		klog.Error(err)
		return nil, err
	}
	return ns, nil
}

func (t *tenantOperator) DeleteNamespace(workspace, namespace string) error {
	_, err := t.DescribeNamespace(workspace, namespace)
	if err != nil {
		return err
	}
	return t.k8sclient.CoreV1().Namespaces().Delete(namespace, metav1.NewDeleteOptions(0))
}
H
hongming 已提交
345

H
hongming 已提交
346
func (t *tenantOperator) UpdateNamespace(workspace string, namespace *corev1.Namespace) (*corev1.Namespace, error) {
H
hongming 已提交
347
	_, err := t.DescribeNamespace(workspace, namespace.Name)
H
hongming 已提交
348 349
	if err != nil {
		return nil, err
H
hongming 已提交
350
	}
351
	namespace = labelNamespaceWithWorkspaceName(namespace, workspace)
H
hongming 已提交
352 353
	return t.k8sclient.CoreV1().Namespaces().Update(namespace)
}
H
hongming 已提交
354

H
hongming 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368
func (t *tenantOperator) PatchNamespace(workspace string, namespace *corev1.Namespace) (*corev1.Namespace, error) {
	_, err := t.DescribeNamespace(workspace, namespace.Name)
	if err != nil {
		return nil, err
	}
	if namespace.Labels != nil {
		namespace.Labels[tenantv1alpha1.WorkspaceLabel] = workspace
	}
	data, err := json.Marshal(namespace)
	if err != nil {
		return nil, err
	}
	return t.k8sclient.CoreV1().Namespaces().Patch(namespace.Name, types.MergePatchType, data)
}
H
hongming 已提交
369

370 371
func (t *tenantOperator) PatchWorkspace(workspace string, data json.RawMessage) (*tenantv1alpha2.WorkspaceTemplate, error) {
	return t.ksclient.TenantV1alpha2().WorkspaceTemplates().Patch(workspace, types.MergePatchType, data)
H
hongming 已提交
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
}

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
	}
396 397 398 399 400 401 402 403 404 405 406 407

	// In this case, spec.placement.clusterSelector will be ignored, since spec.placement.clusters is provided.
	if workspace.Spec.Placement.Clusters != nil {
		clusters := make([]interface{}, 0)
		for _, cluster := range workspace.Spec.Placement.Clusters {
			obj, err := t.resourceGetter.Get(clusterv1alpha1.ResourcesPluralCluster, "", cluster.Name)
			if err != nil {
				klog.Error(err)
				if errors.IsNotFound(err) {
					continue
				}
				return nil, err
H
hongming 已提交
408
			}
409
			clusters = append(clusters, obj)
H
hongming 已提交
410
		}
411
		return &api.ListResult{Items: clusters, TotalItems: len(clusters)}, nil
H
hongming 已提交
412
	}
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

	if workspace.Spec.Placement.ClusterSelector != nil {
		// In this case, the resource will be propagated to all member clusters.
		if workspace.Spec.Placement.ClusterSelector.MatchLabels == nil {
			return t.resourceGetter.List(clusterv1alpha1.ResourcesPluralCluster, "", query.New())
		} else {
			// In this case, the resource will only be propagated to member clusters that are labeled with foo: bar.
			return t.resourceGetter.List(clusterv1alpha1.ResourcesPluralCluster, "", &query.Query{
				Pagination:    query.NoPagination,
				Ascending:     false,
				LabelSelector: labels.SelectorFromSet(workspace.Spec.Placement.ClusterSelector.MatchLabels).String(),
			})
		}
	}

	// In this case, you can either set spec: {} as above or remove spec field from your placement policy. The resource will not be propagated to member clusters.
	return &api.ListResult{Items: []interface{}{}, TotalItems: 0}, nil
H
hongming 已提交
430
}
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
func (t *tenantOperator) ListClusters(user user.Info) (*api.ListResult, error) {

	listClustersInGlobalScope := authorizer.AttributesRecord{
		User:            user,
		Verb:            "list",
		Resource:        "clusters",
		ResourceScope:   request.GlobalScope,
		ResourceRequest: true,
	}

	allowedListClustersInGlobalScope, _, err := t.authorizer.Authorize(listClustersInGlobalScope)

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

	listWorkspacesInGlobalScope := authorizer.AttributesRecord{
		User:            user,
		Verb:            "list",
		Resource:        "workspaces",
		ResourceScope:   request.GlobalScope,
		ResourceRequest: true,
	}

	allowedListWorkspacesInGlobalScope, _, err := t.authorizer.Authorize(listWorkspacesInGlobalScope)

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

	if allowedListClustersInGlobalScope == authorizer.DecisionAllow ||
		allowedListWorkspacesInGlobalScope == authorizer.DecisionAllow {
		result, err := t.resourceGetter.List(clusterv1alpha1.ResourcesPluralCluster, "", query.New())
		if err != nil {
			klog.Error(err)
			return nil, err
		}
		return result, nil
	}

473
	workspaceRoleBindings, err := t.am.ListWorkspaceRoleBindings(user.GetName(), user.GetGroups(), "")
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

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

	clusters := map[string]*clusterv1alpha1.Cluster{}

	for _, roleBinding := range workspaceRoleBindings {
		workspaceName := roleBinding.Labels[tenantv1alpha1.WorkspaceLabel]
		workspace, err := t.DescribeWorkspace(workspaceName)
		if err != nil {
			klog.Error(err)
			return nil, err
		}

H
hongming 已提交
490
		for _, grantedCluster := range workspace.Spec.Placement.Clusters {
491
			// skip if cluster exist
H
hongming 已提交
492
			if clusters[grantedCluster.Name] != nil {
493 494
				continue
			}
H
hongming 已提交
495
			obj, err := t.resourceGetter.Get(clusterv1alpha1.ResourcesPluralCluster, "", grantedCluster.Name)
496 497 498 499 500 501 502 503
			if err != nil {
				klog.Error(err)
				if errors.IsNotFound(err) {
					continue
				}
				return nil, err
			}
			cluster := obj.(*clusterv1alpha1.Cluster)
H
hongming 已提交
504
			clusters[cluster.Name] = cluster
505 506 507 508 509 510 511 512 513 514
		}
	}

	items := make([]interface{}, 0)
	for _, cluster := range clusters {
		items = append(items, cluster)
	}

	return &api.ListResult{Items: items, TotalItems: len(items)}, nil
}
H
hongming 已提交
515 516 517 518 519

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

W
wanjunlei 已提交
520 521 522 523 524
// listIntersectedNamespaces returns a list of namespaces that MUST meet ALL the following filters:
// 1. If `workspaces` is not empty, the namespace SHOULD belong to one of the specified workpsaces.
// 2. If `workspaceSubstrs` is not empty, the namespace SHOULD belong to a workspace whose name contains one of the specified substrings.
// 3. If `namespaces` is not empty, the namespace SHOULD be one of the specified namespacs.
// 4. If `namespaceSubstrs` is not empty, the namespace's name SHOULD contain one of the specified substrings.
525
// 5. If ALL of the filters above are empty, returns all namespaces.
W
wanjunlei 已提交
526 527
func (t *tenantOperator) listIntersectedNamespaces(workspaces, workspaceSubstrs,
	namespaces, namespaceSubstrs []string) ([]*corev1.Namespace, error) {
J
junotx 已提交
528 529 530 531 532 533
	var (
		namespaceSet = stringSet(namespaces)
		workspaceSet = stringSet(workspaces)

		iNamespaces []*corev1.Namespace
	)
J
junotx 已提交
534
	includeNsWithoutWs := len(workspaceSet) == 0 && len(workspaceSubstrs) == 0
J
junotx 已提交
535

536
	result, err := t.resourceGetter.List("namespaces", "", query.New())
J
junotx 已提交
537 538 539
	if err != nil {
		return nil, err
	}
540 541 542 543 544 545
	for _, obj := range result.Items {
		ns, ok := obj.(*corev1.Namespace)
		if !ok {
			continue
		}

J
junotx 已提交
546
		if len(namespaceSet) > 0 {
547
			if _, ok := namespaceSet[ns.Name]; !ok {
J
junotx 已提交
548 549 550
				continue
			}
		}
551
		if len(namespaceSubstrs) > 0 && !stringContains(ns.Name, namespaceSubstrs) {
J
junotx 已提交
552 553
			continue
		}
554 555 556
		if ws := ns.Labels[tenantv1alpha1.WorkspaceLabel]; ws != "" {
			if len(workspaceSet) > 0 {
				if _, ok := workspaceSet[ws]; !ok {
J
junotx 已提交
557 558
					continue
				}
559 560
			}
			if len(workspaceSubstrs) > 0 && !stringContains(ws, workspaceSubstrs) {
J
junotx 已提交
561 562
				continue
			}
563 564
		} else if !includeNsWithoutWs {
			continue
J
junotx 已提交
565
		}
566
		iNamespaces = append(iNamespaces, ns)
J
junotx 已提交
567 568 569 570
	}
	return iNamespaces, nil
}

571 572
// listIntersectedWorkspaces returns a list of workspaces that MUST meet ALL the following filters:
// 1. If `workspaces` is not empty, the workspace SHOULD be one of the specified workpsaces.
W
wanjunlei 已提交
573
// 2. Else if `workspaceSubstrs` is not empty, the workspace SHOULD be contains one of the specified substrings.
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
// 3. Else, return all workspace in the cluster.
func (t *tenantOperator) listIntersectedWorkspaces(workspaces, workspaceSubstrs []string) ([]*tenantv1alpha1.Workspace, error) {
	var (
		workspaceSet = stringSet(workspaces)
		iWorkspaces  []*tenantv1alpha1.Workspace
	)

	result, err := t.resourceGetter.List("workspaces", "", query.New())
	if err != nil {
		return nil, err
	}
	for _, obj := range result.Items {
		ws, ok := obj.(*tenantv1alpha1.Workspace)
		if !ok {
			continue
		}

		if len(workspaceSet) > 0 {
			if _, ok := workspaceSet[ws.Name]; !ok {
				continue
			}
		}
		if len(workspaceSubstrs) > 0 && !stringContains(ws.Name, workspaceSubstrs) {
			continue
		}

		iWorkspaces = append(iWorkspaces, ws)
	}
	return iWorkspaces, nil
}

J
junotx 已提交
605
func (t *tenantOperator) Events(user user.Info, queryParam *eventsv1alpha1.Query) (*eventsv1alpha1.APIResponse, error) {
W
wanjunlei 已提交
606
	iNamespaces, err := t.listIntersectedNamespaces(
J
junotx 已提交
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
		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,
627
			ResourceScope:   request.NamespaceScope,
J
junotx 已提交
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
		}
		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,
649
			ResourceScope:   request.ClusterScope,
J
junotx 已提交
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
		}
		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
huanggze 已提交
666
func (t *tenantOperator) QueryLogs(user user.Info, query *loggingv1alpha2.Query) (*loggingv1alpha2.APIResponse, error) {
667
	iNamespaces, err := t.listIntersectedNamespaces(nil, nil,
H
huanggze 已提交
668 669 670 671 672 673 674
		stringutils.Split(query.NamespaceFilter, ","),
		stringutils.Split(query.NamespaceSearch, ","))
	if err != nil {
		klog.Error(err)
		return nil, err
	}

675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
	namespaceCreateTimeMap := make(map[string]*time.Time)

	var isGlobalAdmin bool

	// If it is a global admin, the user can view logs from any namespace.
	podLogs := authorizer.AttributesRecord{
		User:            user,
		Verb:            "get",
		APIGroup:        "",
		APIVersion:      "v1",
		Resource:        "pods",
		Subresource:     "log",
		ResourceRequest: true,
		ResourceScope:   request.ClusterScope,
	}
	decision, _, err := t.authorizer.Authorize(podLogs)
	if err != nil {
		klog.Error(err)
		return nil, err
	}
	if decision == authorizer.DecisionAllow {
		isGlobalAdmin = true
		if query.NamespaceFilter != "" || query.NamespaceSearch != "" {
			for _, ns := range iNamespaces {
				namespaceCreateTimeMap[ns.Name] = nil
			}
H
huanggze 已提交
701
		}
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
	}

	// If it is a regular user, this user can only view logs of namespaces the user belongs to.
	if !isGlobalAdmin {
		for _, ns := range iNamespaces {
			podLogs := authorizer.AttributesRecord{
				User:            user,
				Verb:            "get",
				APIGroup:        "",
				APIVersion:      "v1",
				Namespace:       ns.Name,
				Resource:        "pods",
				Subresource:     "log",
				ResourceRequest: true,
				ResourceScope:   request.NamespaceScope,
			}
			decision, _, err := t.authorizer.Authorize(podLogs)
			if err != nil {
				klog.Error(err)
				return nil, err
			}
			if decision == authorizer.DecisionAllow {
				namespaceCreateTimeMap[ns.Name] = &ns.CreationTimestamp.Time
			}
H
huanggze 已提交
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
		}
	}

	sf := loggingclient.SearchFilter{
		NamespaceFilter: namespaceCreateTimeMap,
		WorkloadSearch:  stringutils.Split(query.WorkloadSearch, ","),
		WorkloadFilter:  stringutils.Split(query.WorkloadFilter, ","),
		PodSearch:       stringutils.Split(query.PodSearch, ","),
		PodFilter:       stringutils.Split(query.PodFilter, ","),
		ContainerSearch: stringutils.Split(query.ContainerSearch, ","),
		ContainerFilter: stringutils.Split(query.ContainerFilter, ","),
		LogSearch:       stringutils.Split(query.LogSearch, ","),
		Starttime:       query.StartTime,
		Endtime:         query.EndTime,
	}

	var ar loggingv1alpha2.APIResponse
743 744 745
	noHit := !isGlobalAdmin && len(namespaceCreateTimeMap) == 0 ||
		isGlobalAdmin && len(namespaceCreateTimeMap) == 0 && (query.NamespaceFilter != "" || query.NamespaceSearch != "")

H
huanggze 已提交
746 747
	switch query.Operation {
	case loggingv1alpha2.OperationStatistics:
748
		if noHit {
H
huanggze 已提交
749 750 751 752 753
			ar.Statistics = &loggingclient.Statistics{}
		} else {
			ar, err = t.lo.GetCurrentStats(sf)
		}
	case loggingv1alpha2.OperationHistogram:
754
		if noHit {
H
huanggze 已提交
755 756 757 758 759
			ar.Histogram = &loggingclient.Histogram{}
		} else {
			ar, err = t.lo.CountLogsByInterval(sf, query.Interval)
		}
	default:
760
		if noHit {
H
huanggze 已提交
761 762 763 764 765 766 767 768 769
			ar.Logs = &loggingclient.Logs{}
		} else {
			ar, err = t.lo.SearchLogs(sf, query.From, query.Size, query.Sort)
		}
	}
	return &ar, err
}

func (t *tenantOperator) ExportLogs(user user.Info, query *loggingv1alpha2.Query, writer io.Writer) error {
770
	iNamespaces, err := t.listIntersectedNamespaces(nil, nil,
H
huanggze 已提交
771 772 773 774 775 776 777
		stringutils.Split(query.NamespaceFilter, ","),
		stringutils.Split(query.NamespaceSearch, ","))
	if err != nil {
		klog.Error(err)
		return err
	}

778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
	namespaceCreateTimeMap := make(map[string]*time.Time)

	var isGlobalAdmin bool

	// If it is a global admin, the user can view logs from any namespace.
	podLogs := authorizer.AttributesRecord{
		User:            user,
		Verb:            "get",
		APIGroup:        "",
		APIVersion:      "v1",
		Resource:        "pods",
		Subresource:     "log",
		ResourceRequest: true,
		ResourceScope:   request.ClusterScope,
	}
	decision, _, err := t.authorizer.Authorize(podLogs)
	if err != nil {
		klog.Error(err)
		return err
	}
	if decision == authorizer.DecisionAllow {
		isGlobalAdmin = true
		if query.NamespaceFilter != "" || query.NamespaceSearch != "" {
			for _, ns := range iNamespaces {
				namespaceCreateTimeMap[ns.Name] = nil
			}
H
huanggze 已提交
804
		}
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
	}

	// If it is a regular user, this user can only view logs of namespaces the user belongs to.
	if !isGlobalAdmin {
		for _, ns := range iNamespaces {
			podLogs := authorizer.AttributesRecord{
				User:            user,
				Verb:            "get",
				APIGroup:        "",
				APIVersion:      "v1",
				Namespace:       ns.Name,
				Resource:        "pods",
				Subresource:     "log",
				ResourceRequest: true,
				ResourceScope:   request.NamespaceScope,
			}
			decision, _, err := t.authorizer.Authorize(podLogs)
			if err != nil {
				klog.Error(err)
				return err
			}
			if decision == authorizer.DecisionAllow {
				namespaceCreateTimeMap[ns.Name] = &ns.CreationTimestamp.Time
			}
H
huanggze 已提交
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
		}
	}

	sf := loggingclient.SearchFilter{
		NamespaceFilter: namespaceCreateTimeMap,
		WorkloadSearch:  stringutils.Split(query.WorkloadSearch, ","),
		WorkloadFilter:  stringutils.Split(query.WorkloadFilter, ","),
		PodSearch:       stringutils.Split(query.PodSearch, ","),
		PodFilter:       stringutils.Split(query.PodFilter, ","),
		ContainerSearch: stringutils.Split(query.ContainerSearch, ","),
		ContainerFilter: stringutils.Split(query.ContainerFilter, ","),
		LogSearch:       stringutils.Split(query.LogSearch, ","),
		Starttime:       query.StartTime,
		Endtime:         query.EndTime,
	}

845 846 847 848
	noHit := !isGlobalAdmin && len(namespaceCreateTimeMap) == 0 ||
		isGlobalAdmin && len(namespaceCreateTimeMap) == 0 && (query.NamespaceFilter != "" || query.NamespaceSearch != "")

	if noHit {
H
huanggze 已提交
849 850 851 852 853 854
		return nil
	} else {
		return t.lo.ExportLogs(sf, writer)
	}
}

R
root 已提交
855
func (t *tenantOperator) Auditing(user user.Info, queryParam *auditingv1alpha1.Query) (*auditingv1alpha1.APIResponse, error) {
W
wanjunlei 已提交
856
	iNamespaces, err := t.listIntersectedNamespaces(
R
root 已提交
857 858 859 860 861 862 863 864 865
		stringutils.Split(queryParam.WorkspaceFilter, ","),
		stringutils.Split(queryParam.WorkspaceSearch, ","),
		stringutils.Split(queryParam.ObjectRefNamespaceFilter, ","),
		stringutils.Split(queryParam.ObjectRefNamespaceSearch, ","))
	if err != nil {
		klog.Error(err)
		return nil, err
	}

866 867 868 869 870 871 872 873
	iWorkspaces, err := t.listIntersectedWorkspaces(
		stringutils.Split(queryParam.WorkspaceFilter, ","),
		stringutils.Split(queryParam.WorkspaceSearch, ","))
	if err != nil {
		klog.Error(err)
		return nil, err
	}

R
root 已提交
874
	namespaceCreateTimeMap := make(map[string]time.Time)
875
	workspaceCreateTimeMap := make(map[string]time.Time)
876

W
wanjunlei 已提交
877
	// Now auditing and event have the same authorization mechanism, so we can determine whether the user
878
	// has permission to view the auditing log in ns by judging whether the user has the permission to view the event in ns.
R
root 已提交
879
	for _, ns := range iNamespaces {
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
		listEvts := authorizer.AttributesRecord{
			User:            user,
			Verb:            "list",
			APIGroup:        "",
			APIVersion:      "v1",
			Namespace:       ns.Name,
			Resource:        "events",
			ResourceRequest: true,
			ResourceScope:   request.NamespaceScope,
		}
		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
		}
R
root 已提交
898
	}
899

W
wanjunlei 已提交
900 901
	// Now auditing and event have the same authorization mechanism, so we can determine whether the user
	// has permission to view the auditing log in ws by judging whether the user has the permission to view the event in ws.
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
	for _, ws := range iWorkspaces {
		listEvts := authorizer.AttributesRecord{
			User:            user,
			Verb:            "list",
			APIGroup:        "",
			APIVersion:      "v1",
			Workspace:       ws.Name,
			Resource:        "events",
			ResourceRequest: true,
			ResourceScope:   request.WorkspaceScope,
		}
		decision, _, err := t.authorizer.Authorize(listEvts)
		if err != nil {
			klog.Error(err)
			return nil, err
		}
		if decision == authorizer.DecisionAllow {
			workspaceCreateTimeMap[ws.Name] = ws.CreationTimestamp.Time
		}
	}

R
root 已提交
923
	// If there are no ns and ws query conditions,
924
	// those events with empty `objectRef.namespace` will also be listed when user can list all events
R
root 已提交
925 926
	if len(queryParam.WorkspaceFilter) == 0 && len(queryParam.ObjectRefNamespaceFilter) == 0 &&
		len(queryParam.WorkspaceSearch) == 0 && len(queryParam.ObjectRefNamespaceSearch) == 0 {
927
		listEvts := authorizer.AttributesRecord{
R
root 已提交
928 929
			User:            user,
			Verb:            "list",
930 931 932
			APIGroup:        "",
			APIVersion:      "v1",
			Resource:        "events",
R
root 已提交
933
			ResourceRequest: true,
934
			ResourceScope:   request.ClusterScope,
R
root 已提交
935
		}
936
		decision, _, err := t.authorizer.Authorize(listEvts)
R
root 已提交
937 938 939 940 941 942
		if err != nil {
			klog.Error(err)
			return nil, err
		}
		if decision == authorizer.DecisionAllow {
			namespaceCreateTimeMap[""] = time.Time{}
943
			workspaceCreateTimeMap[""] = time.Time{}
R
root 已提交
944 945 946 947 948
		}
	}

	return t.auditing.Events(queryParam, func(filter *auditingclient.Filter) {
		filter.ObjectRefNamespaceMap = namespaceCreateTimeMap
949
		filter.WorkspaceMap = workspaceCreateTimeMap
R
root 已提交
950 951 952
	})
}

H
hongming 已提交
953 954 955 956 957
func contains(objects []runtime.Object, object runtime.Object) bool {
	for _, item := range objects {
		if item == object {
			return true
		}
H
update  
hongming 已提交
958
	}
H
hongming 已提交
959
	return false
H
hongming 已提交
960
}
J
junotx 已提交
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977

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
}