/
trivyserver.go
97 lines (84 loc) · 2.23 KB
/
trivyserver.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
package controller
import (
"errors"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/bluele/gcache"
)
type ServerHealthChecker interface {
TrivyServerAvaliable(serverURL string) (bool, error)
}
func NewTrivyServerChecker(expiration *time.Duration, cache gcache.Cache, httpChecker HttpChecker) ServerHealthChecker {
return &trivyServerHealthChecker{expiration: expiration, cache: cache, httpChecker: httpChecker}
}
type trivyServerHealthChecker struct {
mutex sync.RWMutex
cache gcache.Cache
expiration *time.Duration
httpChecker HttpChecker
}
func NewHttpChecker() HttpChecker {
return &httpChecker{}
}
// HttpChecker check health with http server
type HttpChecker interface {
ServerHealthy(serverURL string) error
}
type httpChecker struct {
}
// TrivyServerAvaliable check if trivy server is avaliable
// 1st cehck in cache and if not found it check for server health via http call the healthz api and update cache
func (r *trivyServerHealthChecker) TrivyServerAvaliable(serverURL string) (bool, error) {
up, err := r.serverUpFromCache()
if err != nil {
if !errors.Is(err, gcache.KeyNotFoundError) {
return false, err
}
err := r.checkServerUp(serverURL)
if err != nil {
return false, nil
}
return true, nil
}
return up, nil
}
func (r *trivyServerHealthChecker) serverUpFromCache() (bool, error) {
r.mutex.RLock()
defer r.mutex.RUnlock()
serverUp, err := r.cache.Get(trivyServerUp)
if err != nil {
return false, err
}
value, ok := serverUp.(bool)
if ok && value {
return true, nil
}
return false, nil
}
func (r *trivyServerHealthChecker) checkServerUp(serverURL string) error {
r.mutex.Lock()
defer r.mutex.Unlock()
err := r.httpChecker.ServerHealthy(serverURL)
if err != nil {
return err
}
_ = r.cache.SetWithExpire(trivyServerUp, true, *r.expiration)
return nil
}
// ServerHealthy make http call the trivy server 'healthz' api for it avaliability
func (r *httpChecker) ServerHealthy(serverURL string) error {
resp, err := http.Get(fmt.Sprintf("%s/%s", strings.TrimSuffix(serverURL, "/"), "healthz"))
if err != nil {
return err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode == http.StatusOK {
return nil
}
return fmt.Errorf("trivy server is not up and running")
}