| 1 | // Copyright 2015 CNI authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package disk |
| 16 | |
| 17 | import ( |
| 18 | "os" |
| 19 | "path" |
| 20 | |
| 21 | "github.com/alexflint/go-filemutex" |
| 22 | ) |
| 23 | |
| 24 | // FileLock wraps os.File to be used as a lock using flock |
| 25 | type FileLock struct { |
| 26 | f *filemutex.FileMutex |
| 27 | } |
| 28 | |
| 29 | // NewFileLock opens file/dir at path and returns unlocked FileLock object |
| 30 | func NewFileLock(lockPath string) (*FileLock, error) { |
| 31 | fi, err := os.Stat(lockPath) |
| 32 | if err != nil { |
| 33 | return nil, err |
| 34 | } |
| 35 | |
| 36 | if fi.IsDir() { |
| 37 | lockPath = path.Join(lockPath, "lock") |
| 38 | } |
| 39 | |
| 40 | f, err := filemutex.New(lockPath) |
| 41 | if err != nil { |
| 42 | return nil, err |
| 43 | } |
| 44 | |
| 45 | return &FileLock{f}, nil |
| 46 | } |
| 47 | |
| 48 | func (l *FileLock) Close() error { |
| 49 | return l.f.Close() |
| 50 | } |
| 51 | |
| 52 | // Lock acquires an exclusive lock |
| 53 | func (l *FileLock) Lock() error { |
| 54 | return l.f.Lock() |
| 55 | } |
| 56 | |
| 57 | // Unlock releases the lock |
| 58 | func (l *FileLock) Unlock() error { |
| 59 | return l.f.Unlock() |
| 60 | } |