forked from tsuru/tsuru
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hc.go
108 lines (99 loc) · 2.46 KB
/
hc.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
// Copyright 2015 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 docker
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
"github.com/pkg/errors"
"github.com/tsuru/config"
"github.com/tsuru/tsuru/hc"
tsuruNet "github.com/tsuru/tsuru/net"
)
var httpRegexp = regexp.MustCompile(`^https?://`)
func init() {
hc.AddChecker("docker-registry", healthCheckDockerRegistry)
hc.AddChecker("docker", healthCheckDocker)
}
func healthCheckDockerRegistry() error {
err := pingDockerRegistry("https")
if err != nil {
return pingDockerRegistry("http")
}
return nil
}
func pingDockerRegistry(scheme string) error {
registry, _ := config.GetString("docker:registry")
if registry == "" {
return hc.ErrDisabledComponent
}
registry = httpRegexp.ReplaceAllString(registry, "")
registry = fmt.Sprintf("%s://%s", scheme, strings.TrimRight(registry, "/"))
v1URL := registry + "/v1/_ping"
v2URL := registry + "/v2/"
client := tsuruNet.Dial15Full60ClientNoKeepAlive
req, err := newRequestWithCredentials(http.MethodGet, v2URL)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode == http.StatusNotFound {
resp.Body.Close()
req, err = newRequestWithCredentials(http.MethodGet, v1URL)
if err != nil {
return err
}
resp, err = client.Do(req)
if err != nil {
return err
}
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return errors.Errorf("unexpected status - %s", body)
}
return nil
}
func newRequestWithCredentials(method, url string) (*http.Request, error) {
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
username, _ := config.GetString("docker:registry-auth:username")
password, _ := config.GetString("docker:registry-auth:password")
if len(username) != 0 || len(password) != 0 {
req.SetBasicAuth(username, password)
}
return req, nil
}
func healthCheckDocker() error {
nodes, err := mainDockerProvisioner.Cluster().Nodes()
if err != nil {
return err
}
if len(nodes) < 1 {
return errors.New("error - no nodes available for running containers")
}
if len(nodes) > 1 {
return hc.ErrDisabledComponent
}
client, err := nodes[0].Client()
if err != nil {
return err
}
err = client.Ping()
if err != nil {
return errors.Wrap(err, "ping failed")
}
return nil
}