watchConfigFile watches the config file at filename for changes and reloads the config if the file was updated. This function blocks indefinitely; it only quits if the poller has errors for long enough time. The filename passed in must be the actual config file used, not one to be discovered. Each s
(filename, adapterName string)
| 249 | // Each second the config files is loaded and parsed into an object |
| 250 | // and is compared to the last config object that was loaded |
| 251 | func watchConfigFile(filename, adapterName string) { |
| 252 | defer func() { |
| 253 | if err := recover(); err != nil { |
| 254 | log.Printf("[PANIC] watching config file: %v\n%s", err, debug.Stack()) |
| 255 | } |
| 256 | }() |
| 257 | |
| 258 | // make our logger; since config reloads can change the |
| 259 | // default logger, we need to get it dynamically each time |
| 260 | logger := func() *zap.Logger { |
| 261 | return caddy.Log(). |
| 262 | Named("watcher"). |
| 263 | With(zap.String("config_file", filename)) |
| 264 | } |
| 265 | |
| 266 | // get current config |
| 267 | lastCfg, _, _, err := loadConfigWithLogger(nil, filename, adapterName) |
| 268 | if err != nil { |
| 269 | logger().Error("unable to load latest config", zap.Error(err)) |
| 270 | return |
| 271 | } |
| 272 | |
| 273 | logger().Info("watching config file for changes") |
| 274 | |
| 275 | // begin poller |
| 276 | //nolint:staticcheck |
| 277 | for range time.Tick(1 * time.Second) { |
| 278 | // get current config |
| 279 | newCfg, _, _, err := loadConfigWithLogger(nil, filename, adapterName) |
| 280 | if err != nil { |
| 281 | logger().Error("unable to load latest config", zap.Error(err)) |
| 282 | return |
| 283 | } |
| 284 | |
| 285 | // if it hasn't changed, nothing to do |
| 286 | if bytes.Equal(lastCfg, newCfg) { |
| 287 | continue |
| 288 | } |
| 289 | logger().Info("config file changed; reloading") |
| 290 | |
| 291 | // remember the current config |
| 292 | lastCfg = newCfg |
| 293 | |
| 294 | // apply the updated config |
| 295 | err = caddy.Load(lastCfg, false) |
| 296 | if err != nil { |
| 297 | logger().Error("applying latest config", zap.Error(err)) |
| 298 | continue |
| 299 | } |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | // Flags wraps a FlagSet so that typed values |
| 304 | // from flags can be easily retrieved. |