github.imxd.top/hashicorp/consul@v1.4.5/agent/mock/notify.go (about)

     1  package mock
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  
     7  	"github.com/hashicorp/consul/types"
     8  )
     9  
    10  type Notify struct {
    11  	updated chan int
    12  
    13  	// A guard to protect an access to the internal attributes
    14  	// of the notification mock in order to prevent panics
    15  	// raised by the race conditions detector.
    16  	sync.RWMutex
    17  	state   map[types.CheckID]string
    18  	updates map[types.CheckID]int
    19  	output  map[types.CheckID]string
    20  }
    21  
    22  func NewNotify() *Notify {
    23  	return &Notify{
    24  		state:   make(map[types.CheckID]string),
    25  		updates: make(map[types.CheckID]int),
    26  		output:  make(map[types.CheckID]string),
    27  	}
    28  }
    29  
    30  func NewNotifyChan() (*Notify, chan int) {
    31  	n := &Notify{
    32  		updated: make(chan int),
    33  		state:   make(map[types.CheckID]string),
    34  		updates: make(map[types.CheckID]int),
    35  		output:  make(map[types.CheckID]string),
    36  	}
    37  	return n, n.updated
    38  }
    39  
    40  func (m *Notify) sprintf(v interface{}) string {
    41  	m.RLock()
    42  	defer m.RUnlock()
    43  	return fmt.Sprintf("%v", v)
    44  }
    45  
    46  func (m *Notify) StateMap() string   { return m.sprintf(m.state) }
    47  func (m *Notify) UpdatesMap() string { return m.sprintf(m.updates) }
    48  func (m *Notify) OutputMap() string  { return m.sprintf(m.output) }
    49  
    50  func (m *Notify) UpdateCheck(id types.CheckID, status, output string) {
    51  	m.Lock()
    52  	m.state[id] = status
    53  	old := m.updates[id]
    54  	m.updates[id] = old + 1
    55  	m.output[id] = output
    56  	m.Unlock()
    57  
    58  	if m.updated != nil {
    59  		m.updated <- 1
    60  	}
    61  }
    62  
    63  // State returns the state of the specified health-check.
    64  func (m *Notify) State(id types.CheckID) string {
    65  	m.RLock()
    66  	defer m.RUnlock()
    67  	return m.state[id]
    68  }
    69  
    70  // Updates returns the count of updates of the specified health-check.
    71  func (m *Notify) Updates(id types.CheckID) int {
    72  	m.RLock()
    73  	defer m.RUnlock()
    74  	return m.updates[id]
    75  }
    76  
    77  // Output returns an output string of the specified health-check.
    78  func (m *Notify) Output(id types.CheckID) string {
    79  	m.RLock()
    80  	defer m.RUnlock()
    81  	return m.output[id]
    82  }