| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 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 | |
| 17 | package server |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "net/http" |
| 22 | "sync" |
| 23 | "time" |
| 24 | |
| 25 | "github.com/prometheus/client_golang/prometheus" |
| 26 | "github.com/prometheus/client_golang/prometheus/promauto" |
| 27 | "github.com/rs/zerolog/log" |
| 28 | |
| 29 | "github.com/sassoftware/relic/v7/internal/zhttp" |
| 30 | "github.com/sassoftware/relic/v7/token" |
| 31 | ) |
| 32 | |
| 33 | var ( |
| 34 | healthStatus int |
| 35 | healthLastPing time.Time |
| 36 | healthMu sync.Mutex |
| 37 | |
| 38 | metricTokenCheckErrors = promauto.NewGaugeVec( |
| 39 | prometheus.GaugeOpts{ |
| 40 | Name: "token_check_sequential_errors", |
| 41 | Help: "Number of sequential errors seen while checking the token's status", |
| 42 | }, |
| 43 | []string{"token"}, |
| 44 | ) |
| 45 | ) |
| 46 | |
| 47 | func (s *Server) healthCheckInterval() time.Duration { |
| 48 | return time.Second * time.Duration(s.Config.Server.TokenCheckInterval) |
| 49 | } |
| 50 | |
| 51 | func (s *Server) startHealthCheck() error { |
| 52 | healthStatus = s.Config.Server.TokenCheckFailures |
| 53 | healthLastPing = time.Now() |
| 54 | go s.healthCheckLoop() |
| 55 | return nil |
| 56 | } |
| 57 | |
| 58 | func (s *Server) healthCheckLoop() { |
| 59 | interval := s.healthCheckInterval() |
| 60 | t := time.NewTimer(0) |
| 61 | defer t.Stop() |
| 62 | for { |
| 63 | select { |
| 64 | case <-t.C: |
| 65 | s.healthCheck() |
| 66 | t.Reset(interval) |
| 67 | case <-s.Closed: |
| 68 | break |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | func (s *Server) healthCheck() bool { |
| 74 | healthMu.Lock() |
| 75 | last := healthStatus |
| 76 | healthMu.Unlock() |
| 77 | var notOK []string |
| 78 | for name, token := range s.tokens { |
| 79 | metric := metricTokenCheckErrors.WithLabelValues(name) |
| 80 | if s.pingOne(token) { |
| 81 | metric.Set(0) |
| 82 | } else { |
| 83 | metric.Inc() |
| 84 | notOK = append(notOK, name) |
| 85 | } |
| 86 | } |
| 87 | next := last |
| 88 | if len(notOK) == 0 { |
| 89 | ev := log.Info().Str("token_state", "OK") |
| 90 | if last == 0 { |
| 91 | ev.Msg("recovered to normal state, status is now OK") |
| 92 | } else if last < s.Config.Server.TokenCheckFailures { |
| 93 | ev.Msg("recovered to normal state") |
| 94 | } |
| 95 | next = s.Config.Server.TokenCheckFailures |
| 96 | } else if last > 0 { |
| 97 | next-- |
| 98 | if next == 0 { |
| 99 | log.Error().Str("token_state", "ERROR"). |
| 100 | Msg("exceeded maximum health check failures, flagging as ERROR") |
| 101 | } |
| 102 | } |
| 103 | healthMu.Lock() |
| 104 | defer healthMu.Unlock() |
| 105 | healthStatus = next |
| 106 | healthLastPing = time.Now() |
| 107 | return len(notOK) == 0 |
| 108 | } |
| 109 | |
| 110 | func (s *Server) pingOne(tok token.Token) bool { |
| 111 | ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(s.Config.Server.TokenCheckTimeout)) |
| 112 | defer cancel() |
| 113 | if err := tok.Ping(ctx); err != nil { |
| 114 | ev := log.Error().Str("token", tok.Config().Name()) |
| 115 | if ctx.Err() != nil { |
| 116 | ev.Msg("token health check timed out") |
| 117 | } else { |
| 118 | ev.Err(err).Msg("token health check failed") |
| 119 | } |
| 120 | return false |
| 121 | } |
| 122 | return true |
| 123 | } |
| 124 | |
| 125 | func (s *Server) Healthy(request *http.Request) bool { |
| 126 | if s.Config.Server.Disabled { |
| 127 | return false |
| 128 | } |
| 129 | healthMu.Lock() |
| 130 | defer healthMu.Unlock() |
| 131 | if time.Since(healthLastPing) > 3*s.healthCheckInterval() { |
| 132 | if request != nil { |
| 133 | log.Error().Dur("stale_for", time.Since(healthLastPing)).Msg("health check is stale") |
| 134 | } |
| 135 | return false |
| 136 | } |
| 137 | return healthStatus > 0 |
| 138 | } |
| 139 | |
| 140 | func (s *Server) serveHealth(rw http.ResponseWriter, request *http.Request) { |
| 141 | zhttp.DontLog(request) |
| 142 | if s.Healthy(request) { |
| 143 | _, _ = rw.Write([]byte("OK\r\n")) |
| 144 | } else { |
| 145 | http.Error(rw, "health check failed", http.StatusServiceUnavailable) |
| 146 | } |
| 147 | } |