Lock acquire a file lock. We achieve this by opening a db for the given filePath. Internally, leveldb acquires a file lock while opening a db. If the db is opened again by the same or another process, error would be returned. When the db is closed or the owner process dies, the lock would be release
()
| 204 | // functionality to acquire and release file lock as the leveldb |
| 205 | // supports this for Windows, Solaris, and Unix. |
| 206 | func (f *FileLock) Lock() error { |
| 207 | dbOpts := &opt.Options{} |
| 208 | var err error |
| 209 | var dirEmpty bool |
| 210 | if dirEmpty, err = fileutil.CreateDirIfMissing(f.filePath); err != nil { |
| 211 | panic(fmt.Sprintf("Error creating dir if missing: %s", err)) |
| 212 | } |
| 213 | dbOpts.ErrorIfMissing = !dirEmpty |
| 214 | db, err := leveldb.OpenFile(f.filePath, dbOpts) |
| 215 | if err != nil && err == syscall.EAGAIN { |
| 216 | return errors.Errorf("lock is already acquired on file %s", f.filePath) |
| 217 | } |
| 218 | if err != nil { |
| 219 | panic(fmt.Sprintf("Error acquiring lock on file %s: %s", f.filePath, err)) |
| 220 | } |
| 221 | |
| 222 | // only mutate the lock db reference AFTER validating that the lock was held. |
| 223 | f.db = db |
| 224 | |
| 225 | return nil |
| 226 | } |
| 227 | |
| 228 | // Determine if the lock is currently held open. |
| 229 | func (f *FileLock) IsLocked() bool { |