-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
260 lines (227 loc) · 7.11 KB
/
client.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package main
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
h "github.com/xorpaul/gohelper"
)
var (
debug bool
verbose bool
info bool
quiet bool
buildtime string
config configSettings
client *http.Client
)
type request struct {
Fqdn string `json:"fqdn"`
Uptime string `json:"uptime"`
RequestID string `json:"request_id,omitempty"`
RestartReason string `json:"restart_reason"`
}
type response struct {
Error string `json:"error"`
Timestamp time.Time `json:"timestamp"`
Goahead bool `json:"go_ahead"`
UnknownHost bool `json:"unknown_host"`
AskagainIn string `json:"ask_again_in"`
RequestID string `json:"request_id"`
FoundCluster string `json:"found_cluster"`
RequestingFqdn string `json:"requesting_fqdn"`
Message string `json:"message"`
}
func inquireRestart() {
url := config.ServiceUrl + "v1/inquire/restart/"
body := doRequest(url, "", "inquire")
var response response
err := json.Unmarshal(body, &response)
if err != nil {
h.Warnf("Could not parse JSON response: " + string(body) + " Error: " + err.Error())
}
if len(response.Error) > 1 {
h.Fatalf("Recieved error: " + response.Error)
h.Infof("Received valid response from " + url)
}
if strings.HasPrefix(response.Message, "YesInquireToRestart") {
h.Infof("Received reason from middle-ware to restart: " + response.Message)
doRestart("forced by middle-ware")
}
}
func askForOSRestart(rid string, restartReason string) response {
url := config.ServiceUrl + "v1/request/restart/os"
body := doRequest(url, rid, restartReason)
var response response
err := json.Unmarshal(body, &response)
if err != nil {
h.Warnf("Could not parse JSON response: " + string(body) + " Error: " + err.Error())
}
if len(response.Error) > 1 {
h.Fatalf("Recieved error: " + response.Error)
}
h.Infof("Received valid response from " + url)
return response
}
func getPayload(rid string, restartReason string) *bytes.Buffer {
var req request
if len(rid) > 0 {
req.RequestID = rid
}
if len(restartReason) > 0 {
req.RestartReason = restartReason
}
if flag.Lookup("test.v") == nil {
req.Fqdn = getPayloadFqdn()
req.Uptime = getPayloadUptime()
} else {
req.Fqdn = "foobar-server-aa02.domain.tld"
if os.Getenv("TEST_FOR_CRASH_TestUptimeLow") == "1" {
req.Uptime = (time.Duration(2) * time.Second).String()
} else {
req.Uptime = (time.Duration(83836) * time.Second).String()
}
}
reqBytes, err := json.Marshal(req)
if err != nil {
h.Fatalf("Error while json.Marshal request. Error: " + err.Error())
}
h.Debugf("Trying to send payload: " + string(reqBytes))
return bytes.NewBuffer(reqBytes)
}
func doRequest(url string, rid string, restartReason string) []byte {
h.Debugf("sending HTTP request " + url)
payload := getPayload(rid, restartReason)
resp, err := client.Post(url, "application/json", payload)
if err != nil {
h.Fatalf("Error while issuing request to " + url + " Error: " + err.Error())
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
h.Fatalf("Error while reading response body: " + err.Error())
}
h.Debugf("Received response: " + string(body))
return body
}
func main() {
log.SetOutput(os.Stdout)
var (
configFileFlag = flag.String("config", "/etc/goahead/client.yml", "which config file to use")
disabledFileFlag = flag.String("disabled", "/etc/goahead/disabled", "file to check if goahead run should be skipped")
versionFlag = flag.Bool("version", false, "show build time and version number")
)
flag.BoolVar(&debug, "debug", false, "log debug output, defaults to false")
flag.Parse()
configFile := *configFileFlag
disabledFile := *disabledFileFlag
version := *versionFlag
if version {
fmt.Println("goahead client version 0.0.2 Build time:", buildtime, "UTC")
os.Exit(0)
}
h.Info = true
h.Debug = debug
h.InfoTimestamp = true
h.WarnExit = true
h.Debugf("Using as config file: " + configFile)
config = readConfigfile(configFile)
client = setupHttpClient()
if h.FileExists(disabledFile) {
data, err := ioutil.ReadFile(disabledFile)
if err != nil {
h.Fatalf("There was an error parsing the file to disabled goahead" + disabledFile + ": " + err.Error())
}
reason := "reason not specified"
if len(data) > 0 {
reason = string(data)
reason = strings.ReplaceAll(reason, "\n", "")
}
fmt.Printf("Notice: Skipping run of goahead client; administratively disabled (Reason: '%s')\n", reason)
} else {
doMain()
}
}
func setupHttpClient() *http.Client {
// Get the SystemCertPool, continue with an empty pool on error
rootCAs, _ := x509.SystemCertPool()
if rootCAs == nil {
rootCAs = x509.NewCertPool()
}
if len(config.ServiceUrlCaFile) > 0 {
// Read in the cert file
certs, err := ioutil.ReadFile(config.ServiceUrlCaFile)
if err != nil {
h.Fatalf("Failed to append " + config.ServiceUrlCaFile + " to RootCAs Error: " + err.Error())
}
// Append our cert to the system pool
h.Debugf("Appending certificate " + config.ServiceUrlCaFile + " to trusted CAs")
if ok := rootCAs.AppendCertsFromPEM(certs); !ok {
h.Debugf("No certs appended, using system certs only")
}
}
// Trust the augmented cert pool in our client
tlsConfig := &tls.Config{
RootCAs: rootCAs,
}
tr := &http.Transport{TLSClientConfig: tlsConfig}
return &http.Client{Transport: tr}
}
func doMain() {
er := h.ExecuteCommand(config.RestartConditionScript, 5, true)
if er.ReturnCode == config.RestartConditionScriptExitCodeForReboot {
doRestart(er.Output)
} else {
h.Infof("Did not find local reason to restart. Asking if I should restart, because of other reasons.")
inquireRestart()
}
}
func doRestart(restartReason string) {
response := askForOSRestart("", restartReason)
if len(response.FoundCluster) < 1 || len(response.AskagainIn) == 0 {
h.Warnf(response.Message + " Exiting...")
}
h.Infof("Sleeping for " + response.AskagainIn)
sleep, err := time.ParseDuration(response.AskagainIn)
if err != nil {
h.Fatalf("Error while trying to parse response.AskagainIn to Duration. Error: " + err.Error())
}
time.Sleep(sleep)
response = askForOSRestart(response.RequestID, restartReason)
if response.Goahead {
// execute hooks and check their exit code
executeRestartHooks()
} else {
h.Infof("Did not recieve go ahead to restart. Reason: " + response.Message)
}
}
func executeRestartHooks() {
if len(config.OsRestartHooksDir) > 0 {
if h.IsDir(config.OsRestartHooksDir) {
globPath := filepath.Join(config.OsRestartHooksDir, "*")
h.Debugf("Glob'ing with path " + globPath)
matches, err := filepath.Glob(globPath)
if len(matches) == 0 {
h.Fatalf("Could not find any restart hook scripts matching " + globPath)
}
h.Debugf("found pre restart hook script: " + strings.Join(matches, " "))
if err != nil {
h.Fatalf("Failed to glob pre restart hook script directory with glob path " + globPath + " Error: " + err.Error())
}
sort.Strings(matches)
for _, file := range matches {
_ = h.ExecuteCommand(file, 10, config.OsRestartHooksAllowFail)
}
}
}
}