Debian Codegraph @

api/v0/healthchecker/slave_health_checker.go

raw symbols SCIP
1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package healthchecker
20
21 import (
22 "errors"
23 "fmt"
24 "net/http"
25 "sync"
26 "sync/atomic"
27 "time"
28
29 log "github.com/golang/glog"
30 "github.com/mesos/mesos-go/api/v0/upid"
31 )
32
33 const (
34 defaultTimeout = time.Second
35 defaultCheckDuration = time.Second
36 defaultThreshold = 5
37 )
38
39 var errCheckerStopped = errors.New("aborted HTTP request because checker was asked to stop")
40
41 // SlaveHealthChecker is for checking the slave's health.
42 type SlaveHealthChecker struct {
43 sync.RWMutex
44 slaveUPID *upid.UPID
45 tr *http.Transport
46 client *http.Client
47 threshold int32 // marked unhealthy once continuousUnhealthCount is greater than this
48 checkDuration time.Duration // perform the check at this interval
49 continuousUnhealthyCount int32 // marked unhealthy when this exceeds threshold
50 stop chan struct{}
51 ch chan time.Time
52 paused bool
53 }
54
55 // NewSlaveHealthChecker creates a slave health checker and return a notification channel.
56 // Each time the checker thinks the slave is unhealthy, it will send a notification through the channel.
57 func NewSlaveHealthChecker(slaveUPID *upid.UPID, threshold int, checkDuration time.Duration, timeout time.Duration) *SlaveHealthChecker {
58 tr := &http.Transport{}
59 checker := &SlaveHealthChecker{
60 slaveUPID: slaveUPID,
61 client: &http.Client{Timeout: timeout, Transport: tr},
62 threshold: int32(threshold),
63 checkDuration: checkDuration,
64 stop: make(chan struct{}),
65 ch: make(chan time.Time, 1),
66 tr: tr,
67 }
68 if timeout == 0 {
69 checker.client.Timeout = defaultTimeout
70 }
71 if checkDuration == 0 {
72 checker.checkDuration = defaultCheckDuration
73 }
74 if threshold <= 0 {
75 checker.threshold = defaultThreshold
76 }
77 return checker
78 }
79
80 // Start will start the health checker and returns the notification channel.
81 func (s *SlaveHealthChecker) Start() <-chan time.Time {
82 go func() {
83 t := time.NewTicker(s.checkDuration)
84 defer t.Stop()
85 for {
86 select {
87 case <-t.C:
88 select {
89 case <-s.stop:
90 return
91 default:
92 // continue
93 }
94 if paused, slavepid := func() (x bool, y upid.UPID) {
95 s.RLock()
96 defer s.RUnlock()
97 x = s.paused
98 if s.slaveUPID != nil {
99 y = *s.slaveUPID
100 }
101 return
102 }(); !paused {
103 s.doCheck(slavepid)
104 }
105 case <-s.stop:
106 return
107 }
108 }
109 }()
110 return s.ch
111 }
112
113 // Pause will pause the slave health checker.
114 func (s *SlaveHealthChecker) Pause() {
115 s.Lock()
116 defer s.Unlock()
117 s.paused = true
118 }
119
120 // Continue will continue the slave health checker with a new slave upid.
121 func (s *SlaveHealthChecker) Continue(slaveUPID *upid.UPID) {
122 s.Lock()
123 defer s.Unlock()
124 s.paused = false
125 s.slaveUPID = slaveUPID
126 }
127
128 // Stop will stop the slave health checker.
129 // It should be called only once during the life span of the checker.
130 func (s *SlaveHealthChecker) Stop() {
131 close(s.stop)
132 }
133
134 type errHttp struct{ StatusCode int }
135
136 func (e *errHttp) Error() string { return fmt.Sprintf("http error code: %d", e.StatusCode) }
137
138 func (s *SlaveHealthChecker) doCheck(pid upid.UPID) {
139 unhealthy := false
140 path := fmt.Sprintf("http://%s:%s/%s/health", pid.Host, pid.Port, pid.ID)
141 req, err := http.NewRequest("HEAD", path, nil)
142 req.Close = true
143 err = s.httpDo(req, func(resp *http.Response, err error) error {
144 if err != nil {
145 return err
146 }
147 defer resp.Body.Close()
148 if resp.StatusCode != http.StatusOK {
149 return &errHttp{resp.StatusCode}
150 }
151 return nil
152 })
153 select {
154 case <-s.stop:
155 return
156 default:
157 }
158 if err != nil {
159 log.Errorf("Failed to request the health path: %v", err)
160 unhealthy = true
161 }
162 if unhealthy {
163 x := atomic.AddInt32(&s.continuousUnhealthyCount, 1)
164 if x >= s.threshold {
165 select {
166 case s.ch <- time.Now(): // If no one is receiving the channel, then just skip it.
167 default:
168 }
169 atomic.StoreInt32(&s.continuousUnhealthyCount, 0)
170 }
171 return
172 }
173 atomic.StoreInt32(&s.continuousUnhealthyCount, 0)
174 }
175
176 func (s *SlaveHealthChecker) httpDo(req *http.Request, f func(*http.Response, error) error) error {
177 // Run the HTTP request in a goroutine and pass the response to f.
178 c := make(chan error, 1)
179 go func() { c <- f(s.client.Do(req)) }()
180 select {
181 case <-s.stop:
182 s.tr.CancelRequest(req)
183 <-c // Wait for f to return.
184 return errCheckerStopped
185 case err := <-c:
186 return err
187 }
188 }