github.com/khulnasoft/cli@v0.0.0-20240402070845-01bcad7beefa/cli/command/events_utils.go (about)

     1  package command
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/docker/docker/api/types/events"
     7  	"github.com/sirupsen/logrus"
     8  )
     9  
    10  // EventHandler is abstract interface for user to customize
    11  // own handle functions of each type of events
    12  //
    13  // Deprecated: EventHandler is no longer used, and will be removed in the next release.
    14  type EventHandler interface {
    15  	Handle(action events.Action, h func(events.Message))
    16  	Watch(c <-chan events.Message)
    17  }
    18  
    19  // InitEventHandler initializes and returns an EventHandler
    20  //
    21  // Deprecated: InitEventHandler is no longer used, and will be removed in the next release.
    22  func InitEventHandler() EventHandler {
    23  	return &eventHandler{handlers: make(map[events.Action]func(events.Message))}
    24  }
    25  
    26  type eventHandler struct {
    27  	handlers map[events.Action]func(events.Message)
    28  	mu       sync.Mutex
    29  }
    30  
    31  func (w *eventHandler) Handle(action events.Action, h func(events.Message)) {
    32  	w.mu.Lock()
    33  	w.handlers[action] = h
    34  	w.mu.Unlock()
    35  }
    36  
    37  // Watch ranges over the passed in event chan and processes the events based on the
    38  // handlers created for a given action.
    39  // To stop watching, close the event chan.
    40  func (w *eventHandler) Watch(c <-chan events.Message) {
    41  	for e := range c {
    42  		w.mu.Lock()
    43  		h, exists := w.handlers[e.Action]
    44  		w.mu.Unlock()
    45  		if !exists {
    46  			continue
    47  		}
    48  		logrus.Debugf("event handler: received event: %v", e)
    49  		go h(e)
    50  	}
    51  }