-
Notifications
You must be signed in to change notification settings - Fork 2
/
servicehost.go
420 lines (363 loc) · 9.82 KB
/
servicehost.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/nettica-com/nettica-admin/model"
log "github.com/sirupsen/logrus"
)
var netticaServiceHostAPIFmt = "%s/api/v1.0/service/%s/status"
var netticaServiceHostUpdateAPIFmt = "%s/api/v1.0/service/%s"
func StartServiceHost(s *Server, c chan bool) {
var host string
for s.Config.Device == nil {
time.Sleep(1 * time.Second)
}
host = s.Config.Device.Server
var client *http.Client
var etag string
err := StartContainers(s)
if err != nil {
log.Debugf("Error starting containers %v", err)
}
if strings.HasPrefix(host, "http:") {
client = &http.Client{
Timeout: time.Second * 10,
}
} else {
// Create a transport like http.DefaultTransport, but with the configured LocalAddr
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 60 * time.Second,
LocalAddr: cfg.sourceAddr,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
}
client = &http.Client{
Transport: transport,
}
}
for {
<-c
if !cfg.loaded {
err := loadConfig()
if err != nil {
log.Errorf("Failed to load config.")
}
}
// Only make API call if ServiceGroup is set
if s.Config.Device.ServiceGroup != "" && s.Config.Device.ServiceApiKey != "" {
var reqURL string = fmt.Sprintf(netticaServiceHostAPIFmt, host, s.Config.Device.ServiceGroup)
log.Debugf(" GET %s", reqURL)
var buffer []byte
req, err := http.NewRequest("GET", reqURL, bytes.NewBuffer(buffer))
if err != nil {
return
}
if req != nil {
req.Header.Set("X-API-KEY", s.Config.Device.ServiceApiKey)
req.Header.Set("User-Agent", "nettica-client/"+Version)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("If-None-Match", etag)
}
resp, err := client.Do(req)
if err == nil {
if resp.StatusCode == 304 {
} else if resp.StatusCode != 200 {
log.Errorf("Response Error Code: %v, sleeping 10 seconds", resp.StatusCode)
time.Sleep(10 * time.Second)
} else {
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Errorf("error reading body %v", err)
}
log.Debugf("%s", string(body))
etag = resp.Header.Get("ETag")
UpdateServiceHostConfig(s, body)
}
} else {
log.Errorf("ERROR: %v, sleeping 10 seconds", err)
time.Sleep(10 * time.Second)
}
if resp != nil {
resp.Body.Close()
}
if req != nil {
req.Body.Close()
}
}
}
}
func StartContainers(s *Server) error {
path := s.Path
path = strings.TrimSuffix(path, ".json")
path = path + "-service-host.json"
file, err := os.Open(path)
if err != nil {
log.Debugf("Error opening config file %v", err)
return err
}
body, err := io.ReadAll(file)
file.Close()
if err != nil {
log.Errorf("Error reading service host config file: %v", err)
return err
}
var msg model.ServiceMessage
err = json.Unmarshal(body, &msg)
if err != nil {
log.Errorf("Error unmarshalling service host config file: %v", err)
return err
}
for _, service := range msg.Config {
if service.ContainerId == "" {
// Start the container
id, err := StartService(service)
if err != nil {
log.Errorf("Error starting service %v", err)
} else {
service.ContainerId = id
service.Status = "Running"
UpdateNetticaServiceHost(s, service)
log.Infof("Started service %s", service.ContainerId)
}
} else {
// If the container isn't running (eg, reboot), restart it
if !CheckService(service) {
service.ContainerId = ""
id, err := StartService(service)
if err == nil {
service.ContainerId = id
service.Status = "Running"
UpdateNetticaServiceHost(s, service)
log.Infof("Restarted service %s", service.ContainerId)
}
}
}
}
return nil
}
func UpdateNetticaServiceHost(s *Server, service model.Service) error {
log.Infof("UPDATING SERVICE: %v", service)
server := s.Config.Device.Server
var client *http.Client
if strings.HasPrefix(server, "http:") {
client = &http.Client{
Timeout: time.Second * 10,
}
} else {
// Create a transport like http.DefaultTransport, but with the configured LocalAddr
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 60 * time.Second,
LocalAddr: cfg.sourceAddr,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
}
client = &http.Client{
Transport: transport,
}
}
var reqURL string = fmt.Sprintf(netticaServiceHostUpdateAPIFmt, server, service.Id)
log.Infof(" PATCH %s", reqURL)
content, err := json.Marshal(service)
if err != nil {
return err
}
req, err := http.NewRequest("PATCH", reqURL, bytes.NewBuffer(content))
if err != nil {
return err
}
if req != nil {
req.Header.Set("X-API-KEY", service.ApiKey)
req.Header.Set("User-Agent", "nettica-client/"+Version)
req.Header.Set("Content-Type", "application/json")
}
resp, err := client.Do(req)
if err == nil {
if resp.StatusCode != 200 {
log.Errorf("PATCH Error: Response %v", resp.StatusCode)
} else {
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Errorf("error reading body %v", err)
}
log.Infof("%s", string(body))
}
}
if resp != nil {
resp.Body.Close()
}
if req != nil {
req.Body.Close()
}
return nil
}
// UpdateServiceHostConfig updates the config from the server
func UpdateServiceHostConfig(s *Server, body []byte) {
// If the file doesn't exist create it for the first time
if _, err := os.Stat(GetDataPath() + "my.nettica.com-service-host.json"); os.IsNotExist(err) {
file, err := os.OpenFile(GetDataPath()+"my.nettica.com-service-host.json", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err == nil {
file.Close()
}
}
file, err := os.Open(GetDataPath() + "my.nettica.com-service-host.json")
if err != nil {
log.Errorf("Error opening service host config file %v", err)
return
}
conf, err := io.ReadAll(file)
file.Close()
if err != nil {
log.Errorf("Error reading nettica config file: %v", err)
return
}
// compare the body to the current config and make no changes if they are the same
if bytes.Equal(conf, body) {
return
} else {
file, err := os.OpenFile(GetDataPath()+"my.nettica.com-service-host.json", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
log.Errorf("Error opening my.nettica.com-service-host.json for write: %v", err)
return
}
_, err = file.Write(body)
file.Close()
if err != nil {
log.Infof("Error writing my.nettica.com-service-host.json file: %v", err)
return
}
var msg model.ServiceMessage
err = json.Unmarshal(body, &msg)
if err != nil {
log.Errorf("Error reading message from server")
}
var oldmsg model.ServiceMessage
err = json.Unmarshal(conf, &oldmsg)
if err != nil {
log.Errorf("Error reading message from disk")
}
log.Debugf("%v", msg)
// Check and update the status of the container
for _, service := range msg.Config {
if service.ContainerId == "" {
// Start the container
id, err := StartService(service)
if err != nil {
log.Errorf("Error starting service %v", err)
service.Status = "Error"
UpdateNetticaServiceHost(s, service)
} else {
service.ContainerId = id
service.Status = "Running"
UpdateNetticaServiceHost(s, service)
}
} else {
// If the container isn't running (eg, reboot), restart it
if !CheckService(service) {
service.ContainerId = ""
id, err := StartService(service)
if err == nil {
service.ContainerId = id
service.Status = "Running"
UpdateNetticaServiceHost(s, service)
} else {
log.Errorf("Error restarting service %v", err)
service.Status = "Error"
UpdateNetticaServiceHost(s, service)
}
}
}
}
// Remove any containers that are no longer in the config
for _, oldservice := range oldmsg.Config {
found := false
for _, newservice := range msg.Config {
if oldservice.ContainerId == newservice.ContainerId {
found = true
}
}
if !found {
log.Infof("Removing container %s", oldservice.ContainerId)
// Stop the container
StopService(oldservice)
}
}
}
}
// StartService starts a container
func StartService(service model.Service) (string, error) {
var err error
id, err := StartContainer(service)
if err != nil {
log.Errorf("Error starting container %v", err)
} else {
service.ContainerId = id
log.Infof("Started container %s", service.ContainerId)
}
return id, err
}
// CheckService checks if a container is running
func CheckService(service model.Service) bool {
if service.ContainerId != "" {
running := CheckContainer(service)
if !running {
log.Infof("Container %s is not running", service.ContainerId)
return false
}
return true
}
return false
}
// StopService stops a container
func StopService(service model.Service) {
err := StopContainer(service)
if err != nil {
log.Errorf("Error stopping container %v", err)
} else {
log.Infof("Stopped container %s", service.ContainerId)
}
}
// DoServiceWork catches any errors in the service and recovers from them, if possible
func DoServiceWork(s *Server) {
var curTs int64
// recover from any panics coming from below
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok := r.(error)
if !ok {
log.Fatalf("Fatal Error: %v", err)
}
}
}()
go func() {
// Determine current timestamp (the wallclock time we'll retrieve files using)
c := make(chan bool)
go StartServiceHost(s, c)
curTs = calculateCurrentTimestamp()
t := time.Unix(curTs, 0)
log.Debugf("current timestamp = %v (%s)", curTs, t.UTC())
for {
time.Sleep(1000 * time.Millisecond)
ts := time.Now()
if ts.Unix() >= curTs {
// call the channel to trigger the next poll
c <- true
curTs = calculateCurrentTimestamp()
curTs += s.Config.Device.CheckInterval
}
}
}()
}