Initial commit
[vaultmon/.git] / vault.go
CommitLineData
9a72579f
SB
1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "io/ioutil"
7 "net/http"
8
9 log "github.com/sirupsen/logrus"
10)
11
12type Vault struct {
13 URL string
14 ConnectionStatus string
15 ClusterStatus string
16}
17
18func (v *Vault) CheckHealth() (bool, error) {
19 healthURL := v.URL + "/v1/sys/health"
20 cnx := NewConnection(healthURL)
21 log.Debugf("Vault Connection on %s", healthURL)
22 resp, err := cnx.Head()
23 if err != nil {
24 return false, err
25 }
26 defer resp.Body.Close()
27
28 log.Debugf("Vault CheckHealth response: %s", resp.Status)
29
30 return resp.StatusCode == http.StatusOK, nil
31}
32
33func (v *Vault) CheckCluster() (bool, error) {
34 ClusterURL := v.URL + "/v1/sys/leader"
35 cnx := NewConnection(ClusterURL)
36 log.Debugf("Vault Connection on %s", ClusterURL)
37 resp, err := cnx.Get()
38 if err != nil {
39 return false, err
40 }
41 defer resp.Body.Close()
42
43 log.Debugf("Vault CheckCluster response: %s", resp.Status)
44
45 buf, err := ioutil.ReadAll(resp.Body)
46 if err != nil {
47 return false, err
48 }
49
50 var result struct {
51 LeaderAddress string `json:"leader_address"`
52 IsSelf bool `json:"is_self"`
53 HAEnabled bool `json:"ha_enabled"`
54 LeaderClusterAddress string `json:"leader_cluster_address"`
55 }
56 err = json.Unmarshal(buf, &result)
57 if err != nil {
58 return false, err
59 }
60
61 log.Debugf("Vault CheckCluster JSON result: %+v", result)
62
63 return result.HAEnabled == true, nil
64}
65
66func (v *Vault) Test() (bool, string) {
67 // test health
68 result, err := v.CheckHealth()
69 if err != nil {
70 log.Errorf("Vault CheckHealth error: %s", err)
71 v.ConnectionStatus = "KO"
72 }
73 v.ConnectionStatus = "OK"
74 log.Debugf("Vault CheckHealth result: %t", result)
75
76 // test cluster
77 result, err = v.CheckCluster()
78 if err != nil {
79 log.Errorf("Vault CheckCluster error: %s", err)
80 v.ClusterStatus = "KO"
81 }
82 v.ClusterStatus = "OK"
83 log.Debugf("Vault CheckCluster result: %t", result)
84
85 return result, fmt.Sprintf("> %s `%s` status *%s*. Cluster status *%s*.", v.Name(), v.URL, v.ConnectionStatus, v.ClusterStatus)
86}
87
88func (v *Vault) Name() string {
89 return "Vault"
90}
91
92func NewVault(url string) CheckProvider {
93 return &Vault{URL: url}
94}