-
Notifications
You must be signed in to change notification settings - Fork 88
/
role.go
96 lines (85 loc) · 2.39 KB
/
role.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//
// Copyright (c) 2012-2019 Red Hat, Inc.
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//
// Contributors:
// Red Hat, Inc. - initial API and implementation
//
package deploy
import (
"context"
"github.com/sirupsen/logrus"
rbac "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
runtimeClient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
func SyncRoleToCluster(
deployContext *DeployContext,
name string,
resources []string,
verbs []string) (*rbac.Role, error) {
specRole, err := getSpecRole(deployContext, name, resources, verbs)
if err != nil {
return nil, err
}
clusterRole, err := getClusterRole(specRole.Name, specRole.Namespace, deployContext.ClusterAPI.Client)
if err != nil {
return nil, err
}
if clusterRole == nil {
logrus.Infof("Creating a new object: %s, name %s", specRole.Kind, specRole.Name)
err := deployContext.ClusterAPI.Client.Create(context.TODO(), specRole)
return nil, err
}
return clusterRole, nil
}
func getClusterRole(name string, namespace string, client runtimeClient.Client) (*rbac.Role, error) {
role := &rbac.Role{}
namespacedName := types.NamespacedName{
Namespace: namespace,
Name: name,
}
err := client.Get(context.TODO(), namespacedName, role)
if err != nil {
if errors.IsNotFound(err) {
return nil, nil
}
return nil, err
}
return role, nil
}
func getSpecRole(deployContext *DeployContext, name string, resources []string, verbs []string) (*rbac.Role, error) {
labels := GetLabels(deployContext.CheCluster, DefaultCheFlavor(deployContext.CheCluster))
role := &rbac.Role{
TypeMeta: metav1.TypeMeta{
Kind: "Role",
APIVersion: rbac.SchemeGroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: deployContext.CheCluster.Namespace,
Labels: labels,
},
Rules: []rbac.PolicyRule{
{
APIGroups: []string{
"",
},
Resources: resources,
Verbs: verbs,
},
},
}
err := controllerutil.SetControllerReference(deployContext.CheCluster, role, deployContext.ClusterAPI.Scheme)
if err != nil {
return nil, err
}
return role, nil
}