/
etcd.go
267 lines (237 loc) · 5.99 KB
/
etcd.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package storage
import (
"context"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/cestlascorpion/opossum/utils"
log "github.com/sirupsen/logrus"
"go.etcd.io/etcd/client/v3"
)
type EtcdHolder struct {
endpoints []string
ip string
port string
addr string
maxId int64
path *etcdPath
lastUpdateTs int64
workerId int64
cancel context.CancelFunc
}
func NewEtcdHolder(ctx context.Context, ip, port string, endpoints []string, table string, maxId int64) (*EtcdHolder, error) {
e := &EtcdHolder{
endpoints: endpoints,
ip: ip,
port: port,
addr: fmt.Sprintf("%s:%s", ip, port),
maxId: maxId,
path: &etcdPath{
LockPath: fmt.Sprintf(etcdLockerPath, table),
ForeverPath: fmt.Sprintf(etcdForeverPath, table),
},
}
locker, err := NewLocker(ctx, e.path.LockPath, endpoints)
if err != nil {
log.Errorf("new locker err %+v", err)
return nil, err
}
err = locker.Lock(ctx)
if err != nil {
log.Errorf("locker lock err %+v", err)
return nil, err
}
defer func() {
_ = locker.UnLock(ctx)
}()
err = e.initWorkerId(ctx)
if err != nil {
log.Errorf("init worker id err %+v", err)
return nil, err
}
log.Infof("new etcd holder ok %+v", e)
return e, nil
}
func (e *EtcdHolder) GetWorkerId(ctx context.Context) (int64, error) {
return e.workerId, nil
}
func (e *EtcdHolder) Close(ctx context.Context) error {
e.cancel()
return nil
}
// ---------------------------------------------------------------------------------------------------------------------
const (
etcdLockerPath = "/snowflake/%s/locker"
etcdForeverPath = "/snowflake/%s/forever"
dialTimeout = time.Second * 10
updateInterval = time.Second * 3
)
type etcdPath struct {
LockPath string
ForeverPath string
}
type endpoint struct {
IP string `json:"ip"`
Port string `json:"port"`
Ts int64 `json:"ts"`
}
func (e *EtcdHolder) initWorkerId(ctx context.Context) error {
cli, err := clientv3.New(clientv3.Config{
Endpoints: e.endpoints,
DialTimeout: dialTimeout,
})
if err != nil {
log.Errorf("new etcd client err %+v", err)
return err
}
resp, err := cli.Get(ctx, e.path.ForeverPath, clientv3.WithPrefix())
if err != nil {
log.Errorf("get forever path err %+v", err)
return err
}
if resp.Count == 0 {
e.workerId = 0
p, err := e.createNode(ctx, cli)
if err != nil {
log.Errorf("create node err %+v", err)
return err
}
e.scheduledUploadData(ctx, cli, p)
return nil
}
nodeMap := make(map[string]int64)
realMap := make(map[string]string)
for _, v := range resp.Kvs {
nodeKey := strings.Split(filepath.Base(string(v.Key)), "-")
if len(nodeKey) != 2 {
log.Errorf("invalid node key %+v", nodeKey)
return errors.New(utils.ErrInvalidNodeKey)
}
realMap[nodeKey[0]] = string(v.Key)
id, err := strconv.ParseInt(nodeKey[1], 10, 64)
if err != nil {
log.Errorf("invalid node key %s", nodeKey[1])
return errors.New(utils.ErrInvalidWorkerId)
}
nodeMap[nodeKey[0]] = id
}
if workerId, ok := nodeMap[e.addr]; ok {
p := realMap[e.addr]
if !e.checkInitTimeStamp(ctx, cli, p) {
log.Errorf("check init ts failed")
return errors.New(utils.ErrInvalidClockTime)
}
e.workerId = workerId
e.scheduledUploadData(ctx, cli, p)
log.Infof("restart node %s ok", e.addr)
return nil
}
workerId := int64(0)
for _, id := range nodeMap {
if workerId < id {
workerId = id
}
}
e.workerId = workerId + 1
if e.workerId > e.maxId {
log.Errorf("invalid worker id")
return errors.New(utils.ErrInvalidWorkerId)
}
p, err := e.createNode(ctx, cli)
if err != nil {
log.Errorf("create node err %+v", err)
return err
}
e.scheduledUploadData(ctx, cli, p)
return nil
}
func (e *EtcdHolder) createNode(ctx context.Context, client *clientv3.Client) (string, error) {
path := fmt.Sprintf("%s/%s-%d", e.path.ForeverPath, e.addr, e.workerId)
data, err := e.marshallNode()
if err != nil {
log.Errorf("build data err %+v", err)
return "", err
}
_, err = client.Put(ctx, path, string(data))
if err != nil {
log.Errorf("put data err %+v", err)
return "", err
}
return path, nil
}
func (e *EtcdHolder) checkInitTimeStamp(ctx context.Context, cli *clientv3.Client, path string) bool {
resp, err := cli.Get(ctx, path)
if err != nil {
log.Errorf("get err %+v", err)
return false
}
if resp == nil || len(resp.Kvs) == 0 {
log.Errorf("no such key %s", path)
return false
}
node, err := e.unmarshallNode(resp.Kvs[0].Value)
return !(node.Ts > time.Now().UnixMilli())
}
func (e *EtcdHolder) scheduledUploadData(ctx context.Context, cli *clientv3.Client, path string) {
ctx, cancel := context.WithCancel(ctx)
e.cancel = cancel
go func(ctx context.Context) {
ticker := time.NewTicker(updateInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
err := e.updateNewData(context.Background(), cli, path)
if err != nil {
log.Errorf("update new data err %+v", err)
}
}
}
}(ctx)
}
func (e *EtcdHolder) updateNewData(ctx context.Context, cli *clientv3.Client, path string) error {
if time.Now().UnixMilli() < e.lastUpdateTs {
log.Warnf("last update ts gt time now")
return nil
}
bs, err := e.marshallNode()
if err != nil {
log.Errorf("build data err %+v", err)
return err
}
_, err = cli.Put(ctx, path, string(bs))
if err != nil {
log.Errorf("put err %+v", err)
return err
}
return nil
}
func (e *EtcdHolder) marshallNode() ([]byte, error) {
node := &endpoint{
IP: e.ip,
Port: e.port,
Ts: time.Now().UnixMilli(),
}
bs, err := json.Marshal(node)
if err != nil {
log.Errorf("json marshall err %+v", err)
return nil, err
}
return bs, nil
}
func (e *EtcdHolder) unmarshallNode(val []byte) (*endpoint, error) {
node := &endpoint{}
err := json.Unmarshal(val, node)
if err != nil {
log.Errorf("json unmarshall err %+v", err)
return nil, err
}
return node, nil
}
// ---------------------------------------------------------------------------------------------------------------------