github.com/uber/kraken@v0.1.4/lib/healthcheck/monitor.go (about)

     1  // Copyright (c) 2016-2019 Uber Technologies, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  package healthcheck
    15  
    16  import (
    17  	"sync"
    18  	"time"
    19  
    20  	"github.com/uber/kraken/lib/hostlist"
    21  	"github.com/uber/kraken/utils/stringset"
    22  )
    23  
    24  // Monitor performs active health checks asynchronously. Can be used in
    25  // as a hostlist.List.
    26  type Monitor struct {
    27  	config MonitorConfig
    28  	hosts  hostlist.List
    29  	filter Filter
    30  
    31  	mu      sync.RWMutex
    32  	healthy stringset.Set
    33  
    34  	stop chan struct{}
    35  }
    36  
    37  var _ hostlist.List = (*Monitor)(nil)
    38  
    39  // NewMonitor monitors the health of hosts using filter.
    40  func NewMonitor(config MonitorConfig, hosts hostlist.List, filter Filter) *Monitor {
    41  	config.applyDefaults()
    42  	m := &Monitor{
    43  		config:  config,
    44  		hosts:   hosts,
    45  		filter:  filter,
    46  		healthy: hosts.Resolve(),
    47  		stop:    make(chan struct{}),
    48  	}
    49  	go m.loop()
    50  	return m
    51  }
    52  
    53  // Resolve returns the latest healthy hosts.
    54  func (m *Monitor) Resolve() stringset.Set {
    55  	m.mu.RLock()
    56  	defer m.mu.RUnlock()
    57  
    58  	return m.healthy
    59  }
    60  
    61  // Stop stops the monitor.
    62  func (m *Monitor) Stop() {
    63  	close(m.stop)
    64  }
    65  
    66  func (m *Monitor) loop() {
    67  	for {
    68  		select {
    69  		case <-m.stop:
    70  			return
    71  		case <-time.After(m.config.Interval):
    72  			healthy := m.filter.Run(m.hosts.Resolve())
    73  			m.mu.Lock()
    74  			m.healthy = healthy
    75  			m.mu.Unlock()
    76  		}
    77  	}
    78  }