-
Notifications
You must be signed in to change notification settings - Fork 0
/
systemaccount.go
93 lines (79 loc) · 2.2 KB
/
systemaccount.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
package systemaccount
import (
"fmt"
"github.com/rancher/rancher/pkg/randomtoken"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/types/config"
"github.com/rancher/types/user"
errors2 "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
clusterOwnerRole = "cluster-owner"
)
func NewManager(management *config.ManagementContext) *Manager {
return &Manager{
userManager: management.UserManager,
crtbs: management.Management.ClusterRoleTemplateBindings(""),
crts: management.Management.ClusterRegistrationTokens(""),
}
}
type Manager struct {
userManager user.Manager
crtbs v3.ClusterRoleTemplateBindingInterface
crts v3.ClusterRegistrationTokenInterface
}
func (s *Manager) CreateSystemAccount(cluster *v3.Cluster) error {
user, err := s.GetSystemUser(cluster)
if err != nil {
return err
}
bindingName := user.Name + "-admin"
_, err = s.crtbs.GetNamespaced(cluster.Name, bindingName, v1.GetOptions{})
if err == nil {
return nil
}
_, err = s.crtbs.Create(&v3.ClusterRoleTemplateBinding{
ObjectMeta: v1.ObjectMeta{
Name: bindingName,
Namespace: cluster.Name,
},
ClusterName: cluster.Name,
UserName: user.Name,
RoleTemplateName: clusterOwnerRole,
})
return err
}
func (s *Manager) GetSystemUser(cluster *v3.Cluster) (*v3.User, error) {
return s.userManager.EnsureUser(fmt.Sprintf("system://%s", cluster.Name), "System account for Cluster "+cluster.Name)
}
func (s *Manager) GetOrCreateSystemClusterToken(clusterName string) (string, error) {
token := ""
crt, err := s.crts.GetNamespaced(clusterName, "system", v1.GetOptions{})
if errors2.IsNotFound(err) {
token, err = randomtoken.Generate()
if err != nil {
return "", err
}
crt = &v3.ClusterRegistrationToken{
ObjectMeta: v1.ObjectMeta{
Name: "system",
Namespace: clusterName,
},
Spec: v3.ClusterRegistrationTokenSpec{
ClusterName: clusterName,
},
Status: v3.ClusterRegistrationTokenStatus{
Token: token,
},
}
if _, err := s.crts.Create(crt); err != nil {
return "", err
}
} else if err != nil {
return "", err
} else {
token = crt.Status.Token
}
return token, nil
}