func()

in pkg/dataplane/reloadCredentials.go [93:145]


func (r *reloadingCredential) start(ctx context.Context, credentialFile string) error {
	// set up the file watcher, call load() when we see events or on some timer in case no events are delivered
	fileWatcher, err := fsnotify.NewWatcher()
	if err != nil {
		return fmt.Errorf("failed to create file watcher: %w", err)
	}
	// we close the file watcher if adding the file to watch fails.
	// this will also close the new go routine created to watch the file
	err = fileWatcher.Add(credentialFile)
	if err != nil {
		if closeErr := fileWatcher.Close(); closeErr != nil {
			r.logger.Error(err, "failed to close file watcher")
		}
		return fmt.Errorf("failed to add credential file to file watcher: %w", err)
	}

	go func() {
		defer func() {
			if err := fileWatcher.Close(); err != nil {
				r.logger.Error(err, "failed to close file watcher")
			}
		}()
		defer r.ticker.Stop()
		for {
			select {
			case event, ok := <-fileWatcher.Events:
				if !ok {
					r.logger.Info("stopping credential reloader since file watcher has no events")
					return
				}
				if event.Op.Has(fsnotify.Write) {
					if err := r.load(credentialFile); err != nil {
						r.logger.Error(err, "failed to reload credential after file event")
					}
				}
			case <-r.ticker.C:
				if err := r.load(credentialFile); err != nil {
					r.logger.Error(err, "failed to reload credential periodically")
				}
			case err, ok := <-fileWatcher.Errors:
				if !ok {
					r.logger.Info("stopping credential reloader since file watcher has no events")
					return
				}
				r.logger.Error(err, "recieved an error from the file watcher")
			case <-ctx.Done():
				r.logger.Info("user signaled context cancel, stopping credential reloader")
				return
			}
		}
	}()
	return nil
}