github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/manager/watchapi/server.go (about)

     1  package watchapi
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"sync"
     7  
     8  	"github.com/docker/swarmkit/manager/state/store"
     9  )
    10  
    11  var (
    12  	errAlreadyRunning = errors.New("broker is already running")
    13  	errNotRunning     = errors.New("broker is not running")
    14  )
    15  
    16  // Server is the store API gRPC server.
    17  type Server struct {
    18  	store     *store.MemoryStore
    19  	mu        sync.Mutex
    20  	pctx      context.Context
    21  	cancelAll func()
    22  }
    23  
    24  // NewServer creates a store API server.
    25  func NewServer(store *store.MemoryStore) *Server {
    26  	return &Server{
    27  		store: store,
    28  	}
    29  }
    30  
    31  // Start starts the watch server.
    32  func (s *Server) Start(ctx context.Context) error {
    33  	s.mu.Lock()
    34  	defer s.mu.Unlock()
    35  
    36  	if s.cancelAll != nil {
    37  		return errAlreadyRunning
    38  	}
    39  
    40  	s.pctx, s.cancelAll = context.WithCancel(ctx)
    41  	return nil
    42  }
    43  
    44  // Stop stops the watch server.
    45  func (s *Server) Stop() error {
    46  	s.mu.Lock()
    47  	defer s.mu.Unlock()
    48  
    49  	if s.cancelAll == nil {
    50  		return errNotRunning
    51  	}
    52  	s.cancelAll()
    53  	s.cancelAll = nil
    54  
    55  	return nil
    56  }