github.com/jlowellwofford/u-root@v1.0.0/pkg/sos/service.go (about)

     1  // Copyright 2018 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sos
     6  
     7  import (
     8  	"fmt"
     9  	"sync"
    10  )
    11  
    12  type Registry map[string]uint
    13  
    14  type SosService struct {
    15  	rWLock   sync.RWMutex
    16  	registry Registry
    17  }
    18  
    19  func (s *SosService) Read(serviceName string) (uint, error) {
    20  	s.rWLock.RLock()
    21  	defer s.rWLock.RUnlock()
    22  	port, exists := s.registry[serviceName]
    23  	if !exists {
    24  		return 0, fmt.Errorf("%v is not in the registry", serviceName)
    25  	}
    26  	return port, nil
    27  }
    28  
    29  func (s *SosService) Register(serviceName string, portNum uint) error {
    30  	s.rWLock.Lock()
    31  	defer s.rWLock.Unlock()
    32  	_, exists := s.registry[serviceName]
    33  	if exists {
    34  		return fmt.Errorf("%v already exists", serviceName)
    35  	}
    36  	s.registry[serviceName] = portNum
    37  	return nil
    38  }
    39  
    40  func (s *SosService) Unregister(serviceName string) {
    41  	s.rWLock.Lock()
    42  	defer s.rWLock.Unlock()
    43  	delete(s.registry, serviceName)
    44  }
    45  
    46  func (s *SosService) SnapshotRegistry() Registry {
    47  	s.rWLock.RLock()
    48  	defer s.rWLock.RUnlock()
    49  	snapshot := make(map[string]uint)
    50  	for name, port := range s.registry {
    51  		snapshot[name] = port
    52  	}
    53  	return snapshot
    54  }
    55  
    56  func NewSosService() *SosService {
    57  	return &SosService{
    58  		registry: make(map[string]uint),
    59  	}
    60  }