|
| 1 | +package etcd |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "strconv" |
| 8 | + "strings" |
| 9 | + "time" |
| 10 | + |
| 11 | + "mosn.io/layotto/components/lock" |
| 12 | + "mosn.io/pkg/log" |
| 13 | + |
| 14 | + "go.etcd.io/etcd/client/v3" |
| 15 | +) |
| 16 | + |
| 17 | +const ( |
| 18 | + defaultDialTimeout = 5 |
| 19 | + defaultKeyPrefix = "/layotto/" |
| 20 | + |
| 21 | + prefixKey = "keyPrefix" |
| 22 | + usernameKey = "username" |
| 23 | + passwordKey = "password" |
| 24 | + dialTimeoutKey = "dialTimeout" |
| 25 | + endpointsKey = "endpoints" |
| 26 | +) |
| 27 | + |
| 28 | +type EtcdLock struct { |
| 29 | + client *clientv3.Client |
| 30 | + metadata metadata |
| 31 | + |
| 32 | + features []lock.Feature |
| 33 | + logger log.ErrorLogger |
| 34 | + |
| 35 | + ctx context.Context |
| 36 | + cancel context.CancelFunc |
| 37 | +} |
| 38 | + |
| 39 | +// NewEtcdLock returns a new etcd lock |
| 40 | +func NewEtcdLock(logger log.ErrorLogger) *EtcdLock { |
| 41 | + s := &EtcdLock{ |
| 42 | + features: make([]lock.Feature, 0), |
| 43 | + logger: logger, |
| 44 | + } |
| 45 | + |
| 46 | + return s |
| 47 | +} |
| 48 | + |
| 49 | +func (e *EtcdLock) Init(metadata lock.Metadata) error { |
| 50 | + // 1. parse config |
| 51 | + m, err := parseEtcdMetadata(metadata) |
| 52 | + if err != nil { |
| 53 | + return err |
| 54 | + } |
| 55 | + e.metadata = m |
| 56 | + // 2. construct client |
| 57 | + if e.client, err = e.newClient(m); err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + |
| 61 | + e.ctx, e.cancel = context.WithCancel(context.Background()) |
| 62 | + |
| 63 | + return err |
| 64 | +} |
| 65 | + |
| 66 | +func (e *EtcdLock) Features() []lock.Feature { |
| 67 | + return e.features |
| 68 | +} |
| 69 | + |
| 70 | +func (e *EtcdLock) TryLock(req *lock.TryLockRequest) (*lock.TryLockResponse, error) { |
| 71 | + var leaseId clientv3.LeaseID |
| 72 | + //1.Create new lease |
| 73 | + lease := clientv3.NewLease(e.client) |
| 74 | + if leaseGrantResp, err := lease.Grant(context.TODO(), 10); err != nil { |
| 75 | + return &lock.TryLockResponse{}, fmt.Errorf("[etcdLock]: Create new lease returned error: %s.ResourceId: %s", err, req.ResourceId) |
| 76 | + } else { |
| 77 | + leaseId = leaseGrantResp.ID |
| 78 | + } |
| 79 | + |
| 80 | + key := e.getKey(req.ResourceId) |
| 81 | + |
| 82 | + //2.Create new KV |
| 83 | + kv := clientv3.NewKV(e.client) |
| 84 | + //3.Create txn |
| 85 | + txn := kv.Txn(e.ctx) |
| 86 | + txn.If(clientv3.Compare(clientv3.CreateRevision(key), "=", 0)).Then( |
| 87 | + clientv3.OpPut(key, req.LockOwner, clientv3.WithLease(leaseId))).Else( |
| 88 | + clientv3.OpGet(key)) |
| 89 | + //4.Commit and try get lock |
| 90 | + txnResponse, err := txn.Commit() |
| 91 | + if err != nil { |
| 92 | + return &lock.TryLockResponse{}, fmt.Errorf("[etcdLock]: Creat lock returned error: %s.ResourceId: %s", err, req.ResourceId) |
| 93 | + } |
| 94 | + |
| 95 | + return &lock.TryLockResponse{ |
| 96 | + Success: txnResponse.Succeeded, |
| 97 | + }, nil |
| 98 | +} |
| 99 | + |
| 100 | +func (e *EtcdLock) Unlock(req *lock.UnlockRequest) (*lock.UnlockResponse, error) { |
| 101 | + key := e.getKey(req.ResourceId) |
| 102 | + |
| 103 | + kv := clientv3.NewKV(e.client) |
| 104 | + txn := kv.Txn(e.ctx) |
| 105 | + txn.If(clientv3.Compare(clientv3.Value(key), "=", req.LockOwner)).Then( |
| 106 | + clientv3.OpDelete(key)).Else( |
| 107 | + clientv3.OpGet(key)) |
| 108 | + txnResponse, err := txn.Commit() |
| 109 | + if err != nil { |
| 110 | + return newInternalErrorUnlockResponse(), fmt.Errorf("[etcdLock]: Unlock returned error: %s.ResourceId: %s", err, req.ResourceId) |
| 111 | + } |
| 112 | + |
| 113 | + if txnResponse.Succeeded { |
| 114 | + return &lock.UnlockResponse{Status: lock.SUCCESS}, nil |
| 115 | + } else { |
| 116 | + resp := txnResponse.Responses[0].GetResponseRange() |
| 117 | + if len(resp.Kvs) == 0 { |
| 118 | + return &lock.UnlockResponse{Status: lock.LOCK_UNEXIST}, nil |
| 119 | + } |
| 120 | + |
| 121 | + return &lock.UnlockResponse{Status: lock.LOCK_BELONG_TO_OTHERS}, nil |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +func (e *EtcdLock) Close() error { |
| 126 | + e.cancel() |
| 127 | + |
| 128 | + return e.client.Close() |
| 129 | +} |
| 130 | + |
| 131 | +func (e *EtcdLock) newClient(meta metadata) (*clientv3.Client, error) { |
| 132 | + |
| 133 | + config := clientv3.Config{ |
| 134 | + Endpoints: meta.endpoints, |
| 135 | + DialTimeout: time.Duration(meta.dialTimeout) * time.Second, |
| 136 | + Username: meta.username, |
| 137 | + Password: meta.password, |
| 138 | + } |
| 139 | + |
| 140 | + if client, err := clientv3.New(config); err != nil { |
| 141 | + return nil, err |
| 142 | + } else { |
| 143 | + return client, nil |
| 144 | + } |
| 145 | +} |
| 146 | + |
| 147 | +func (e *EtcdLock) getKey(resourceId string) string { |
| 148 | + return fmt.Sprintf("%s%s", e.metadata.keyPrefix, resourceId) |
| 149 | +} |
| 150 | + |
| 151 | +func newInternalErrorUnlockResponse() *lock.UnlockResponse { |
| 152 | + return &lock.UnlockResponse{ |
| 153 | + Status: lock.INTERNAL_ERROR, |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +func parseEtcdMetadata(meta lock.Metadata) (metadata, error) { |
| 158 | + m := metadata{} |
| 159 | + var err error |
| 160 | + |
| 161 | + if val, ok := meta.Properties[endpointsKey]; ok && val != "" { |
| 162 | + m.endpoints = strings.Split(val, ";") |
| 163 | + } else { |
| 164 | + return m, errors.New("etcd lock error: missing endpoints address") |
| 165 | + } |
| 166 | + |
| 167 | + if val, ok := meta.Properties[dialTimeoutKey]; ok && val != "" { |
| 168 | + if m.dialTimeout, err = strconv.Atoi(val); err != nil { |
| 169 | + return m, fmt.Errorf("etcd lock error: ncorrect dialTimeout value %s", val) |
| 170 | + } |
| 171 | + } else { |
| 172 | + m.dialTimeout = defaultDialTimeout |
| 173 | + } |
| 174 | + |
| 175 | + if val, ok := meta.Properties[prefixKey]; ok && val != "" { |
| 176 | + m.keyPrefix = val |
| 177 | + } else { |
| 178 | + m.keyPrefix = defaultKeyPrefix |
| 179 | + } |
| 180 | + |
| 181 | + if val, ok := meta.Properties[usernameKey]; ok && val != "" { |
| 182 | + m.username = val |
| 183 | + } |
| 184 | + |
| 185 | + if val, ok := meta.Properties[passwordKey]; ok && val != "" { |
| 186 | + m.password = val |
| 187 | + } |
| 188 | + |
| 189 | + return m, nil |
| 190 | +} |
| 191 | + |
| 192 | +type metadata struct { |
| 193 | + keyPrefix string |
| 194 | + dialTimeout int |
| 195 | + endpoints []string |
| 196 | + username string |
| 197 | + password string |
| 198 | +} |
0 commit comments