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

H
hongming 已提交
58
type Interface interface {
H
hongming 已提交
59 60
	ListWorkspaces(user user.Info, query *query.Query) (*api.ListResult, error)
	ListNamespaces(user user.Info, workspace string, query *query.Query) (*api.ListResult, error)
H
hongming 已提交
61 62 63 64 65 66
	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 已提交
67
	Events(user user.Info, queryParam *eventsv1alpha1.Query) (*eventsv1alpha1.APIResponse, error)
H
huanggze 已提交
68 69
	QueryLogs(user user.Info, query *loggingv1alpha2.Query) (*loggingv1alpha2.APIResponse, error)
	ExportLogs(user user.Info, query *loggingv1alpha2.Query, writer io.Writer) error
R
root 已提交
70
	Auditing(user user.Info, queryParam *auditingv1alpha1.Query) (*auditingv1alpha1.APIResponse, error)
H
hongming 已提交
71 72 73 74 75
	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)
	PatchWorkspace(workspace *tenantv1alpha2.WorkspaceTemplate) (*tenantv1alpha2.WorkspaceTemplate, error)
76
	ListClusters(info user.Info) (*api.ListResult, error)
H
hongming 已提交
77
}
H
hongming 已提交
78

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

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

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

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

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

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

H
hongming 已提交
123
	if decision == authorizer.DecisionAllow {
H
update  
hongming 已提交
124

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

H
update  
hongming 已提交
127 128 129 130
		if err != nil {
			klog.Error(err)
			return nil, err
		}
H
hongming 已提交
131

H
hongming 已提交
132 133 134 135 136 137 138 139 140
		return result, nil
	}

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

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

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

H
hongming 已提交
144
	for _, roleBinding := range workspaceRoleBindings {
H
hongming 已提交
145

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

H
hongming 已提交
149
		if errors.IsNotFound(err) {
H
hongming 已提交
150
			klog.Warningf("workspace role binding: %+v found but workspace not exist", roleBinding.ObjectMeta.String())
H
hongming 已提交
151 152 153 154 155 156 157 158 159 160
			continue
		}

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

		if !contains(workspaces, workspace) {
			workspaces = append(workspaces, workspace)
H
update  
hongming 已提交
161
		}
H
hongming 已提交
162
	}
H
hongming 已提交
163

H
hongming 已提交
164
	result := resources.DefaultList(workspaces, queryParam, func(left runtime.Object, right runtime.Object, field query.Field) bool {
H
hongming 已提交
165
		return resources.DefaultObjectMetaCompare(left.(*tenantv1alpha2.WorkspaceTemplate).ObjectMeta, right.(*tenantv1alpha2.WorkspaceTemplate).ObjectMeta, field)
H
hongming 已提交
166
	}, func(workspace runtime.Object, filter query.Filter) bool {
H
hongming 已提交
167
		return resources.DefaultObjectMetaFilter(workspace.(*tenantv1alpha2.WorkspaceTemplate).ObjectMeta, filter)
H
hongming 已提交
168 169 170
	})

	return result, nil
H
hongming 已提交
171 172
}

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

	listNSInWS := authorizer.AttributesRecord{
H
hongming 已提交
176 177 178 179 180
		User:            user,
		Verb:            "list",
		Workspace:       workspace,
		Resource:        "namespaces",
		ResourceRequest: true,
H
hongming 已提交
181
		ResourceScope:   request.WorkspaceScope,
H
hongming 已提交
182
	}
H
update  
hongming 已提交
183

H
hongming 已提交
184
	decision, _, err := t.authorizer.Authorize(listNSInWS)
H
hongming 已提交
185 186

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

H
hongming 已提交
191
	if decision == authorizer.DecisionAllow {
H
hongming 已提交
192

H
hongming 已提交
193 194 195
		if workspace != "" {
			queryParam.Filters[query.FieldLabel] = query.Value(fmt.Sprintf("%s=%s", tenantv1alpha1.WorkspaceLabel, workspace))
		}
H
hongming 已提交
196 197

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

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

H
hongming 已提交
204 205 206 207
		return result, nil
	}

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

H
hongming 已提交
209 210 211 212
	if err != nil {
		klog.Error(err)
		return nil, err
	}
H
hongming 已提交
213

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

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

H
hongming 已提交
219 220 221 222
		if err != nil {
			klog.Error(err)
			return nil, err
		}
H
update  
hongming 已提交
223

H
hongming 已提交
224
		// skip if not controlled by the specified workspace
