Lock obtains a lock named by the given key. It blocks until the lock can be obtained or an error is returned.
(ctx context.Context, key string)
| 217 | // Lock obtains a lock named by the given key. It blocks |
| 218 | // until the lock can be obtained or an error is returned. |
| 219 | func (s *Storage) Lock(ctx context.Context, key string) error { |
| 220 | start := time.Now() |
| 221 | lockFile := s.lockFileName(key) |
| 222 | |
| 223 | for { |
| 224 | err := s.createLockFile(lockFile) |
| 225 | if err == nil { |
| 226 | // got the lock |
| 227 | return nil |
| 228 | } |
| 229 | |
| 230 | if err.Error() != lockFileExists { |
| 231 | // unexpected error |
| 232 | return helpers.Logger.LogError(helpers.GetRequestID(context.TODO()), "Unable to create lock file in lets encrypt", err, nil) |
| 233 | } |
| 234 | |
| 235 | // lock file already exists |
| 236 | info, err := s.Stat(lockFile) |
| 237 | switch { |
| 238 | case err != nil: |
| 239 | return helpers.Logger.LogError(helpers.GetRequestID(context.TODO()), "Unable to get stats of lock file in lets encrypt", err, nil) |
| 240 | |
| 241 | case s.fileLockIsStale(info): |
| 242 | helpers.Logger.LogWarn(helpers.GetRequestID(context.TODO()), "lets encrypt lock file is in stale state removing and trying again", nil) |
| 243 | if err := s.deleteLockFile(lockFile); err != nil { |
| 244 | return err |
| 245 | } |
| 246 | continue |
| 247 | |
| 248 | case time.Since(start) > staleLockDuration*2: |
| 249 | // should never happen, hopefully |
| 250 | return helpers.Logger.LogError(helpers.GetRequestID(context.TODO()), "Lets encrypt dead lock by passing", fmt.Errorf("possible deadlock: %s passed trying to obtain lock for %s", time.Since(start), key), nil) |
| 251 | |
| 252 | default: |
| 253 | // lockfile exists and is not stale; |
| 254 | // just wait a moment and try again |
| 255 | time.Sleep(fileLockPollInterval) |
| 256 | |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | // Unlock releases the lock for name. |
| 262 | func (s *Storage) Unlock(key string) error { |
no test coverage detected