forked from tsuru/tsuru
-
Notifications
You must be signed in to change notification settings - Fork 0
/
healthcheck.go
70 lines (66 loc) · 1.73 KB
/
healthcheck.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
// Copyright 2016 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package swarm
import (
"fmt"
"strings"
"time"
"github.com/docker/docker/api/types/container"
"github.com/tsuru/tsuru/provision"
)
func toHealthConfig(meta provision.TsuruYamlData, port int) *container.HealthConfig {
hc := meta.Healthcheck
path := hc.Path
method := hc.Method
match := hc.Match
status := hc.Status
scheme := hc.Scheme
if scheme == "" {
scheme = provision.DefaultHealthcheckScheme
}
allowedFailures := hc.AllowedFailures
if hc.TimeoutSeconds == 0 {
hc.TimeoutSeconds = 60
}
var cmdLine string
if path != "" {
path = strings.TrimSpace(strings.TrimLeft(path, "/"))
if method == "" {
method = "GET"
}
method = strings.ToUpper(method)
if status == 0 && match == "" {
status = 200
}
cmdLine = fmt.Sprintf("curl -k -X%s -fsSL %s://localhost:%d/%s", method, scheme, port, strings.TrimPrefix(path, "/"))
if match != "" {
cmdLine = fmt.Sprintf("%s | egrep %q", cmdLine, match)
} else {
cmdLine = fmt.Sprintf("%s -o/dev/null -w '%%{http_code}' | grep %d", cmdLine, status)
}
}
if len(meta.Hooks.Restart.After) > 0 {
restartHooks := fmt.Sprintf(`if [ ! -f %[1]s ]; then %[2]s && touch %[1]s; fi`,
"/tmp/restartafterok",
strings.Join(meta.Hooks.Restart.After, " && "),
)
if cmdLine == "" {
cmdLine = restartHooks
} else {
cmdLine = fmt.Sprintf("%s && %s", cmdLine, restartHooks)
}
}
if cmdLine == "" {
return nil
}
return &container.HealthConfig{
Interval: 3 * time.Second,
Retries: allowedFailures + 1,
Timeout: time.Duration(hc.TimeoutSeconds) * time.Second,
Test: []string{
"CMD-SHELL",
cmdLine,
},
}
}