David K. Bainbridge | b4a9ab0 | 2019-09-20 15:12:16 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2019-present Open Networking Foundation |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | package probe |
| 17 | |
| 18 | import ( |
| 19 | "context" |
| 20 | "fmt" |
| 21 | "github.com/opencord/voltha-go/common/log" |
| 22 | "net/http" |
| 23 | "sync" |
| 24 | ) |
| 25 | |
| 26 | // ProbeContextKey used to fetch the Probe instance from a context |
| 27 | type ProbeContextKeyType string |
| 28 | |
| 29 | // ServiceStatus typed values for service status |
| 30 | type ServiceStatus int |
| 31 | |
| 32 | const ( |
| 33 | // ServiceStatusUnknown initial state of services |
| 34 | ServiceStatusUnknown ServiceStatus = iota |
| 35 | |
| 36 | // ServiceStatusPreparing to optionally be used for prep, such as connecting |
| 37 | ServiceStatusPreparing |
| 38 | |
| 39 | // ServiceStatusPrepared to optionally be used when prep is complete, but before run |
| 40 | ServiceStatusPrepared |
| 41 | |
| 42 | // ServiceStatusRunning service is functional |
| 43 | ServiceStatusRunning |
| 44 | |
| 45 | // ServiceStatusStopped service has stopped, but not because of error |
| 46 | ServiceStatusStopped |
| 47 | |
| 48 | // ServiceStatusFailed service has stopped because of an error |
| 49 | ServiceStatusFailed |
| 50 | ) |
| 51 | |
| 52 | const ( |
| 53 | // ProbeContextKey value of context key to fetch probe |
| 54 | ProbeContextKey = ProbeContextKeyType("status-update-probe") |
| 55 | ) |
| 56 | |
| 57 | // String convert ServiceStatus values to strings |
| 58 | func (s ServiceStatus) String() string { |
| 59 | switch s { |
| 60 | default: |
| 61 | fallthrough |
| 62 | case ServiceStatusUnknown: |
| 63 | return "Unknown" |
| 64 | case ServiceStatusPreparing: |
| 65 | return "Preparing" |
| 66 | case ServiceStatusPrepared: |
| 67 | return "Prepared" |
| 68 | case ServiceStatusRunning: |
| 69 | return "Running" |
| 70 | case ServiceStatusStopped: |
| 71 | return "Stopped" |
| 72 | case ServiceStatusFailed: |
| 73 | return "Failed" |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | // ServiceStatusUpdate status update event |
| 78 | type ServiceStatusUpdate struct { |
| 79 | Name string |
| 80 | Status ServiceStatus |
| 81 | } |
| 82 | |
| 83 | // Probe reciever on which to implement probe capabilities |
| 84 | type Probe struct { |
| 85 | readyFunc func(map[string]ServiceStatus) bool |
| 86 | healthFunc func(map[string]ServiceStatus) bool |
| 87 | |
| 88 | mutex sync.RWMutex |
| 89 | status map[string]ServiceStatus |
| 90 | isReady bool |
| 91 | isHealthy bool |
| 92 | } |
| 93 | |
| 94 | // WithReadyFunc override the default ready calculation function |
| 95 | func (p *Probe) WithReadyFunc(readyFunc func(map[string]ServiceStatus) bool) *Probe { |
| 96 | p.readyFunc = readyFunc |
| 97 | return p |
| 98 | } |
| 99 | |
| 100 | // WithHealthFunc override the default health calculation function |
| 101 | func (p *Probe) WithHealthFunc(healthFunc func(map[string]ServiceStatus) bool) *Probe { |
| 102 | p.healthFunc = healthFunc |
| 103 | return p |
| 104 | } |
| 105 | |
| 106 | // RegisterService register one or more service names with the probe, status will be track against service name |
| 107 | func (p *Probe) RegisterService(names ...string) { |
| 108 | p.mutex.Lock() |
| 109 | defer p.mutex.Unlock() |
| 110 | if p.status == nil { |
| 111 | p.status = make(map[string]ServiceStatus) |
| 112 | } |
| 113 | for _, name := range names { |
| 114 | if _, ok := p.status[name]; !ok { |
| 115 | p.status[name] = ServiceStatusUnknown |
| 116 | log.Debugw("probe-service-registered", log.Fields{"service-name": name}) |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | // UpdateStatus utility function to send a service update to the probe |
| 122 | func (p *Probe) UpdateStatus(name string, status ServiceStatus) { |
| 123 | p.mutex.Lock() |
| 124 | defer p.mutex.Unlock() |
| 125 | if p.status == nil { |
| 126 | p.status = make(map[string]ServiceStatus) |
| 127 | } |
| 128 | p.status[name] = status |
| 129 | if p.readyFunc != nil { |
| 130 | p.isReady = p.readyFunc(p.status) |
| 131 | } else { |
| 132 | p.isReady = defaultReadyFunc(p.status) |
| 133 | } |
| 134 | |
| 135 | if p.healthFunc != nil { |
| 136 | p.isHealthy = p.healthFunc(p.status) |
| 137 | } else { |
| 138 | p.isHealthy = defaultHealthFunc(p.status) |
| 139 | } |
| 140 | log.Debugw("probe-service-status-updated", |
| 141 | log.Fields{ |
| 142 | "service-name": name, |
| 143 | "status": status.String(), |
| 144 | "ready": p.isReady, |
| 145 | "health": p.isHealthy, |
| 146 | }) |
| 147 | } |
| 148 | |
| 149 | // UpdateStatusFromContext a convenience function to pull the Probe reference from the |
| 150 | // Context, if it exists, and then calling UpdateStatus on that Probe reference. If Context |
| 151 | // is nil or if a Probe reference is not associated with the ProbeContextKey then nothing |
| 152 | // happens |
| 153 | func UpdateStatusFromContext(ctx context.Context, name string, status ServiceStatus) { |
| 154 | if ctx != nil { |
| 155 | if value := ctx.Value(ProbeContextKey); value != nil { |
| 156 | if p, ok := value.(*Probe); ok { |
| 157 | p.UpdateStatus(name, status) |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | // pulled out to a function to help better enable unit testing |
| 164 | func (p *Probe) readzFunc(w http.ResponseWriter, req *http.Request) { |
| 165 | p.mutex.RLock() |
| 166 | defer p.mutex.RUnlock() |
| 167 | if p.isReady { |
| 168 | w.WriteHeader(http.StatusOK) |
| 169 | } else { |
| 170 | w.WriteHeader(http.StatusTeapot) |
| 171 | } |
| 172 | } |
| 173 | func (p *Probe) healthzFunc(w http.ResponseWriter, req *http.Request) { |
| 174 | p.mutex.RLock() |
| 175 | defer p.mutex.RUnlock() |
| 176 | if p.isHealthy { |
| 177 | w.WriteHeader(http.StatusOK) |
| 178 | } else { |
| 179 | w.WriteHeader(http.StatusTeapot) |
| 180 | } |
| 181 | } |
| 182 | func (p *Probe) detailzFunc(w http.ResponseWriter, req *http.Request) { |
| 183 | p.mutex.RLock() |
| 184 | defer p.mutex.RUnlock() |
| 185 | w.Header().Set("Content-Type", "application/json") |
| 186 | w.Write([]byte("{")) |
| 187 | comma := "" |
| 188 | for c, s := range p.status { |
| 189 | w.Write([]byte(fmt.Sprintf("%s\"%s\": \"%s\"", comma, c, s.String()))) |
| 190 | comma = ", " |
| 191 | } |
| 192 | w.Write([]byte("}")) |
| 193 | w.WriteHeader(http.StatusOK) |
| 194 | |
| 195 | } |
| 196 | |
| 197 | // ListenAndServe implements 3 HTTP endpoints on the given port for healthz, readz, and detailz. Returns only on error |
| 198 | func (p *Probe) ListenAndServe(port int) { |
| 199 | mux := http.NewServeMux() |
| 200 | |
| 201 | // Returns the result of the readyFunc calculation |
| 202 | mux.HandleFunc("/readz", p.readzFunc) |
| 203 | |
| 204 | // Returns the result of the healthFunc calculation |
| 205 | mux.HandleFunc("/healthz", p.healthzFunc) |
| 206 | |
| 207 | // Returns the details of the services and their status as JSON |
| 208 | mux.HandleFunc("/detailz", p.detailzFunc) |
| 209 | s := &http.Server{ |
| 210 | Addr: fmt.Sprintf(":%d", port), |
| 211 | Handler: mux, |
| 212 | } |
| 213 | log.Fatal(s.ListenAndServe()) |
| 214 | } |
| 215 | |
| 216 | // defaultReadyFunc if all services are running then ready, else not |
| 217 | func defaultReadyFunc(services map[string]ServiceStatus) bool { |
| 218 | if len(services) == 0 { |
| 219 | return false |
| 220 | } |
| 221 | for _, status := range services { |
| 222 | if status != ServiceStatusRunning { |
| 223 | return false |
| 224 | } |
| 225 | } |
| 226 | return true |
| 227 | } |
| 228 | |
| 229 | // defaultHealthFunc if no service is stopped or failed, then healthy, else not. |
| 230 | // service is start as unknown, so they are considered healthy |
| 231 | func defaultHealthFunc(services map[string]ServiceStatus) bool { |
| 232 | if len(services) == 0 { |
| 233 | return false |
| 234 | } |
| 235 | for _, status := range services { |
| 236 | if status == ServiceStatusStopped || status == ServiceStatusFailed { |
| 237 | return false |
| 238 | } |
| 239 | } |
| 240 | return true |
| 241 | } |