Skip to content

Commit b2c31f8

Browse files
committed
Implement readiness check using atomic value and improve error handling
1 parent d45dac9 commit b2c31f8

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

main.go

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"os/signal"
1313
"strconv"
1414
"strings"
15+
"sync/atomic"
1516
"syscall"
1617
"text/template"
1718
"time"
@@ -20,6 +21,8 @@ import (
2021
var version string = "dev"
2122
var revision string = "000000000000000000000000000000"
2223

24+
var lastSuccess atomic.Value
25+
2326
type customMetric struct {
2427
Name string
2528
Value float64
@@ -74,6 +77,11 @@ func readMetricsFile(path string) ([]byte, error) {
7477
if path == "" {
7578
return nil, nil
7679
}
80+
81+
if _, err := os.Stat(path); os.IsNotExist(err) {
82+
return nil, nil
83+
}
84+
7785
rendered, err := renderTemplateFile(path)
7886
if err != nil {
7987
return nil, err
@@ -114,8 +122,14 @@ func main() {
114122
go func() {
115123
mux := http.NewServeMux()
116124
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
117-
w.WriteHeader(http.StatusOK)
118-
w.Write([]byte("ok"))
125+
ok, _ := lastSuccess.Load().(bool)
126+
if ok {
127+
w.WriteHeader(http.StatusOK)
128+
w.Write([]byte("ok"))
129+
} else {
130+
w.WriteHeader(http.StatusServiceUnavailable)
131+
w.Write([]byte("not ready"))
132+
}
119133
})
120134
srv := &http.Server{Addr: healthAddr, Handler: mux}
121135

@@ -143,7 +157,9 @@ func main() {
143157
default:
144158
customMetrics, err := readMetricsFile(metricsFile)
145159
if err != nil {
146-
fmt.Println("read metrics file:", err)
160+
if !os.IsNotExist(err) {
161+
fmt.Println("read metrics file:", err)
162+
}
147163
}
148164
run(client, sourceURL, pushURL, pushUser, pushPass, scrapeTimeout, pushTimeout, customMetrics)
149165
select {

0 commit comments

Comments
 (0)