|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 NVIDIA CORPORATION. All rights reserved. |
| 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 flock |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + "os" |
| 23 | + "syscall" |
| 24 | + "time" |
| 25 | +) |
| 26 | + |
| 27 | +type Flock struct { |
| 28 | + path string |
| 29 | +} |
| 30 | + |
| 31 | +type AcquireOption func(*acquireConfig) |
| 32 | + |
| 33 | +type acquireConfig struct { |
| 34 | + timeout time.Duration |
| 35 | + pollPeriod time.Duration |
| 36 | +} |
| 37 | + |
| 38 | +func WithTimeout(timeout time.Duration) AcquireOption { |
| 39 | + return func(cfg *acquireConfig) { |
| 40 | + cfg.timeout = timeout |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +func WithPollPeriod(period time.Duration) AcquireOption { |
| 45 | + return func(cfg *acquireConfig) { |
| 46 | + cfg.pollPeriod = period |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +func NewFlock(path string) *Flock { |
| 51 | + return &Flock{ |
| 52 | + path: path, |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// Acquire attempts to acquire an exclusive file lock, polling with the configured |
| 57 | +// PollPeriod until whichever comes first: |
| 58 | +// |
| 59 | +// - lock successfully acquired |
| 60 | +// - timeout (if provided) |
| 61 | +// - external cancellation of context |
| 62 | +// |
| 63 | +// Returns a release function that must be called to unlock the file, typically |
| 64 | +// with defer(). |
| 65 | +// |
| 66 | +// Introduced to protect the work in nodePrepareResource() and |
| 67 | +// nodeUnprepareResource() under a file-based lock because more than one driver |
| 68 | +// pod may be running on a node, but at most one such function must execute at |
| 69 | +// any given time. |
| 70 | +func (l *Flock) Acquire(ctx context.Context, opts ...AcquireOption) (func(), error) { |
| 71 | + cfg := &acquireConfig{ |
| 72 | + // Default: short period to keep lock acquisition rather responsive |
| 73 | + pollPeriod: 200 * time.Millisecond, |
| 74 | + // Default: timeout disabled |
| 75 | + timeout: 0, |
| 76 | + } |
| 77 | + for _, opt := range opts { |
| 78 | + opt(cfg) |
| 79 | + } |
| 80 | + |
| 81 | + f, oerr := os.OpenFile(l.path, os.O_RDWR|os.O_CREATE, 0644) |
| 82 | + if oerr != nil { |
| 83 | + return nil, fmt.Errorf("error opening lock file (%s): %w", l.path, oerr) |
| 84 | + } |
| 85 | + |
| 86 | + t0 := time.Now() |
| 87 | + ticker := time.NewTicker(cfg.pollPeriod) |
| 88 | + defer ticker.Stop() |
| 89 | + |
| 90 | + // Use non-blocking peek with LOCK_NB flag and polling; trade-off: |
| 91 | + // |
| 92 | + // - pro: no need for having to reliably cancel a potentially long-blocking |
| 93 | + // flock() system call (can only be done with signals). |
| 94 | + // - con: lock acquisition time after a release is not immediate, but may |
| 95 | + // take up to PollPeriod amount of time. Not an issue in this context. |
| 96 | + for { |
| 97 | + flerr := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) |
| 98 | + if flerr == nil { |
| 99 | + // Lock acquired. Return release function. An exclusive flock() lock |
| 100 | + // gets released when its file descriptor gets closed (also true |
| 101 | + // when the lock-holding process crashes). |
| 102 | + release := func() { |
| 103 | + f.Close() |
| 104 | + } |
| 105 | + return release, nil |
| 106 | + } |
| 107 | + |
| 108 | + if flerr != syscall.EWOULDBLOCK { |
| 109 | + // May be EBADF, EINTR, EINVAl, ENOLCK, and |
| 110 | + // in general we want an outer retry mechanism |
| 111 | + // to retry in view of any of those. |
| 112 | + f.Close() |
| 113 | + return nil, fmt.Errorf("error acquiring lock (%s): %w", l.path, flerr) |
| 114 | + } |
| 115 | + |
| 116 | + // Lock is currently held by other entity. Check for exit criteria; |
| 117 | + // otherwise retry lock acquisition upon next tick. |
| 118 | + |
| 119 | + if cfg.timeout > 0 && time.Since(t0) > cfg.timeout { |
| 120 | + f.Close() |
| 121 | + return nil, fmt.Errorf("timeout acquiring lock (%s)", l.path) |
| 122 | + } |
| 123 | + |
| 124 | + select { |
| 125 | + case <-ctx.Done(): |
| 126 | + f.Close() |
| 127 | + return nil, fmt.Errorf("error acquiring lock (%s): %w", l.path, ctx.Err()) |
| 128 | + case <-ticker.C: |
| 129 | + // Retry flock(). |
| 130 | + continue |
| 131 | + } |
| 132 | + } |
| 133 | +} |
0 commit comments