func()

in pkg/tls/reloader.go [258:327]


func (r *Reloader) watchFiles() {
	r.log.Info().Msg("TLS file watcher loop started")
	for {
		select {
		case event, ok := <-r.watcher.Events:
			if !ok {
				r.log.Info().Msg("Watcher events channel closed")
				return
			}

			r.log.Debug().Str("file", event.Name).Str("op", event.Op.String()).Msg("Detected file event")

			// Handle all relevant file operation events
			if event.Op&(fsnotify.Remove|fsnotify.Create|fsnotify.Write|fsnotify.Rename) != 0 {
				// Special handling for removal/creation
				if event.Op&(fsnotify.Remove|fsnotify.Create) != 0 {
					r.log.Info().Str("file", event.Name).Msg("File removed or created, performing stability checks")

					// Remove from watcher first to avoid duplicate watches
					_ = r.watcher.Remove(event.Name)

					// Wait for file operations to complete
					time.Sleep(1 * time.Second)

					// Try to re-add files to watcher with retries
					maxRetries := 5
					for i := 0; i < maxRetries; i++ {
						if event.Name == r.certFile {
							if r.isFileStable(r.certFile) {
								if err := r.watcher.Add(r.certFile); err != nil {
									r.log.Error().Err(err).Str("file", r.certFile).Msg("Failed to re-add cert file to watcher")
								} else {
									r.log.Debug().Str("file", r.certFile).Msg("Re-added cert file to watcher")
									break
								}
							}
						} else if event.Name == r.keyFile {
							if r.isFileStable(r.keyFile) {
								if err := r.watcher.Add(r.keyFile); err != nil {
									r.log.Error().Err(err).Str("file", r.keyFile).Msg("Failed to re-add key file to watcher")
								} else {
									r.log.Debug().Str("file", r.keyFile).Msg("Re-added key file to watcher")
									break
								}
							}
						}
						if i < maxRetries-1 {
							time.Sleep(500 * time.Millisecond)
						} else {
							logger.Panicf("Failed to re-add file to watcher after %d attempts", maxRetries)
						}
					}
				} else {
					r.log.Info().Str("file", event.Name).Msg("Detected certificate modification")
					time.Sleep(200 * time.Millisecond) // Ensure file is fully written
				}

				// Schedule a reload attempt with debouncing for all types of events
				r.scheduleReloadAttempt()
			}

		case err, ok := <-r.watcher.Errors:
			if !ok {
				r.log.Info().Msg("Watcher errors channel closed")
				return
			}
			r.log.Error().Err(err).Msg("Error in file watcher")
		}
	}
}