forked from Dynatrace/dynatrace-oneagent-operator
/
communication_hosts.go
103 lines (85 loc) · 2.26 KB
/
communication_hosts.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
package dynatrace_client
import (
"encoding/json"
"errors"
"net/url"
"strconv"
)
// CommunicationHost => struct of connection endpoint
type CommunicationHost struct {
Protocol string
Host string
Port uint32
}
func (dc *dynatraceClient) GetCommunicationHostForClient() (CommunicationHost, error) {
return dc.parseEndpoint(dc.url)
}
func (dc *dynatraceClient) GetCommunicationHosts() ([]CommunicationHost, error) {
resp, err := dc.makeRequest("%s/v1/deployment/installer/agent/connectioninfo?Api-Token=%s", dc.url, dc.paasToken)
if err != nil {
return nil, err
}
defer resp.Body.Close()
responseData, err := dc.getServerResponseData(resp)
if err != nil {
return nil, err
}
return dc.readResponseForConnectionInfo(responseData)
}
func (dc *dynatraceClient) readResponseForConnectionInfo(response []byte) ([]CommunicationHost, error) {
type jsonResponse struct {
CommunicationEndpoints []string
}
resp := jsonResponse{}
err := json.Unmarshal(response, &resp)
if err != nil {
logger.Error(err, "error unmarshalling json response")
return nil, err
}
out := make([]CommunicationHost, 0, len(resp.CommunicationEndpoints))
for _, s := range resp.CommunicationEndpoints {
logger := logger.WithValues("url", s)
e, err := dc.parseEndpoint(s)
if err != nil {
logger.Info("failed to parse communication endpoint")
continue
}
out = append(out, e)
}
if len(out) == 0 {
return nil, errors.New("no hosts available")
}
return out, nil
}
func (dc *dynatraceClient) parseEndpoint(s string) (CommunicationHost, error) {
u, err := url.ParseRequestURI(s)
if err != nil {
return CommunicationHost{}, errors.New("failed to parse URL")
}
if u.Scheme == "" {
return CommunicationHost{}, errors.New("no protocol provided")
} else if u.Scheme != "http" && u.Scheme != "https" {
return CommunicationHost{}, errors.New("unknown protocol")
}
rp := u.Port() // Empty if not included in the URI
var p uint32
if rp == "" {
switch u.Scheme {
case "http":
p = 80
case "https":
p = 443
}
} else {
q, err := strconv.ParseUint(rp, 10, 32)
if err != nil {
return CommunicationHost{}, errors.New("failed to parse port")
}
p = uint32(q)
}
return CommunicationHost{
Protocol: u.Scheme,
Host: u.Hostname(),
Port: p,
}, nil
}