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