git.iko.soy/typeable/oauth2-proxy
on v2.1 help sign in
68 lines 1.8 kB history raw
1// +build go1.3,!plan9,!solaris
3package main
5import (
6 "log"
7 "os"
8 "path/filepath"
9 "time"
11 "gopkg.in/fsnotify.v1"
14func WaitForReplacement(filename string, op fsnotify.Op,
15 watcher *fsnotify.Watcher) {
16 const sleep_interval = 50 * time.Millisecond
18 // Avoid a race when fsnofity.Remove is preceded by fsnotify.Chmod.
19 if op&fsnotify.Chmod != 0 {
20 time.Sleep(sleep_interval)
21 }
22 for {
23 if _, err := os.Stat(filename); err == nil {
24 if err := watcher.Add(filename); err == nil {
25 log.Printf("watching resumed for %s", filename)
26 return
27 }
28 }
29 time.Sleep(sleep_interval)
30 }
33func WatchForUpdates(filename string, done <-chan bool, action func()) {
34 filename = filepath.Clean(filename)
35 watcher, err := fsnotify.NewWatcher()
36 if err != nil {
37 log.Fatal("failed to create watcher for ", filename, ": ", err)
38 }
39 go func() {
40 defer watcher.Close()
41 for {
42 select {
43 case _ = <-done:
44 log.Printf("Shutting down watcher for: %s", filename)
45 break
46 case event := <-watcher.Events:
47 // On Arch Linux, it appears Chmod events precede Remove events,
48 // which causes a race between action() and the coming Remove event.
49 // If the Remove wins, the action() (which calls
50 // UserMap.LoadAuthenticatedEmailsFile()) crashes when the file
51 // can't be opened.
52 if event.Op&(fsnotify.Remove|fsnotify.Rename|fsnotify.Chmod) != 0 {
53 log.Printf("watching interrupted on event: %s", event)
54 watcher.Remove(filename)
55 WaitForReplacement(filename, event.Op, watcher)
56 }
57 log.Printf("reloading after event: %s", event)
58 action()
59 case err := <-watcher.Errors:
60 log.Printf("error watching %s: %s", filename, err)
61 }
62 }
63 }()
64 if err = watcher.Add(filename); err != nil {
65 log.Fatal("failed to add ", filename, " to watcher: ", err)
66 }
67 log.Printf("watching %s for updates", filename)