github.com/sijibomii/docker@v0.0.0-20231230191044-5cf6ca554647/pkg/discovery/memory/memory.go (about)

     1  package memory
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/docker/docker/pkg/discovery"
     7  )
     8  
     9  // Discovery implements a descovery backend that keeps
    10  // data in memory.
    11  type Discovery struct {
    12  	heartbeat time.Duration
    13  	values    []string
    14  }
    15  
    16  func init() {
    17  	Init()
    18  }
    19  
    20  // Init registers the memory backend on demand.
    21  func Init() {
    22  	discovery.Register("memory", &Discovery{})
    23  }
    24  
    25  // Initialize sets the heartbeat for the memory backend.
    26  func (s *Discovery) Initialize(_ string, heartbeat time.Duration, _ time.Duration, _ map[string]string) error {
    27  	s.heartbeat = heartbeat
    28  	s.values = make([]string, 0)
    29  	return nil
    30  }
    31  
    32  // Watch sends periodic discovery updates to a channel.
    33  func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-chan error) {
    34  	ch := make(chan discovery.Entries)
    35  	errCh := make(chan error)
    36  	ticker := time.NewTicker(s.heartbeat)
    37  
    38  	go func() {
    39  		defer close(errCh)
    40  		defer close(ch)
    41  
    42  		// Send the initial entries if available.
    43  		var currentEntries discovery.Entries
    44  		if len(s.values) > 0 {
    45  			var err error
    46  			currentEntries, err = discovery.CreateEntries(s.values)
    47  			if err != nil {
    48  				errCh <- err
    49  			} else {
    50  				ch <- currentEntries
    51  			}
    52  		}
    53  
    54  		// Periodically send updates.
    55  		for {
    56  			select {
    57  			case <-ticker.C:
    58  				newEntries, err := discovery.CreateEntries(s.values)
    59  				if err != nil {
    60  					errCh <- err
    61  					continue
    62  				}
    63  
    64  				// Check if the file has really changed.
    65  				if !newEntries.Equals(currentEntries) {
    66  					ch <- newEntries
    67  				}
    68  				currentEntries = newEntries
    69  			case <-stopCh:
    70  				ticker.Stop()
    71  				return
    72  			}
    73  		}
    74  	}()
    75  
    76  	return ch, errCh
    77  }
    78  
    79  // Register adds a new address to the discovery.
    80  func (s *Discovery) Register(addr string) error {
    81  	s.values = append(s.values, addr)
    82  	return nil
    83  }