forked from jaegertracing/jaeger
/
handler.go
144 lines (126 loc) · 3.82 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package healthcheck
import (
"context"
"net"
"net/http"
"strconv"
"sync/atomic"
"go.uber.org/zap"
"github.com/jaegertracing/jaeger/pkg/version"
)
// Status represents the state of the service.
type Status int
const (
// Unavailable indicates the service is not able to handle requests
Unavailable Status = iota
// Ready indicates the service is ready to handle requests
Ready
// Broken indicates that the healthcheck itself is broken, not serving HTTP
Broken
)
func (s Status) String() string {
switch s {
case Unavailable:
return "unavailable"
case Ready:
return "ready"
case Broken:
return "broken"
default:
return "unknown"
}
}
// HealthCheck provides an HTTP endpoint thta returns the health status of the service
type HealthCheck struct {
state int32 // atomic, keep at the top to be word-aligned
logger *zap.Logger
mapping map[Status]int
server *http.Server
}
// Option is a functional option for passing paameters to New()
type Option func(*HealthCheck)
// Logger creates an option to set the logger. If not specified, Nop logger is used.
func Logger(logger *zap.Logger) Option {
return func(hc *HealthCheck) {
hc.logger = logger
}
}
// New creates a HealthCheck with the specified initial state.
func New(state Status, options ...Option) *HealthCheck {
hc := &HealthCheck{
state: int32(state),
mapping: map[Status]int{
Unavailable: http.StatusServiceUnavailable,
Ready: http.StatusNoContent,
},
}
for _, option := range options {
option(hc)
}
if hc.logger == nil {
hc.logger = zap.NewNop()
}
return hc
}
// Serve starts HTTP server on the specified port.
func (hc *HealthCheck) Serve(port int) (*HealthCheck, error) {
portStr := ":" + strconv.Itoa(port)
l, err := net.Listen("tcp", portStr)
if err != nil {
hc.logger.Error("Health Check server failed to listen", zap.Error(err))
return nil, err
}
hc.serveWithListener(l)
hc.logger.Info("Health Check server started", zap.Int("http-port", port), zap.Stringer("status", hc.Get()))
return hc, nil
}
func (hc *HealthCheck) serveWithListener(l net.Listener) {
hc.server = &http.Server{Handler: hc.httpHandler()}
go func() {
if err := hc.server.Serve(l); err != nil {
hc.logger.Error("failed to serve", zap.Error(err))
hc.Set(Broken)
}
}()
}
// Close stops the HTTP server
func (hc *HealthCheck) Close() error {
return hc.server.Shutdown(context.Background())
}
// httpHandler creates a new HTTP handler.
func (hc *HealthCheck) httpHandler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(hc.mapping[hc.Get()])
// this is written only for response with an entity, so, it won't be used for a 204 - No content
w.Write([]byte("Server not available"))
})
version.RegisterHandler(mux, hc.logger)
return mux
}
// Set a new health check status
func (hc *HealthCheck) Set(state Status) {
atomic.StoreInt32(&hc.state, int32(state))
hc.logger.Info("Health Check state change", zap.Stringer("status", hc.Get()))
}
// Get the current status of this health check
func (hc *HealthCheck) Get() Status {
return Status(atomic.LoadInt32(&hc.state))
}
// Ready is a shortcut for Set(Ready) (kept for backwards compatibility)
func (hc *HealthCheck) Ready() {
hc.Set(Ready)
}