github.com/mrwater98/go-ethereum@v1.9.7/accounts/keystore/watch.go (about) 1 // Copyright 2016 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // +build darwin,!ios,cgo freebsd linux,!arm64 netbsd solaris 18 19 package keystore 20 21 import ( 22 "time" 23 24 "github.com/ethereum/go-ethereum/log" 25 "github.com/rjeczalik/notify" 26 ) 27 28 type watcher struct { 29 ac *accountCache 30 starting bool 31 running bool 32 ev chan notify.EventInfo 33 quit chan struct{} 34 } 35 36 func newWatcher(ac *accountCache) *watcher { 37 return &watcher{ 38 ac: ac, 39 ev: make(chan notify.EventInfo, 10), 40 quit: make(chan struct{}), 41 } 42 } 43 44 // starts the watcher loop in the background. 45 // Start a watcher in the background if that's not already in progress. 46 // The caller must hold w.ac.mu. 47 func (w *watcher) start() { 48 if w.starting || w.running { 49 return 50 } 51 w.starting = true 52 go w.loop() 53 } 54 55 func (w *watcher) close() { 56 close(w.quit) 57 } 58 59 func (w *watcher) loop() { 60 defer func() { 61 w.ac.mu.Lock() 62 w.running = false 63 w.starting = false 64 w.ac.mu.Unlock() 65 }() 66 logger := log.New("path", w.ac.keydir) 67 68 if err := notify.Watch(w.ac.keydir, w.ev, notify.All); err != nil { 69 logger.Trace("Failed to watch keystore folder", "err", err) 70 return 71 } 72 defer notify.Stop(w.ev) 73 logger.Trace("Started watching keystore folder") 74 defer logger.Trace("Stopped watching keystore folder") 75 76 w.ac.mu.Lock() 77 w.running = true 78 w.ac.mu.Unlock() 79 80 // Wait for file system events and reload. 81 // When an event occurs, the reload call is delayed a bit so that 82 // multiple events arriving quickly only cause a single reload. 83 var ( 84 debounceDuration = 500 * time.Millisecond 85 rescanTriggered = false 86 debounce = time.NewTimer(0) 87 ) 88 // Ignore initial trigger 89 if !debounce.Stop() { 90 <-debounce.C 91 } 92 defer debounce.Stop() 93 for { 94 select { 95 case <-w.quit: 96 return 97 case <-w.ev: 98 // Trigger the scan (with delay), if not already triggered 99 if !rescanTriggered { 100 debounce.Reset(debounceDuration) 101 rescanTriggered = true 102 } 103 case <-debounce.C: 104 w.ac.scanAccounts() 105 rescanTriggered = false 106 } 107 } 108 }