Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fsnotify file watcher #41

Merged
merged 6 commits into from
Feb 24, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ test:
lint:
golangci-lint run ./...

format:
go fmt ./...

proto:
@ if ! which protoc > /dev/null; then \
echo "error: protoc not installed" >&2; \
Expand Down
2 changes: 1 addition & 1 deletion blazar.sample.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ http-port = 1234
grpc-port = 5678

[watchers]
# Interval to poll for upgrade-info.json
# Interval to poll for upgrade-info.json. If zero (0) blazar will utilize fsnotify to watch the file, instaead of polling at given interval.
# Interpreted as Go's time.Duration
upgrade-info-interval = "300ms"
# Interval to poll the chain for the last height
Expand Down
16 changes: 14 additions & 2 deletions internal/pkg/chain_watcher/upgrades_info_watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,19 @@ type NewUpgradeInfo struct {

func NewUpgradeInfoWatcher(ctx context.Context, upgradeInfoFilePath string, interval time.Duration) (*UpgradesInfoWatcher, error) {
logger := log.FromContext(ctx)
exists, fw, err := file_watcher.NewFileWatcher(logger, upgradeInfoFilePath, interval)
var (
exists bool
fw file_watcher.FileWatcher
err error
)

if interval == 0 {
exists, fw, err = file_watcher.NewNotifyFileWatcher(logger, upgradeInfoFilePath)
logger.Info("Selected notify file watcher")
} else {
exists, fw, err = file_watcher.NewPollingFileWatcher(logger, upgradeInfoFilePath, interval)
logger.Info("Selected polling file watcher")
}
if err != nil {
return nil, errors.Wrapf(err, "error creating file watcher for %s", upgradeInfoFilePath)
}
Expand All @@ -54,7 +66,7 @@ func NewUpgradeInfoWatcher(ctx context.Context, upgradeInfoFilePath string, inte

go func() {
for {
newEvent := <-fw.ChangeEvents
newEvent := <-fw.ChangeEvents()
if newEvent.Error != nil {
panic(errors.Wrapf(newEvent.Error, "upgrade info watcher's file watcher observed an error"))
}
Expand Down
4 changes: 2 additions & 2 deletions internal/pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -460,8 +460,8 @@ func (cfg *Config) ValidateAll() error {
return errors.New("http-port cannot be 0")
}

if cfg.Watchers.UIInterval <= 0 {
return errors.New("watchers.upgrade-info-interval cannot be less than or equal to 0")
if cfg.Watchers.UIInterval < 0 {
return errors.New("watchers.upgrade-info-interval cannot be less than 0")
}

if cfg.Watchers.HInterval < 0 {
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/daemon/daemon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ func generateConfig(t *testing.T, tempDir, serviceName string, grpcPort, cometbf
UpgradeMode: config.UpgradeInComposeFile,
Host: "dummy",
Watchers: config.Watchers{
UIInterval: time.Millisecond * 5,
UIInterval: 0, // NotifyFileWatcher is enabled
HInterval: time.Second * 0,
HTimeout: 20 * time.Second,
UPInterval: time.Minute * 5,
Expand Down
99 changes: 9 additions & 90 deletions internal/pkg/file_watcher/file_watcher.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
package file_watcher

import (
"os"
"time"

"blazar/internal/pkg/errors"
"blazar/internal/pkg/log"
)
import "os"

type FileChangeEvent int

Expand All @@ -21,90 +15,15 @@ type NewFileChangeEvent struct {
Error error
}

type FileWatcher struct {
// full path to a watched file
lastModTime time.Time
exists bool
ChangeEvents <-chan NewFileChangeEvent
cancel chan<- struct{}
type FileWatcher interface {
ChangeEvents() <-chan NewFileChangeEvent
Cancel()
}

// Returns if the file exists, file watcher, error
func NewFileWatcher(logger *log.MultiLogger, filepath string, interval time.Duration) (bool, *FileWatcher, error) {
// In case file doesn't exist, modTime will be "zero"
// so we can still use it to check for "file change"
// as modTime of created file will be be greater than this
initExists, initModTime, err := getFileStatus(filepath)
if err != nil {
return false, nil, errors.Wrapf(err, "failed to check %s status", filepath)
func fileExists(file string) (bool, error) {
_, err := os.Stat(file)
if os.IsNotExist(err) {
return false, nil
}

events := make(chan NewFileChangeEvent)
cancel := make(chan struct{})

fw := &FileWatcher{
lastModTime: initModTime,
exists: initExists,
ChangeEvents: events,
cancel: cancel,
}

go func() {
ticker := time.NewTicker(interval)
for {
select {
case <-ticker.C:
var newEvent NewFileChangeEvent
exists, modTime, err := getFileStatus(filepath)
if err != nil {
newEvent.Error = err
} else {
if exists != fw.exists {
if exists {
fw.lastModTime = modTime
newEvent.Event = FileCreated
} else {
newEvent.Event = FileRemoved
}
fw.exists = exists
} else if modTime.After(fw.lastModTime) {
fw.lastModTime = modTime
newEvent.Event = FileModified
}
}
select {
case events <- newEvent:
// to prevent deadlock with events channel
case <-cancel:
logger.Debug("File watcher exiting")
return
}
// this isn't necessary since we exit in the above select statement
// but this will help in early exit in case cancel is called before the ticker fires
case <-cancel:
logger.Debug("File watcher exiting")
return
}
}
}()
return initExists, fw, nil
}

func (fw *FileWatcher) Cancel() {
fw.cancel <- struct{}{}
}

// Checks if the file exists and returns the timestamp of the last modification
// returns exists, modTime, error
func getFileStatus(file string) (bool, time.Time, error) {
stat, err := os.Stat(file)

switch {
case os.IsNotExist(err):
return false, time.Time{}, nil
case err != nil:
return false, time.Time{}, err
}

return true, stat.ModTime(), nil
return err == nil, err
}
Loading