Debian Codegraph @

README.md

raw symbols SCIP
1 dsync [![Slack](https://slack.minio.io/slack?type=svg)](https://slack.minio.io) [![Go Report Card](https://goreportcard.com/badge/minio/minio)](https://goreportcard.com/report/minio/minio) [![codecov](https://codecov.io/gh/minio/dsync/branch/master/graph/badge.svg)](https://codecov.io/gh/minio/dsync)
2 =====
3
4 A distributed locking and syncing package for Go.
5
6 Introduction
7 ------------
8
9 `dsync` is a package for doing distributed locks over a network of `n` nodes. It is designed with simplicity in mind and hence offers limited scalability (`n <= 16`). Each node will be connected to all other nodes and lock requests from any node will be broadcast to all connected nodes. A node will succeed in getting the lock if `n/2 + 1` nodes (whether or not including itself) respond positively. If the lock is acquired it can be held for as long as the client desires and needs to be released afterwards. This will cause the release to be broadcast to all nodes after which the lock becomes available again.
10
11 Motivation
12 ----------
13
14 This package was developed for the distributed server version of [Minio Object Storage](https://minio.io/). For this we needed a distributed locking mechanism for up to 16 servers that each would be running `minio server`. The locking mechanism itself should be a reader/writer mutual exclusion lock meaning that it can be held by a single writer or an arbitrary number of readers.
15
16 For [minio](https://minio.io/) the distributed version is started as follows (for a 6-server system):
17
18 ```
19 $ minio server http://server1/disk http://server2/disk http://server3/disk http://server4/disk http://server5/disk http://server6/disk
20 ```
21
22 _(note that the same identical command should be run on servers `server1` through to `server6`)_
23
24 Design goals
25 ------------
26
27 * **Simple design**: by keeping the design simple, many tricky edge cases can be avoided.
28 * **No master node**: there is no concept of a master node which, if this would be used and the master would be down, causes locking to come to a complete stop. (Unless you have a design with a slave node but this adds yet more complexity.)
29 * **Resilient**: if one or more nodes go down, the other nodes should not be affected and can continue to acquire locks (provided not more than `n/2 - 1` nodes are down).
30 * Drop-in replacement for `sync.RWMutex` and supports [`sync.Locker`](https://github.com/golang/go/blob/master/src/sync/mutex.go#L30) interface.
31 * Automatically reconnect to (restarted) nodes.
32
33 Restrictions
34 ------------
35
36 * Limited scalability: up to 16 nodes.
37 * Fixed configuration: changes in the number and/or network names/IP addresses need a restart of all nodes in order to take effect.
38 * If a down node comes up, it will not try to (re)acquire any locks that it may have held.
39 * Not designed for high performance applications such as key/value stores.
40
41 Performance
42 -----------
43
44 * Support up to a total of 7500 locks/second for maximum size of 16 nodes (consuming 10% CPU usage per server) on moderately powerful server hardware.
45 * Lock requests (successful) should not take longer than 1ms (provided decent network connection of 1 Gbit or more between the nodes).
46
47 The tables below show detailed performance numbers.
48
49 ### Performance with varying number of nodes
50
51 This table shows test performance on the same (EC2) instance type but with a varying number of nodes:
52
53 | EC2 Instance Type | Nodes | Locks/server/sec | Total Locks/sec | CPU Usage |
54 | -------------------- | -----:| --------------------:| ---------------:| ---------:|
55 | c3.2xlarge | 4 | (min=3110, max=3376) | 12972 | 25% |
56 | c3.2xlarge | 8 | (min=1884, max=2096) | 15920 | 25% |
57 | c3.2xlarge | 12 | (min=1239, max=1558) | 16782 | 25% |
58 | c3.2xlarge | 16 | (min=996, max=1391) | 19096 | 25% |
59
60 The min and max locks/server/sec gradually declines but due to the larger number of nodes the overall total number of locks rises steadily (at the same CPU usage level).
61
62 ### Performance with difference instance types
63
64 This table shows test performance for a fixed number of 8 nodes on different EC2 instance types:
65
66 | EC2 Instance Type | Nodes | Locks/server/sec | Total Locks/sec | CPU Usage |
67 | -------------------- | -----:| --------------------:| ---------------:| ---------:|
68 | c3.large (2 vCPU) | 8 | (min=823, max=896) | 6876 | 75% |
69 | c3.2xlarge (8 vCPU) | 8 | (min=1884, max=2096) | 15920 | 25% |
70 | c3.8xlarge (32 vCPU) | 8 | (min=2601, max=2898) | 21996 | 10% |
71
72 With the rise in the number of cores the CPU load decreases and overall performance increases.
73
74 ### Stress test
75
76 Stress test on a c3.8xlarge (32 vCPU) instance type:
77
78 | EC2 Instance Type | Nodes | Locks/server/sec | Total Locks/sec | CPU Usage |
79 | -------------------- | -----:| --------------------:| ---------------:| ---------:|
80 | c3.8xlarge | 8 | (min=2601, max=2898) | 21996 | 10% |
81 | c3.8xlarge | 8 | (min=4756, max=5227) | 39932 | 20% |
82 | c3.8xlarge | 8 | (min=7979, max=8517) | 65984 | 40% |
83 | c3.8xlarge | 8 | (min=9267, max=9469) | 74944 | 50% |
84
85 The system can be pushed to 75K locks/sec at 50% CPU load.
86
87 Usage
88 -----
89
90 ### Exclusive lock
91
92 Here is a simple example showing how to protect a single resource (drop-in replacement for `sync.Mutex`):
93
94 ```
95 import (
96 "github.com/minio/dsync"
97 )
98
99 func lockSameResource() {
100
101 // Create distributed mutex to protect resource 'test'
102 dm := dsync.NewDRWMutex("test")
103
104 dm.Lock()
105 log.Println("first lock granted")
106
107 // Release 1st lock after 5 seconds
108 go func() {
109 time.Sleep(5 * time.Second)
110 log.Println("first lock unlocked")
111 dm.Unlock()
112 }()
113
114 // Try to acquire lock again, will block until initial lock is released
115 log.Println("about to lock same resource again...")
116 dm.Lock()
117 log.Println("second lock granted")
118
119 time.Sleep(2 * time.Second)
120 dm.Unlock()
121 }
122 ```
123
124 which gives the following output:
125
126 ```
127 2016/09/02 14:50:00 first lock granted
128 2016/09/02 14:50:00 about to lock same resource again...
129 2016/09/02 14:50:05 first lock unlocked
130 2016/09/02 14:50:05 second lock granted
131 ```
132
133 ### Read locks
134
135 DRWMutex also supports multiple simultaneous read locks as shown below (analogous to `sync.RWMutex`)
136
137 ```
138 func twoReadLocksAndSingleWriteLock() {
139
140 drwm := dsync.NewDRWMutex("resource")
141
142 drwm.RLock()
143 log.Println("1st read lock acquired, waiting...")
144
145 drwm.RLock()
146 log.Println("2nd read lock acquired, waiting...")
147
148 go func() {
149 time.Sleep(1 * time.Second)
150 drwm.RUnlock()
151 log.Println("1st read lock released, waiting...")
152 }()
153
154 go func() {
155 time.Sleep(2 * time.Second)
156 drwm.RUnlock()
157 log.Println("2nd read lock released, waiting...")
158 }()
159
160 log.Println("Trying to acquire write lock, waiting...")
161 drwm.Lock()
162 log.Println("Write lock acquired, waiting...")
163
164 time.Sleep(3 * time.Second)
165
166 drwm.Unlock()
167 }
168 ```
169
170 which gives the following output:
171
172 ```
173 2016/09/02 15:05:20 1st read lock acquired, waiting...
174 2016/09/02 15:05:20 2nd read lock acquired, waiting...
175 2016/09/02 15:05:20 Trying to acquire write lock, waiting...
176 2016/09/02 15:05:22 1st read lock released, waiting...
177 2016/09/02 15:05:24 2nd read lock released, waiting...
178 2016/09/02 15:05:24 Write lock acquired, waiting...
179 ```
180
181 Basic architecture
182 ------------------
183
184 ### Lock process
185
186 The basic steps in the lock process are as follows:
187 - broadcast lock message to all `n` nodes
188 - collect all responses within certain time-out window
189 - if quorum met (minimally `n/2 + 1` responded positively) then grant lock
190 - otherwise release all underlying locks and try again after a (semi-)random delay
191 - release any locks that (still) came in after time time-out window
192
193 ### Unlock process
194
195 The unlock process is really simple:
196 - broadcast unlock message to all nodes that granted lock
197 - if a destination is not available, retry with gradually longer back-off window to still deliver
198 - ignore the 'result' (cover for cases where destination node has gone down and came back up)
199
200 Dealing with Stale Locks
201 ------------------------
202
203 A 'stale' lock is a lock that is left at a node while the client that originally acquired the client either:
204 - never released the lock (due to eg a crash) or
205 - is disconnected from the network and henceforth not able to deliver the unlock message.
206
207 Too many stale locks can prevent a new lock on a resource from being acquired, that is, if the sum of the stale locks and the number of down nodes is greater than `n/2 - 1`. In `dsync` a recovery mechanism is implemented to remove stale locks (see [here](https://github.com/minio/dsync/pull/22#issue-176751755) for the details).
208
209 Known deficiencies
210 ------------------
211
212 Known deficiencies can be divided into two categories, namely a) more than one write lock granted and b) lock not becoming available anymore.
213
214 ### More than one write lock
215
216 So far we have identified one case during which this can happen (example for 8 node system):
217 - 3 nodes are down (say 6, 7, and 8)
218 - node 1 acquires a lock on "test" (nodes 1 through to 5 giving quorum)
219 - node 4 and 5 crash (dropping the lock)
220 - nodes 4 through to 8 restart
221 - node 4 acquires a lock on "test" (nodes 4 through to 8 giving quorum)
222
223 Now we have two concurrent locks on the same resource name which violates the core requirement. Note that if just a single server out of 4 or 5 crashes that we are still fine because the second lock cannot acquire quorum.
224
225 This table summarizes the conditions for different configurations during which this can happen:
226
227 | Nodes | Down nodes | Crashed nodes | Total nodes |
228 | -----:| ----------:| -------------:| -----------:|
229 | 4 | 1 | 2 | 3 |
230 | 8 | 3 | 2 | 5 |
231 | 12 | 5 | 2 | 7 |
232 | 16 | 7 | 2 | 9 |
233
234 (for more info see `testMultipleServersOverQuorumDownDuringLockKnownError` in [chaos.go](https://github.com/minio/dsync/blob/master/chaos/chaos.go))
235
236 ### Lock not available anymore
237
238 This would be due to too many stale locks and/or too many servers down (total over `n/2 - 1`). The following table shows the maximum toterable number for different node sizes:
239
240 | Nodes | Max tolerable |
241 | -----:| -------------:|
242 | 4 | 1 |
243 | 8 | 3 |
244 | 12 | 5 |
245 | 16 | 7 |
246
247 If you see any other short comings, we would be interested in hearing about them.
248
249 Tackled issues
250 --------------
251
252 * When two nodes want to acquire the same lock at precisely the same time, it is possible for both to just acquire `n/2` locks and there is no majority winner. Both will fail back to their clients and will retry later after a semi-randomized delay.
253
254 Server side logic
255 -----------------
256
257 On the server side just the following logic needs to be added (barring some extra error checking):
258
259 ```
260 const WriteLock = -1
261
262 type lockServer struct {
263 mutex sync.Mutex
264 lockMap map[string]int64 // Map of locks, with negative value indicating (exclusive) write lock
265 // and positive values indicating number of read locks
266 }
267
268 func (l *lockServer) Lock(args *LockArgs, reply *bool) error {
269 l.mutex.Lock()
270 defer l.mutex.Unlock()
271 if _, *reply = l.lockMap[args.Name]; !*reply {
272 l.lockMap[args.Name] = WriteLock // No locks held on the given name, so claim write lock
273 }
274 *reply = !*reply // Negate *reply to return true when lock is granted or false otherwise
275 return nil
276 }
277
278 func (l *lockServer) Unlock(args *LockArgs, reply *bool) error {
279 l.mutex.Lock()
280 defer l.mutex.Unlock()
281 var locksHeld int64
282 if locksHeld, *reply = l.lockMap[args.Name]; !*reply { // No lock is held on the given name
283 return fmt.Errorf("Unlock attempted on an unlocked entity: %s", args.Name)
284 }
285 if *reply = locksHeld == WriteLock; !*reply { // Unless it is a write lock
286 return fmt.Errorf("Unlock attempted on a read locked entity: %s (%d read locks active)", args.Name, locksHeld)
287 }
288 delete(l.lockMap, args.Name) // Remove the write lock
289 return nil
290 }
291 ```
292
293 If you also want RLock()/RUnlock() functionality, then add this as well:
294
295 ```
296 const ReadLock = 1
297
298 func (l *lockServer) RLock(args *LockArgs, reply *bool) error {
299 l.mutex.Lock()
300 defer l.mutex.Unlock()
301 var locksHeld int64
302 if locksHeld, *reply = l.lockMap[args.Name]; !*reply {
303 l.lockMap[args.Name] = ReadLock // No locks held on the given name, so claim (first) read lock
304 *reply = true
305 } else {
306 if *reply = locksHeld != WriteLock; *reply { // Unless there is a write lock
307 l.lockMap[args.Name] = locksHeld + ReadLock // Grant another read lock
308 }
309 }
310 return nil
311 }
312
313 func (l *lockServer) RUnlock(args *LockArgs, reply *bool) error {
314 l.mutex.Lock()
315 defer l.mutex.Unlock()
316 var locksHeld int64
317 if locksHeld, *reply = l.lockMap[args.Name]; !*reply { // No lock is held on the given name
318 return fmt.Errorf("RUnlock attempted on an unlocked entity: %s", args.Name)
319 }
320 if *reply = locksHeld != WriteLock; !*reply { // A write-lock is held, cannot release a read lock
321 return fmt.Errorf("RUnlock attempted on a write locked entity: %s", args.Name)
322 }
323 if locksHeld > ReadLock {
324 l.lockMap[args.Name] = locksHeld - ReadLock // Remove one of the read locks held
325 } else {
326 delete(l.lockMap, args.Name) // Remove the (last) read lock
327 }
328 return nil
329 }
330 ```
331
332 See [dsync-server_test.go](https://github.com/fwessels/dsync/blob/master/dsync-server_test.go) for a full implementation.
333
334 Sub projects
335 ------------
336
337 * See [performance](https://github.com/minio/dsync/tree/master/performance) directory for performance measurements
338 * See [chaos](https://github.com/minio/dsync/tree/master/chaos) directory for some edge cases
339
340 Testing
341 -------
342
343 The full test code (including benchmarks) from `sync/rwmutex_test.go` is used for testing purposes.
344
345 Extensions / Other use cases
346 ----------------------------
347
348 ### Robustness vs Performance
349
350 It is possible to trade some level of robustness with overall performance by not contacting each node for every Lock()/Unlock() cycle. In the normal case (example for `n = 16` nodes) a total of 32 RPC messages is sent and the lock is granted if at least a quorum of `n/2 + 1` nodes respond positively. When all nodes are functioning normally this would mean `n = 16` positive responses and, in fact, `n/2 - 1 = 7` responses over the (minimum) quorum of `n/2 + 1 = 9`. So you could say that this is some overkill, meaning that even if 6 nodes are down you still have an extra node over the quorum.
351
352 For this case it is possible to reduce the number of nodes to be contacted to for example `12`. Instead of 32 RPC messages now 24 message will be sent which is 25% less. As the performance is mostly depending on the number of RPC messages sent, the total locks/second handled by all nodes would increase by 33% (given the same CPU load).
353
354 You do however want to make sure that you have some sort of 'random' selection of which 12 out of the 16 nodes will participate in every lock. See [here](https://gist.github.com/fwessels/dbbafd537c13ec8f88b360b3a0091ac0) for some sample code that could help with this.
355
356 ### Scale beyond 16 nodes?
357
358 Building on the previous example and depending on how resilient you want to be for outages of nodes, you can also go the other way, namely to increase the total number of nodes while keeping the number of nodes contacted per lock the same.
359
360 For instance you could imagine a system of 32 nodes where only a quorom majority of `9` would be needed out of `12` nodes. Again this requires some sort of pseudo-random 'deterministic' selection of 12 nodes out of the total of 32 servers (same [example](https://gist.github.com/fwessels/dbbafd537c13ec8f88b360b3a0091ac0) as above).
361
362 Other techniques
363 ----------------
364
365 We are well aware that there are more sophisticated systems such as zookeeper, raft, etc. However we found that for our limited use case this was adding too much complexity. So if `dsync` does not meet your requirements than you are probably better off using one of those systems.
366
367 Other links that you may find interesting:
368 - [Distributed locks with Redis](http://redis.io/topics/distlock)
369 - Based on the above: [Redis-based distributed mutual exclusion lock implementation for Go](https://github.com/hjr265/redsync.go)
370
371 Performance of `net/rpc` vs `grpc`
372 ----------------------------------
373
374 We did an analysis of the performance of `net/rpc` vs `grpc`, see [here](https://github.com/golang/go/issues/16844#issuecomment-245261755), so we'll stick with `net/rpc` for now.
375
376 License
377 -------
378
379 Released under the Apache License v2.0. You can find the complete text in the file LICENSE.
380
381 Contributing
382 ------------
383
384 Contributions are welcome, please send PRs for any enhancements.