lockfile.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. /*
  10. Package lockutil contains a file based lock which can be used to lock file resources
  11. across different processes. The lock file is monitored by a Go routine. Invalidating
  12. the lock file (e.g. just writing a single character to it) causes the Go routine
  13. to exit. A client can check if the lockfile is still being monitored by calling
  14. WatcherRunning().
  15. */
  16. package lockutil
  17. import (
  18. "errors"
  19. "fmt"
  20. "os"
  21. "sync"
  22. "time"
  23. )
  24. /*
  25. LockFile data structure
  26. */
  27. type LockFile struct {
  28. filename string // Filename for LockFile
  29. timestamp int64 // Timestamp to uniquely indentify the lockfile
  30. interval time.Duration // Interval with which the file should be watched
  31. errorChan chan error // Error communication channel with watcher goroutine
  32. running bool // Flag to indicate that a lockfile is being watched
  33. mutex *sync.Mutex
  34. }
  35. /*
  36. NewLockFile creates a new LockFile which and watch it in given intervals.
  37. */
  38. func NewLockFile(filename string, interval time.Duration) *LockFile {
  39. return &LockFile{filename, time.Now().UnixNano(), interval, nil, false, &sync.Mutex{}}
  40. }
  41. /*
  42. watch is the internal watcher goroutine function.
  43. */
  44. func (lf *LockFile) watch() {
  45. // Attempt to read the lockfile - no error checking since the next write
  46. // lockfile call will catch any file related errors
  47. res, _ := lf.checkLockfile()
  48. if err := lf.writeLockfile(); err != nil {
  49. lf.errorChan <- err
  50. return
  51. }
  52. if res != 0 {
  53. time.Sleep(lf.interval * 10)
  54. // If we have overwritten an existing timestamp then check
  55. // if it was overwritten again by another process after some time
  56. res, err := lf.checkLockfile()
  57. if res != lf.timestamp || err != nil {
  58. lf.errorChan <- errors.New(fmt.Sprint(
  59. "Could not write lockfile - read result after writing: ", res,
  60. "(expected: ", lf.timestamp, ")", err))
  61. return
  62. }
  63. }
  64. // Signal that all is well
  65. lf.SetWatcherRunning(true)
  66. lf.errorChan <- nil
  67. for lf.WatcherRunning() {
  68. // Wakeup every interval and read the file
  69. time.Sleep(lf.interval)
  70. res, err := lf.checkLockfile()
  71. if err != nil {
  72. // Shut down if we get an error back
  73. lf.SetWatcherRunning(false)
  74. lf.errorChan <- err
  75. return
  76. }
  77. if res != lf.timestamp {
  78. // Attempt to write the timestamp again - no error checking
  79. // if it fails we'll try again next time
  80. lf.writeLockfile()
  81. }
  82. }
  83. // At this point lf.running is false - remove lockfile and return
  84. lf.errorChan <- os.Remove(lf.filename)
  85. }
  86. /*
  87. Write a timestamp to the lockfile
  88. */
  89. func (lf *LockFile) writeLockfile() error {
  90. lf.mutex.Lock()
  91. defer lf.mutex.Unlock()
  92. file, err := os.OpenFile(lf.filename, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0660)
  93. if err != nil {
  94. return err
  95. }
  96. defer file.Close()
  97. data := make([]byte, 8)
  98. data[0] = byte(lf.timestamp >> 56)
  99. data[1] = byte(lf.timestamp >> 48)
  100. data[2] = byte(lf.timestamp >> 40)
  101. data[3] = byte(lf.timestamp >> 32)
  102. data[4] = byte(lf.timestamp >> 24)
  103. data[5] = byte(lf.timestamp >> 16)
  104. data[6] = byte(lf.timestamp >> 8)
  105. data[7] = byte(lf.timestamp >> 0)
  106. _, err = file.Write(data)
  107. return err
  108. }
  109. /*
  110. Try to read a timestamp from a lockfile
  111. */
  112. func (lf *LockFile) checkLockfile() (int64, error) {
  113. lf.mutex.Lock()
  114. defer lf.mutex.Unlock()
  115. file, err := os.OpenFile(lf.filename, os.O_RDONLY, 0660)
  116. if err != nil {
  117. if os.IsNotExist(err) {
  118. return 0, nil
  119. }
  120. return 0, err
  121. }
  122. defer file.Close()
  123. // Read timestamp
  124. timestamp := make([]byte, 8)
  125. i, err := file.Read(timestamp)
  126. if i != 8 {
  127. return 0, errors.New(fmt.Sprint("Unexpected timestamp value found in lockfile:", timestamp))
  128. }
  129. return (int64(timestamp[0]) << 56) |
  130. (int64(timestamp[1]) << 48) |
  131. (int64(timestamp[2]) << 40) |
  132. (int64(timestamp[3]) << 32) |
  133. (int64(timestamp[4]) << 24) |
  134. (int64(timestamp[5]) << 16) |
  135. (int64(timestamp[6]) << 8) |
  136. (int64(timestamp[7]) << 0), err
  137. }
  138. /*
  139. Start creates the lockfile and starts watching it.
  140. */
  141. func (lf *LockFile) Start() error {
  142. // Do nothing if the lockfile is already being watched
  143. if lf.WatcherRunning() {
  144. return nil
  145. }
  146. // Set the running flag and kick off the watcher goroutine
  147. lf.errorChan = make(chan error)
  148. go lf.watch()
  149. return <-lf.errorChan
  150. }
  151. /*
  152. WatcherRunning returns if the watcher goroutine is running.
  153. */
  154. func (lf *LockFile) WatcherRunning() bool {
  155. lf.mutex.Lock()
  156. defer lf.mutex.Unlock()
  157. return lf.running
  158. }
  159. /*
  160. SetWatcherRunning sets if the watcher goroutine is running.
  161. */
  162. func (lf *LockFile) SetWatcherRunning(state bool) {
  163. lf.mutex.Lock()
  164. defer lf.mutex.Unlock()
  165. lf.running = state
  166. }
  167. /*
  168. Finish watching a lockfile and return once the watcher goroutine has finished.
  169. */
  170. func (lf *LockFile) Finish() error {
  171. var err error
  172. // Do nothing if the lockfile is not being watched
  173. if !lf.WatcherRunning() {
  174. // Clean up if there is a channel still open
  175. if lf.errorChan != nil {
  176. err = <-lf.errorChan
  177. lf.errorChan = nil
  178. }
  179. return err
  180. }
  181. // Signale the watcher goroutine to stop
  182. lf.SetWatcherRunning(false)
  183. // Wait for the goroutine to finish
  184. err = <-lf.errorChan
  185. lf.errorChan = nil
  186. return err
  187. }