-
Notifications
You must be signed in to change notification settings - Fork 4
/
config.go
81 lines (69 loc) · 1.68 KB
/
config.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
package etcdpasswd
import (
"context"
"encoding/json"
clientv3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/client/v3/clientv3util"
)
// Config represents etcdpasswd configurations
type Config struct {
StartUID int `json:"start-uid"`
StartGID int `json:"start-gid"`
DefaultGroup string `json:"default-group"`
DefaultGroups []string `json:"default-groups"`
DefaultShell string `json:"default-shell"`
}
func (c Client) initializeConfig(ctx context.Context) error {
config := &Config{
DefaultShell: DefaultShell,
}
j, err := json.Marshal(config)
if err != nil {
return err
}
_, err = c.Txn(ctx).
If(clientv3util.KeyMissing(KeyConfig)).
Then(clientv3.OpPut(KeyConfig, string(j))).
Commit()
return err
}
// GetConfig retrieves *Config with revision.
func (c Client) GetConfig(ctx context.Context) (*Config, int64, error) {
RETRY:
resp, err := c.Get(ctx, KeyConfig)
if err != nil {
return nil, 0, err
}
if resp.Count == 0 {
err = c.initializeConfig(ctx)
if err != nil {
return nil, 0, err
}
goto RETRY
}
config := new(Config)
err = json.Unmarshal(resp.Kvs[0].Value, config)
if err != nil {
return nil, 0, err
}
return config, resp.Kvs[0].ModRevision, nil
}
// SetConfig tries to update *Config.
// If update was conflicted, ErrCASFailure is returned.
func (c Client) SetConfig(ctx context.Context, cfg *Config, rev int64) error {
j, err := json.Marshal(cfg)
if err != nil {
return err
}
resp, err := c.Txn(ctx).
If(clientv3.Compare(clientv3.ModRevision(KeyConfig), "=", rev)).
Then(clientv3.OpPut(KeyConfig, string(j))).
Commit()
if err != nil {
return err
}
if !resp.Succeeded {
return ErrCASFailure
}
return nil
}