Debian Codegraph @

chaos/lock-rpc-server.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 main
18
19 import (
20 "fmt"
21 "log"
22 "sync"
23 "time"
24
25 "github.com/minio/dsync"
26 )
27
28 type lockRequesterInfo struct {
29 writer bool // Bool whether write or read lock
30 serverAddr string // Network address of client claiming lock
31 resource string // RPC path of client claiming lock
32 uid string // Uid to uniquely identify request of client
33 timestamp time.Time // Timestamp set at the time of initialization
34 timeLastCheck time.Time // Timestamp for last check of validity of lock
35 }
36
37 func isWriteLock(lri []lockRequesterInfo) bool {
38 return len(lri) == 1 && lri[0].writer
39 }
40
41 type lockServer struct {
42 mutex sync.Mutex
43 lockMap map[string][]lockRequesterInfo
44 timestamp time.Time // Timestamp set at the time of initialization. Resets naturally on minio server restart.
45 }
46
47 // Lock - rpc handler for (single) write lock operation.
48 func (l *lockServer) Lock(args *dsync.LockArgs, reply *bool) error {
49 l.mutex.Lock()
50 defer l.mutex.Unlock()
51 _, *reply = l.lockMap[args.Resource]
52 if !*reply { // No locks held on the given name, so claim write lock
53 l.lockMap[args.Resource] = []lockRequesterInfo{
54 {
55 writer: true,
56 serverAddr: args.ServerAddr,
57 resource: args.Resource,
58 uid: args.UID,
59 timestamp: time.Now().UTC(),
60 timeLastCheck: time.Now().UTC(),
61 },
62 }
63 }
64 *reply = !*reply // Negate *reply to return true when lock is granted or false otherwise
65 return nil
66 }
67
68 // Unlock - rpc handler for (single) write unlock operation.
69 func (l *lockServer) Unlock(args *dsync.LockArgs, reply *bool) error {
70 l.mutex.Lock()
71 defer l.mutex.Unlock()
72 var lri []lockRequesterInfo
73 if lri, *reply = l.lockMap[args.Resource]; !*reply { // No lock is held on the given name
74 return fmt.Errorf("Unlock attempted on an unlocked entity: %s", args.Resource)
75 }
76 if *reply = isWriteLock(lri); !*reply { // Unless it is a write lock
77 return fmt.Errorf("Unlock attempted on a read locked entity: %s (%d read locks active)", args.Resource, len(lri))
78 }
79 if !l.removeEntry(args.Resource, args.UID, &lri) {
80 return fmt.Errorf("Unlock unable to find corresponding lock for uid: %s", args.UID)
81 }
82 return nil
83 }
84
85 // RLock - rpc handler for read lock operation.
86 func (l *lockServer) RLock(args *dsync.LockArgs, reply *bool) error {
87 l.mutex.Lock()
88 defer l.mutex.Unlock()
89 lrInfo := lockRequesterInfo{
90 writer: false,
91 serverAddr: args.ServerAddr,
92 resource: args.Resource,
93 uid: args.UID,
94 timestamp: time.Now().UTC(),
95 timeLastCheck: time.Now().UTC(),
96 }
97 if lri, ok := l.lockMap[args.Resource]; ok {
98 if *reply = !isWriteLock(lri); *reply { // Unless there is a write lock
99 l.lockMap[args.Resource] = append(l.lockMap[args.Resource], lrInfo)
100 }
101 } else { // No locks held on the given name, so claim (first) read lock
102 l.lockMap[args.Resource] = []lockRequesterInfo{lrInfo}
103 *reply = true
104 }
105 return nil
106 }
107
108 // RUnlock - rpc handler for read unlock operation.
109 func (l *lockServer) RUnlock(args *dsync.LockArgs, reply *bool) error {
110 l.mutex.Lock()
111 defer l.mutex.Unlock()
112 var lri []lockRequesterInfo
113 if lri, *reply = l.lockMap[args.Resource]; !*reply { // No lock is held on the given name
114 return fmt.Errorf("RUnlock attempted on an unlocked entity: %s", args.Resource)
115 }
116 if *reply = !isWriteLock(lri); !*reply { // A write-lock is held, cannot release a read lock
117 return fmt.Errorf("RUnlock attempted on a write locked entity: %s", args.Resource)
118 }
119 if !l.removeEntry(args.Resource, args.UID, &lri) {
120 return fmt.Errorf("RUnlock unable to find corresponding read lock for uid: %s", args.UID)
121 }
122 return nil
123 }
124
125 // ForceUnlock - rpc handler for force unlock operation.
126 func (l *lockServer) ForceUnlock(args *dsync.LockArgs, reply *bool) error {
127 l.mutex.Lock()
128 defer l.mutex.Unlock()
129 if len(args.UID) != 0 {
130 return fmt.Errorf("ForceUnlock called with non-empty UID: %s", args.UID)
131 }
132 if _, ok := l.lockMap[args.Resource]; ok { // Only clear lock when set
133 delete(l.lockMap, args.Resource) // Remove the lock (irrespective of write or read lock)
134 }
135 *reply = true
136 return nil
137 }
138
139 // Expired - rpc handler for expired lock status.
140 func (l *lockServer) Expired(args *dsync.LockArgs, reply *bool) error {
141 l.mutex.Lock()
142 defer l.mutex.Unlock()
143 if lri, ok := l.lockMap[args.Resource]; ok {
144 // Check whether uid is still active for this name
145 for _, entry := range lri {
146 if entry.uid == args.UID {
147 *reply = false // When uid found, lock is still active so return not expired
148 return nil
149 }
150 }
151 }
152 // When we get here, lock is no longer active due to either args.Resource being absent from map
153 // or uid not found for given args.Resource
154 *reply = true
155 return nil
156 }
157
158 // removeEntry either, based on the uid of the lock message, removes a single entry from the
159 // lockRequesterInfo array or the whole array from the map (in case of a write lock or last read lock)
160 func (l *lockServer) removeEntry(name, uid string, lri *[]lockRequesterInfo) bool {
161 // Find correct entry to remove based on uid
162 for index, entry := range *lri {
163 if entry.uid == uid {
164 if len(*lri) == 1 {
165 delete(l.lockMap, name) // Remove the (last) lock
166 } else {
167 // Remove the appropriate read lock
168 *lri = append((*lri)[:index], (*lri)[index+1:]...)
169 l.lockMap[name] = *lri
170 }
171 return true
172 }
173 }
174 return false
175 }
176
177 // Similar to removeEntry but only removes an entry only if the lock entry exists in map.
178 func (l *lockServer) removeEntryIfExists(nlrip nameLockRequesterInfoPair) {
179 // Check if entry is still in map (could have been removed altogether by 'concurrent' (R)Unlock of last entry)
180 if lri, ok := l.lockMap[nlrip.name]; ok {
181 if !l.removeEntry(nlrip.name, nlrip.lri.uid, &lri) {
182 // Remove failed, in case it is a:
183 if nlrip.lri.writer {
184 // Writer: this should never happen as the whole (mapped) entry should have been deleted
185 log.Println("Lock maintenance failed to remove entry for write lock (should never happen)", nlrip.name, nlrip.lri.uid, lri)
186 } // Reader: this can happen if multiple read locks were active and
187 // the one we are looking for has been released concurrently (so it is fine)
188 } // Remove went okay, all is fine
189 }
190 }
191
192 type nameLockRequesterInfoPair struct {
193 name string
194 lri lockRequesterInfo
195 }
196
197 // getLongLivedLocks returns locks that are older than a certain time and
198 // have not been 'checked' for validity too soon enough
199 func getLongLivedLocks(m map[string][]lockRequesterInfo, interval time.Duration) []nameLockRequesterInfoPair {
200
201 rslt := []nameLockRequesterInfoPair{}
202
203 for name, lriArray := range m {
204
205 for idx := range lriArray {
206 // Check whether enough time has gone by since last check
207 if time.Since(lriArray[idx].timeLastCheck) >= interval {
208 rslt = append(rslt, nameLockRequesterInfoPair{name: name, lri: lriArray[idx]})
209 lriArray[idx].timeLastCheck = time.Now()
210 }
211 }
212 }
213
214 return rslt
215 }
216
217 // lockMaintenance loops over locks that have been active for some time and checks back
218 // with the original server whether it is still alive or not
219 //
220 // Following logic inside ignores the errors generated for Dsync.Active operation.
221 // - server at client down
222 // - some network error (and server is up normally)
223 //
224 // We will ignore the error, and we will retry later to get a resolve on this lock
225 func (l *lockServer) lockMaintenance(interval time.Duration) {
226 l.mutex.Lock()
227 // Get list of long lived locks to check for staleness.
228 nlripLongLived := getLongLivedLocks(l.lockMap, interval)
229 l.mutex.Unlock()
230
231 // Validate if long lived locks are indeed clean.
232 for _, nlrip := range nlripLongLived {
233 // Initialize client based on the long live locks.
234 c := newClient(nlrip.lri.serverAddr, nlrip.lri.resource)
235
236 var expired bool
237
238 // Call back to original server to verify whether the lock is still active (based on name & uid)
239 // We will ignore any errors (see above for reasons), such locks will be retried later to get resolved
240 c.Call("Dsync.Expired", &dsync.LockArgs{
241 Resource: nlrip.name,
242 UID: nlrip.lri.uid,
243 }, &expired)
244 c.Close()
245
246 if expired {
247 // The lock is no longer active at server that originated the lock
248 // So remove the lock from the map.
249 l.mutex.Lock()
250 l.removeEntryIfExists(nlrip) // Purge the stale entry if it exists.
251 l.mutex.Unlock()
252 }
253 }
254 }