git.iko.soy/typeable/oauth2-proxy
on ea261ca help sign in
80 lines 2.3 kB history raw
1// +build go1.3,!plan9,!solaris
3package main
5import (
6 "os"
7 "path/filepath"
8 "time"
10 "github.com/fsnotify/fsnotify"
12 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
15// WaitForReplacement waits for a file to exist on disk and then starts a watch
16// for the file
17func WaitForReplacement(filename string, op fsnotify.Op,
18 watcher *fsnotify.Watcher) {
19 const sleepInterval = 50 * time.Millisecond
21 // Avoid a race when fsnofity.Remove is preceded by fsnotify.Chmod.
22 if op&fsnotify.Chmod != 0 {
23 time.Sleep(sleepInterval)
24 }
25 for {
26 if _, err := os.Stat(filename); err == nil {
27 if err := watcher.Add(filename); err == nil {
28 logger.Printf("watching resumed for %s", filename)
29 return
30 }
31 }
32 time.Sleep(sleepInterval)
33 }
36// WatchForUpdates performs an action every time a file on disk is updated
37func WatchForUpdates(filename string, done <-chan bool, action func()) {
38 filename = filepath.Clean(filename)
39 watcher, err := fsnotify.NewWatcher()
40 if err != nil {
41 logger.Fatal("failed to create watcher for ", filename, ": ", err)
42 }
43 go func() {
44 defer func(w *fsnotify.Watcher) {
45 cerr := w.Close()
46 if cerr != nil {
47 logger.Fatalf("error closing watcher: %v", err)
48 }
49 }(watcher)
50 for {
51 select {
52 case <-done:
53 logger.Printf("Shutting down watcher for: %s", filename)
54 return
55 case event := <-watcher.Events:
56 // On Arch Linux, it appears Chmod events precede Remove events,
57 // which causes a race between action() and the coming Remove event.
58 // If the Remove wins, the action() (which calls
59 // UserMap.LoadAuthenticatedEmailsFile()) crashes when the file
60 // can't be opened.
61 if event.Op&(fsnotify.Remove|fsnotify.Rename|fsnotify.Chmod) != 0 {
62 logger.Printf("watching interrupted on event: %s", event)
63 err = watcher.Remove(filename)
64 if err != nil {
65 logger.Printf("error removing watcher on %s: %v", filename, err)
66 }
67 WaitForReplacement(filename, event.Op, watcher)
68 }
69 logger.Printf("reloading after event: %s", event)
70 action()
71 case err = <-watcher.Errors:
72 logger.Errorf("error watching %s: %s", filename, err)
73 }
74 }
75 }()
76 if err = watcher.Add(filename); err != nil {
77 logger.Fatal("failed to add ", filename, " to watcher: ", err)
78 }
79 logger.Printf("watching %s for updates", filename)