H
hongming 已提交
225
		if ns := namespace.(*corev1.Namespace); workspace != "" && ns.Labels[tenantv1alpha1.WorkspaceLabel] != workspace {
H
hongming 已提交
226 227 228
			continue
		}

H
hongming 已提交
229 230
		if !contains(namespaces, namespace) {
			namespaces = append(namespaces, namespace)
H
update  
hongming 已提交
231
		}
H
hongming 已提交
232 233
	}

H
hongming 已提交
234 235 236 237 238 239
	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 已提交
240
		}
H
hongming 已提交
241 242
		return resources.DefaultObjectMetaFilter(namespace, filter)
	})
H
hongming 已提交
243

H
hongming 已提交
244
	return result, nil
H
update  
hongming 已提交
245 246
}

H
hongming 已提交
247 248
func (t *tenantOperator) CreateNamespace(workspace string, namespace *corev1.Namespace) (*corev1.Namespace, error) {
	_, err := t.resourceGetter.Get(tenantv1alpha1.ResourcePluralWorkspace, "", workspace)
H
hongming 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262
	if err != nil {
		return nil, err
	}
	namespace = appendWorkspaceLabel(namespace, workspace)
	return t.k8sclient.CoreV1().Namespaces().Create(namespace)
}

func appendWorkspaceLabel(namespace *corev1.Namespace, workspace string) *corev1.Namespace {
	if namespace.Labels == nil {
		namespace.Labels = make(map[string]string, 0)
	}
	namespace.Labels[tenantv1alpha1.WorkspaceLabel] = workspace
	return namespace
}
H
hongming 已提交
263

H
hongming 已提交
264 265
func (t *tenantOperator) DescribeNamespace(workspace, namespace string) (*corev1.Namespace, error) {
	obj, err := t.resourceGetter.Get("namespaces", "", namespace)
H
hongming 已提交
266 267 268
	if err != nil {
		return nil, err
	}
H
hongming 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
	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 已提交
285

H
hongming 已提交
286
func (t *tenantOperator) UpdateNamespace(workspace string, namespace *corev1.Namespace) (*corev1.Namespace, error) {
H
hongming 已提交
287
	_, err := t.DescribeNamespace(workspace, namespace.Name)
H
hongming 已提交
288 289
	if err != nil {
		return nil, err
H
hongming 已提交
290
	}
H
hongming 已提交
291 292 293
	namespace = appendWorkspaceLabel(namespace, workspace)
	return t.k8sclient.CoreV1().Namespaces().Update(namespace)
}
H
hongming 已提交
294

H
hongming 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308
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 已提交
309

H
hongming 已提交
310 311 312 313 314 315 316 317 318 319
func (t *tenantOperator) PatchWorkspace(workspace *tenantv1alpha2.WorkspaceTemplate) (*tenantv1alpha2.WorkspaceTemplate, error) {
	_, err := t.DescribeWorkspace(workspace.Name)
	if err != nil {
		return nil, err
	}
	data, err := json.Marshal(workspace)
	if err != nil {
		return nil, err
	}
	return t.ksclient.TenantV1alpha2().WorkspaceTemplates().Patch(workspace.Name, types.MergePatchType, data)
H
hongming 已提交
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
}

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)
H
hongming 已提交
345 346
	for _, cluster := range workspace.Spec.Placement.Clusters {
		obj, err := t.resourceGetter.Get(clusterv1alpha1.ResourcesPluralCluster, "", cluster.Name)
H
hongming 已提交
347 348 349 350 351 352 353 354 355 356 357 358
		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
}
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 410 411 412 413 414 415 416 417
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
	}

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

	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 已提交
418
		for _, grantedCluster := range workspace.Spec.Placement.Clusters {
419
			// skip if cluster exist
H
hongming 已提交
420
			if clusters[grantedCluster.Name] != nil {
421 422
				continue
			}
H
hongming 已提交
423
			obj, err := t.resourceGetter.Get(clusterv1alpha1.ResourcesPluralCluster, "", grantedCluster.Name)
424 425 426 427 428 429 430 431
			if err != nil {
				klog.Error(err)
				if errors.IsNotFound(err) {
					continue
				}
				return nil, err
			}
			cluster := obj.(*clusterv1alpha1.Cluster)
H
hongming 已提交
432
			clusters[cluster.Name] = cluster
433 434 435 436 437 438 439 440 441 442
		}
	}

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

	return &api.ListResult{Items: items, TotalItems: len(items)}, nil
}
H
hongming 已提交
443 444 445 446 447

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

J
junotx 已提交
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
// 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
	)

