예제 #1
0
func ExampleNewWatcher() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		for {
			select {
			case ev := <-watcher.Event:
				log.Println("event:", ev)
			case err := <-watcher.Error:
				log.Println("error:", err)
			}
		}
	}()

	err = watcher.Watch("/tmp/foo")
	if err != nil {
		log.Fatal(err)
	}
}
예제 #2
0
// RolesWatch catches filesystem notify events to determine when new roles files are ready to be read
// in and used as new authentication values.
func (rf *RolesFiles) RolesWatch(err_chan chan error, read_signal chan bool) {
	log.Printf("initiate roles watching\n")
	watcher, watcher_err := fsnotify.NewWatcher()
	if watcher_err != nil {
		err_chan <- watcher_err
	}
	watch_err := watcher.Watch(rf.BaseDir)
	if watch_err != nil {
		err_chan <- watch_err
	}
	defer watcher.Close()
	touched_access_file := false
	touched_secret_file := false
	touched_token_file := false
	func() {
		for {
			select {
			case ev := <-watcher.Event:
				func() {
					if ev.IsModify() || ev.IsCreate() {
						ev_s := ev.String()
						// collect events for all of the role files.
						// we only want to read in and reset the
						// strings when all have been written - to
						// do so earlier would leave the strings
						// in an inconsistent state
						if strings.Contains(ev_s, rf.AccessKeyFile) {
							touched_access_file = true
						}
						if strings.Contains(ev_s, rf.SecretFile) {
							touched_secret_file = true
						}
						if strings.Contains(ev_s, rf.TokenFile) {
							touched_token_file = true
						}
						// once we have seen all of the role files trigger
						// events, we want to lock access, read them in,
						// unlock access, and unset our flags
						if touched_access_file &&
							touched_secret_file &&
							touched_token_file {
							// our existing perms should be adequate while
							// we provide for writes of new perms files to
							// finish.
							log.Printf("roles_files.RolesWatch: " +
								"sleep (1) to allow file ops to complete")
							time.Sleep(time.Duration(1) * time.Second)
							roles_err := rf.rolesFilesRead()
							if roles_err != nil {
								e := fmt.Sprintf("roles_files.RolesWatch: "+
									"zeroing all roles on err:%s",
									roles_err.Error())
								log.Printf(e)
								rf.ZeroRoles()
								err_chan <- roles_err
							} else {
								log.Printf("roles_files.RolesWatch: "+
									"succesful re-read on %s\n",
									ev_s)
								touched_access_file = false
								touched_secret_file = false
								touched_token_file = false
								read_signal <- true
							}
						}
					}
				}()
			case err := <-watcher.Error:
				// return an error to the caller via the channel
				err_chan <- err
			}
		}
	}()
	// typically not reached, but signifies normal termination
	log.Printf("terminating roles watching\n")
	err_chan <- nil
}