-
Notifications
You must be signed in to change notification settings - Fork 15
/
etcd_util.go
60 lines (48 loc) · 1.16 KB
/
etcd_util.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
package cke
import (
"context"
"crypto/rand"
"encoding/hex"
"github.com/cybozu-go/etcdutil"
clientv3 "go.etcd.io/etcd/client/v3"
)
const (
defaultEtcdPrefix = "/cke/"
)
// NewEtcdConfig creates Config with default prefix.
func NewEtcdConfig() *etcdutil.Config {
return etcdutil.NewConfig(defaultEtcdPrefix)
}
// AddUserRole create etcd user and role.
func AddUserRole(ctx context.Context, cli *clientv3.Client, name, prefix string) error {
r := make([]byte, 32)
_, err := rand.Read(r)
if err != nil {
return err
}
_, err = cli.UserAdd(ctx, name, hex.EncodeToString(r))
if err != nil {
return err
}
if prefix == "" {
return nil
}
_, err = cli.RoleAdd(ctx, name)
if err != nil {
return err
}
_, err = cli.RoleGrantPermission(ctx, name, prefix, clientv3.GetPrefixRangeEnd(prefix), clientv3.PermissionType(clientv3.PermReadWrite))
if err != nil {
return err
}
_, err = cli.UserGrantRole(ctx, name, name)
if err != nil {
return err
}
return nil
}
// GetUserRoles get roles of target user.
func GetUserRoles(ctx context.Context, cli *clientv3.Client, user string) ([]string, error) {
resp, err := cli.UserGet(ctx, user)
return resp.Roles, err
}