Debian Codegraph @

drwmutex.go

raw symbols SCIP
1 /*
2 * Minio Cloud Storage, (C) 2016 Minio, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package dsync
18
19 import (
20 cryptorand "crypto/rand"
21 "fmt"
22 golog "log"
23 "math"
24 "math/rand"
25 "net"
26 "os"
27 "sync"
28 "time"
29 )
30
31 // Indicator if logging is enabled.
32 var dsyncLog bool
33
34 func init() {
35 // Check for DSYNC_LOG env variable, if set logging will be enabled for failed RPC operations.
36 dsyncLog = os.Getenv("DSYNC_LOG") == "1"
37 }
38
39 func log(msg ...interface{}) {
40 if dsyncLog {
41 golog.Println(msg...)
42 }
43 }
44
45 // DRWMutexAcquireTimeout - tolerance limit to wait for lock acquisition before.
46 const DRWMutexAcquireTimeout = 25 * time.Millisecond // 25ms.
47
48 // A DRWMutex is a distributed mutual exclusion lock.
49 type DRWMutex struct {
50 Name string
51 writeLocks []string // Array of nodes that granted a write lock
52 readersLocks [][]string // Array of array of nodes that granted reader locks
53 m sync.Mutex // Mutex to prevent multiple simultaneous locks from this node
54 }
55
56 type Granted struct {
57 index int
58 lockUid string // Locked if set with UID string, unlocked if empty
59 }
60
61 func (g *Granted) isLocked() bool {
62 return isLocked(g.lockUid)
63 }
64
65 func isLocked(uid string) bool {
66 return len(uid) > 0
67 }
68
69 func NewDRWMutex(name string) *DRWMutex {
70 return &DRWMutex{
71 Name: name,
72 writeLocks: make([]string, dnodeCount),
73 }
74 }
75
76 // Lock holds a write lock on dm.
77 //
78 // If the lock is already in use, the calling go routine
79 // blocks until the mutex is available.
80 func (dm *DRWMutex) Lock() {
81
82 isReadLock := false
83 dm.lockBlocking(isReadLock)
84 }
85
86 // RLock holds a read lock on dm.
87 //
88 // If one or more read lock are already in use, it will grant another lock.
89 // Otherwise the calling go routine blocks until the mutex is available.
90 func (dm *DRWMutex) RLock() {
91
92 isReadLock := true
93 dm.lockBlocking(isReadLock)
94 }
95
96 // lockBlocking will acquire either a read or a write lock
97 //
98 // The call will block until the lock is granted using a built-in
99 // timing randomized back-off algorithm to try again until successful
100 func (dm *DRWMutex) lockBlocking(isReadLock bool) {
101
102 runs, backOff := 1, 1
103
104 for {
105 // create temp array on stack
106 locks := make([]string, dnodeCount)
107
108 // try to acquire the lock
109 success := lock(clnts, &locks, dm.Name, isReadLock)
110 if success {
111 dm.m.Lock()
112 defer dm.m.Unlock()
113
114 // if success, copy array to object
115 if isReadLock {
116 // append new array of strings at the end
117 dm.readersLocks = append(dm.readersLocks, make([]string, dnodeCount))
118 // and copy stack array into last spot
119 copy(dm.readersLocks[len(dm.readersLocks)-1], locks[:])
120 } else {
121 copy(dm.writeLocks, locks[:])
122 }
123
124 return
125 }
126
127 // We timed out on the previous lock, incrementally wait for a longer back-off time,
128 // and try again afterwards
129 time.Sleep(time.Duration(backOff) * time.Millisecond)
130
131 backOff += int(rand.Float64() * math.Pow(2, float64(runs)))
132 if backOff > 1024 {
133 backOff = backOff % 64
134
135 runs = 1 // reset runs
136 } else if runs < 10 {
137 runs++
138 }
139 }
140 }
141
142 // lock tries to acquire the distributed lock, returning true or false
143 //
144 func lock(clnts []NetLocker, locks *[]string, lockName string, isReadLock bool) bool {
145
146 // Create buffered channel of size equal to total number of nodes.
147 ch := make(chan Granted, dnodeCount)
148
149 for index, c := range clnts {
150
151 // broadcast lock request to all nodes
152 go func(index int, isReadLock bool, c NetLocker) {
153 // All client methods issuing RPCs are thread-safe and goroutine-safe,
154 // i.e. it is safe to call them from multiple concurrently running go routines.
155 bytesUid := [16]byte{}
156 cryptorand.Read(bytesUid[:])
157 uid := fmt.Sprintf("%X", bytesUid[:])
158
159 args := LockArgs{
160 UID: uid,
161 Resource: lockName,
162 ServerAddr: clnts[ownNode].ServerAddr(),
163 ServiceEndpoint: clnts[ownNode].ServiceEndpoint(),
164 }
165
166 var locked bool
167 var err error
168 if isReadLock {
169 if locked, err = c.RLock(args); err != nil {
170 log("Unable to call RLock", err)
171 }
172 } else {
173 if locked, err = c.Lock(args); err != nil {
174 log("Unable to call Lock", err)
175 }
176 }
177
178 g := Granted{index: index}
179 if locked {
180 g.lockUid = args.UID
181 }
182 ch <- g
183
184 }(index, isReadLock, c)
185 }
186
187 quorum := false
188
189 var wg sync.WaitGroup
190 wg.Add(1)
191 go func(isReadLock bool) {
192
193 // Wait until we have either a) received all lock responses, b) received too many 'non-'locks for quorum to be or c) time out
194 i, locksFailed := 0, 0
195 done := false
196 timeout := time.After(DRWMutexAcquireTimeout)
197
198 for ; i < dnodeCount; i++ { // Loop until we acquired all locks
199
200 select {
201 case grant := <-ch:
202 if grant.isLocked() {
203 // Mark that this node has acquired the lock
204 (*locks)[grant.index] = grant.lockUid
205 } else {
206 locksFailed++
207 if !isReadLock && locksFailed > dnodeCount-dquorum ||
208 isReadLock && locksFailed > dnodeCount-dquorumReads {
209 // We know that we are not going to get the lock anymore, so exit out
210 // and release any locks that did get acquired
211 done = true
212 // Increment the number of grants received from the buffered channel.
213 i++
214 releaseAll(clnts, locks, lockName, isReadLock)
215 }
216 }
217
218 case <-timeout:
219 done = true
220 // timeout happened, maybe one of the nodes is slow, count
221 // number of locks to check whether we have quorum or not
222 if !quorumMet(locks, isReadLock) {
223 releaseAll(clnts, locks, lockName, isReadLock)
224 }
225 }
226
227 if done {
228 break
229 }
230 }
231
232 // Count locks in order to determine whterh we have quorum or not
233 quorum = quorumMet(locks, isReadLock)
234
235 // Signal that we have the quorum
236 wg.Done()
237
238 // Wait for the other responses and immediately release the locks
239 // (do not add them to the locks array because the DRWMutex could
240 // already has been unlocked again by the original calling thread)
241 for ; i < dnodeCount; i++ {
242 grantToBeReleased := <-ch
243 if grantToBeReleased.isLocked() {
244 // release lock
245 sendRelease(clnts[grantToBeReleased.index], lockName, grantToBeReleased.lockUid, isReadLock)
246 }
247 }
248 }(isReadLock)
249
250 wg.Wait()
251
252 // Verify that localhost server is actively participating in the lock (the lock maintenance relies on this fact)
253 if quorum && !isLocked((*locks)[ownNode]) {
254 // If not, release lock (and try again later)
255 releaseAll(clnts, locks, lockName, isReadLock)
256 quorum = false
257 }
258
259 return quorum
260 }
261
262 // quorumMet determines whether we have acquired the required quorum of underlying locks or not
263 func quorumMet(locks *[]string, isReadLock bool) bool {
264
265 count := 0
266 for _, uid := range *locks {
267 if isLocked(uid) {
268 count++
269 }
270 }
271
272 if isReadLock {
273 return count >= dquorumReads
274 } else {
275 return count >= dquorum
276 }
277 }
278
279 // releaseAll releases all locks that are marked as locked
280 func releaseAll(clnts []NetLocker, locks *[]string, lockName string, isReadLock bool) {
281 for lock := 0; lock < dnodeCount; lock++ {
282 if isLocked((*locks)[lock]) {
283 sendRelease(clnts[lock], lockName, (*locks)[lock], isReadLock)
284 (*locks)[lock] = ""
285 }
286 }
287 }
288
289 // Unlock unlocks the write lock.
290 //
291 // It is a run-time error if dm is not locked on entry to Unlock.
292 func (dm *DRWMutex) Unlock() {
293
294 // create temp array on stack
295 locks := make([]string, dnodeCount)
296
297 {
298 dm.m.Lock()
299 defer dm.m.Unlock()
300
301 // Check if minimally a single bool is set in the writeLocks array
302 lockFound := false
303 for _, uid := range dm.writeLocks {
304 if isLocked(uid) {
305 lockFound = true
306 break
307 }
308 }
309 if !lockFound {
310 panic("Trying to Unlock() while no Lock() is active")
311 }
312
313 // Copy write locks to stack array
314 copy(locks, dm.writeLocks[:])
315 // Clear write locks array
316 dm.writeLocks = make([]string, dnodeCount)
317 }
318
319 isReadLock := false
320 unlock(locks, dm.Name, isReadLock)
321 }
322
323 // RUnlock releases a read lock held on dm.
324 //
325 // It is a run-time error if dm is not locked on entry to RUnlock.
326 func (dm *DRWMutex) RUnlock() {
327
328 // create temp array on stack
329 locks := make([]string, dnodeCount)
330
331 {
332 dm.m.Lock()
333 defer dm.m.Unlock()
334 if len(dm.readersLocks) == 0 {
335 panic("Trying to RUnlock() while no RLock() is active")
336 }
337 // Copy out first element to release it first (FIFO)
338 copy(locks, dm.readersLocks[0][:])
339 // Drop first element from array
340 dm.readersLocks = dm.readersLocks[1:]
341 }
342
343 isReadLock := true
344 unlock(locks, dm.Name, isReadLock)
345 }
346
347 func unlock(locks []string, name string, isReadLock bool) {
348
349 // We don't need to synchronously wait until we have released all the locks (or the quorum)
350 // (a subsequent lock will retry automatically in case it would fail to get quorum)
351
352 for index, c := range clnts {
353
354 if isLocked(locks[index]) {
355 // broadcast lock release to all nodes that granted the lock
356 sendRelease(c, name, locks[index], isReadLock)
357 }
358 }
359 }
360
361 // ForceUnlock will forcefully clear a write or read lock.
362 func (dm *DRWMutex) ForceUnlock() {
363
364 {
365 dm.m.Lock()
366 defer dm.m.Unlock()
367
368 // Clear write locks array
369 dm.writeLocks = make([]string, dnodeCount)
370 // Clear read locks array
371 dm.readersLocks = nil
372 }
373
374 for _, c := range clnts {
375 // broadcast lock release to all nodes that granted the lock
376 sendRelease(c, dm.Name, "", false)
377 }
378 }
379
380 // sendRelease sends a release message to a node that previously granted a lock
381 func sendRelease(c NetLocker, name, uid string, isReadLock bool) {
382
383 backOffArray := []time.Duration{
384 30 * time.Second, // 30 secs
385 1 * time.Minute, // 1 min
386 3 * time.Minute, // 3 min
387 10 * time.Minute, // 10 min
388 30 * time.Minute, // 30 min
389 1 * time.Hour, // 1 hour
390 }
391
392 go func(c NetLocker, name string) {
393
394 for _, backOff := range backOffArray {
395
396 // All client methods issuing RPCs are thread-safe and goroutine-safe,
397 // i.e. it is safe to call them from multiple concurrently running goroutines.
398 args := LockArgs{
399 UID: uid,
400 Resource: name,
401 ServerAddr: clnts[ownNode].ServerAddr(),
402 ServiceEndpoint: clnts[ownNode].ServiceEndpoint(),
403 }
404
405 var err error
406 if len(uid) == 0 {
407 if _, err = c.ForceUnlock(args); err != nil {
408 log("Unable to call ForceUnlock", err)
409 }
410 } else if isReadLock {
411 if _, err = c.RUnlock(args); err != nil {
412 log("Unable to call RUnlock", err)
413 }
414 } else {
415 if _, err = c.Unlock(args); err != nil {
416 log("Unable to call Unlock", err)
417 }
418 }
419
420 if err != nil {
421 // Ignore if err is net.Error and it is occurred due to timeout.
422 // The cause could have been server timestamp mismatch or server may have restarted.
423 // FIXME: This is minio specific behaviour and we would need a way to make it generically.
424 if nErr, ok := err.(net.Error); ok && nErr.Timeout() {
425 err = nil
426 }
427 }
428
429 if err == nil {
430 return
431 }
432
433 // Wait..
434 time.Sleep(backOff)
435 }
436 }(c, name)
437 }
438
439 // DRLocker returns a sync.Locker interface that implements
440 // the Lock and Unlock methods by calling drw.RLock and drw.RUnlock.
441 func (dm *DRWMutex) DRLocker() sync.Locker {
442 return (*drlocker)(dm)
443 }
444
445 type drlocker DRWMutex
446
447 func (dr *drlocker) Lock() { (*DRWMutex)(dr).RLock() }
448 func (dr *drlocker) Unlock() { (*DRWMutex)(dr).RUnlock() }