Skip to content

Commit

Permalink
improve config error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoblurye committed Apr 12, 2022
1 parent e66aa85 commit d88f4f4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
26 changes: 18 additions & 8 deletions tinylb/loadbalancer.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ func Open(configPath string, log *logrus.Logger) (*LoadBalancer, error) {
targetGroups: make(map[string]*TargetGroup),
log: log,
}
lb.ReloadConfig()
err := lb.ReloadConfig()
if err != nil {
return nil, err
}

go lb.configWatcher()

return lb, nil
Expand Down Expand Up @@ -139,22 +143,24 @@ func (lb *LoadBalancer) Close() error {
return nil
}

func (lb *LoadBalancer) ReloadConfig() {
func (lb *LoadBalancer) ReloadConfig() error {
configFile, err := os.Open(lb.configPath)
if err != nil {
lb.log.Errorln("error opening config file: ", err)
return err
}
defer configFile.Close()

config, err := LoadConfig(configFile)
if err != nil {
lb.log.Errorln("error loading config: ", err)
return err
}

err = lb.UpdateConfig(*config)
if err != nil {
lb.log.Errorln("error updating config: ", err)
return err
}

return nil
}

// configWatcher listens for config file changes at the load balancer's configPath.
Expand All @@ -181,18 +187,22 @@ func (lb *LoadBalancer) configWatcher() {
case <-time.After(1 * time.Second):
continue
case event := <-watcher.Events:
var err error
// Support k8s configmap updates, which look like removals.
if event.Op&fsnotify.Remove == fsnotify.Remove {
watcher.Remove(event.Name)
watcher.Add(lb.configPath)
lb.ReloadConfig()
err = lb.ReloadConfig()
}
// Support normal file updates.
if event.Op&fsnotify.Write == fsnotify.Write {
lb.ReloadConfig()
err = lb.ReloadConfig()
}
if err != nil {
lb.log.Error("error reloading config: ", err)
}
case err := <-watcher.Errors:
lb.log.Errorln(err)
lb.log.Error("error watching config: ", err)
}
}

Expand Down
4 changes: 4 additions & 0 deletions tinylb/tinylb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@ func countTargetHits(ctx context.Context, targetGroup *TargetGroup) int {
}

func TestLoadBalancerOpen(t *testing.T) {
// Open errors if the config file doesn't exist
_, err := Open("foo.json", log)
assert.NotNil(t, err)

configFile, err := ioutil.TempFile("", "config.*.json")
if err != nil {
log.Fatal(err)
Expand Down

0 comments on commit d88f4f4

Please sign in to comment.