J
junotx 已提交
463
	includeNsWithoutWs := len(workspaceSet) == 0 && len(workspaceSubstrs) == 0
J
junotx 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

	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
huanggze 已提交
560 561 562 563 564 565 566 567 568 569 570 571 572 573 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 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
func (t *tenantOperator) QueryLogs(user user.Info, query *loggingv1alpha2.Query) (*loggingv1alpha2.APIResponse, error) {
	iNamespaces, err := t.listIntersectedNamespaces(user,
		stringutils.Split(query.WorkspaceFilter, ","),
		stringutils.Split(query.WorkspaceSearch, ","),
		stringutils.Split(query.NamespaceFilter, ","),
		stringutils.Split(query.NamespaceSearch, ","))
	if err != nil {
		klog.Error(err)
		return nil, err
	}

	namespaceCreateTimeMap := make(map[string]time.Time)
	for _, ns := range iNamespaces {
		podLogs := authorizer.AttributesRecord{
			User:            user,
			Verb:            "get",
			APIGroup:        "",
			APIVersion:      "v1",
			Namespace:       ns.Name,
			Resource:        "pods",
			Subresource:     "log",
			ResourceRequest: true,
		}
		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
		}
	}

	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
	switch query.Operation {
	case loggingv1alpha2.OperationStatistics:
		if len(namespaceCreateTimeMap) == 0 {
			ar.Statistics = &loggingclient.Statistics{}
		} else {
			ar, err = t.lo.GetCurrentStats(sf)
		}
	case loggingv1alpha2.OperationHistogram:
		if len(namespaceCreateTimeMap) == 0 {
			ar.Histogram = &loggingclient.Histogram{}
		} else {
			ar, err = t.lo.CountLogsByInterval(sf, query.Interval)
		}
	default:
		if len(namespaceCreateTimeMap) == 0 {
			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 {
	iNamespaces, err := t.listIntersectedNamespaces(user,
		stringutils.Split(query.WorkspaceFilter, ","),
		stringutils.Split(query.WorkspaceSearch, ","),
		stringutils.Split(query.NamespaceFilter, ","),
		stringutils.Split(query.NamespaceSearch, ","))
	if err != nil {
		klog.Error(err)
		return err
	}

	namespaceCreateTimeMap := make(map[string]time.Time)
	for _, ns := range iNamespaces {
		podLogs := authorizer.AttributesRecord{
			User:            user,
			Verb:            "get",
			APIGroup:        "",
			APIVersion:      "v1",
			Namespace:       ns.Name,
			Resource:        "pods",
			Subresource:     "log",
			ResourceRequest: true,
		}
		decision, _, err := t.authorizer.Authorize(podLogs)
		if err != nil {
			klog.Error(err)
			return err
		}
		if decision == authorizer.DecisionAllow {
			namespaceCreateTimeMap[ns.Name] = ns.CreationTimestamp.Time
		}
	}

	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,
	}

	if len(namespaceCreateTimeMap) == 0 {
		return nil
	} else {
		return t.lo.ExportLogs(sf, writer)
	}
}

R
root 已提交
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
func (t *tenantOperator) Auditing(user user.Info, queryParam *auditingv1alpha1.Query) (*auditingv1alpha1.APIResponse, error) {
	iNamespaces, err := t.listIntersectedNamespaces(user,
		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
	}

	namespaceCreateTimeMap := make(map[string]time.Time)
	for _, ns := range iNamespaces {
		namespaceCreateTimeMap[ns.Name] = ns.CreationTimestamp.Time
	}
	// If there are no ns and ws query conditions,
	// those events with empty `ObjectRef.Namespace` will also be listed when user can list all namespaces
	if len(queryParam.WorkspaceFilter) == 0 && len(queryParam.ObjectRefNamespaceFilter) == 0 &&
		len(queryParam.WorkspaceSearch) == 0 && len(queryParam.ObjectRefNamespaceSearch) == 0 {
		listEvts := authorizer.AttributesRecord{
			User:            user,
			Verb:            "list",
			APIGroup:        "",
			APIVersion:      "v1",
			Resource:        "namespaces",
			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.auditing.Events(queryParam, func(filter *auditingclient.Filter) {
		filter.ObjectRefNamespaceMap = namespaceCreateTimeMap
	})
}

H
hongming 已提交
725 726 727 728 729
func contains(objects []runtime.Object, object runtime.Object) bool {
	for _, item := range objects {
		if item == object {
			return true
		}
H
update  
hongming 已提交
730
	}
H
hongming 已提交
731
	return false
H
hongming 已提交
732
}
J
junotx 已提交
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

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
}