/
client.go
228 lines (187 loc) · 7.62 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
package dynatrace
import (
"crypto/tls"
"crypto/x509"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
"golang.org/x/net/http/httpproxy"
)
const (
DynatracePaasToken = "paasToken"
DynatraceApiToken = "apiToken"
DynatraceDataIngestToken = "dataIngestToken"
)
// Client is the interface for the Dynatrace REST API client.
type Client interface {
// GetLatestAgentVersion gets the latest agent version for the given OS and installer type.
// Returns the version as received from the server on success.
//
// Returns an error for the following conditions:
// - os or installerType is empty
// - IO error or unexpected response
// - error response from the server (e.g. authentication failure)
// - the agent version is not set or empty
GetLatestAgentVersion(os, installerType string) (string, error)
// GetLatestAgent returns a reader with the contents of the download. Must be closed by caller.
GetLatestAgent(os, installerType, flavor, arch string, technologies []string, skipMetadata bool, writer io.Writer) error
// GetAgent downloads a specific agent version and writes it to the given io.Writer
GetAgent(os, installerType, flavor, arch, version string, technologies []string, skipMetadata bool, writer io.Writer) error
// GetAgentViaInstallerUrl downloads the agent from the user specified URL and writes it to the given io.Writer
GetAgentViaInstallerUrl(url string, writer io.Writer) error
// GetAgentVersions on success returns an array of versions that can be used with GetAgent to
// download a specific agent version
GetAgentVersions(os, installerType, flavor, arch string) ([]string, error)
GetOneAgentConnectionInfo() (OneAgentConnectionInfo, error)
GetProcessModuleConfig(prevRevision uint) (*ProcessModuleConfig, error)
// GetCommunicationHostForClient returns a CommunicationHost for the client's API URL. Or error, if failed to be parsed.
GetCommunicationHostForClient() (CommunicationHost, error)
// SendEvent posts events to dynatrace API
SendEvent(eventData *EventData) error
// GetEntityIDForIP returns the entity id for a given IP address.
//
// Returns an error in case the lookup failed.
GetEntityIDForIP(ip string) (string, error)
// GetTokenScopes returns the list of scopes assigned to a token if successful.
GetTokenScopes(token string) (TokenScopes, error)
// GetActiveGateConnectionInfo returns AgentTenantInfo for ActiveGate that holds UUID, Tenant Token and Endpoints
GetActiveGateConnectionInfo() (ActiveGateConnectionInfo, error)
// CreateOrUpdateKubernetesSetting returns the object id of the created k8s settings if successful, or an api error otherwise
CreateOrUpdateKubernetesSetting(name, kubeSystemUUID, scope string) (string, error)
// CreateOrUpdateKubernetesAppSetting returns the object id of the created k8s app settings if successful, or an api error otherwise
CreateOrUpdateKubernetesAppSetting(scope string) (string, error)
// GetMonitoredEntitiesForKubeSystemUUID returns a (possibly empty) list of k8s monitored entities for the given uuid,
// or an api error otherwise
GetMonitoredEntitiesForKubeSystemUUID(kubeSystemUUID string) ([]MonitoredEntity, error)
// GetSettingsForMonitoredEntities returns the settings response with the number of settings objects,
// or an api error otherwise
GetSettingsForMonitoredEntities(monitoredEntities []MonitoredEntity, schemaId string) (GetSettingsResponse, error)
// GetSettingsForMonitoredEntities returns the settings response with the number of settings objects,
// or an api error otherwise
GetActiveGateAuthToken(dynakubeName string) (*ActiveGateAuthTokenInfo, error)
GetLatestOneAgentImage() (*LatestImageInfo, error)
GetLatestCodeModulesImage() (*LatestImageInfo, error)
GetLatestActiveGateImage() (*LatestImageInfo, error)
// GetLatestActiveGateVersion gets the latest gateway version for the given OS and arch.
// Returns the version as received from the server on success.
GetLatestActiveGateVersion(os string) (string, error)
}
// Known OS values.
const (
OsUnix = "unix"
// Commented for linter, left for further reference
// OsWindows = "windows"
// OsAix = "aix"
// OsSolaris = "solaris"
)
// Known installer types.
const (
InstallerTypeDefault = "default"
// Commented for linter, left for further reference
// InstallerTypeUnattended = "default-unattended"
InstallerTypePaaS = "paas"
// InstallerTypePaasSh = "paas-sh"
)
// Known token scopes
const (
TokenScopeInstallerDownload = "InstallerDownload"
TokenScopeDataExport = "DataExport"
TokenScopeMetricsIngest = "metrics.ingest"
TokenScopeEntitiesRead = "entities.read"
TokenScopeSettingsRead = "settings.read"
TokenScopeSettingsWrite = "settings.write"
TokenScopeActiveGateTokenCreate = "activeGateTokenManagement.create"
)
// NewClient creates a REST client for the given API base URL and authentication tokens.
// Returns an error if a token or the URL is empty.
//
// The API base URL is different for managed and SaaS environments:
// - SaaS: https://{environment-id}.live.dynatrace.com/api
// - Managed: https://{domain}/e/{environment-id}/api
//
// opts can be used to customize the created client, entries must not be nil.
func NewClient(url, apiToken, paasToken string, opts ...Option) (Client, error) {
if len(url) == 0 {
return nil, errors.New("url is empty")
}
if len(apiToken) == 0 && len(paasToken) == 0 {
return nil, errors.New("tokens are empty")
}
url = strings.TrimSuffix(url, "/")
dc := &dynatraceClient{
url: url,
apiToken: apiToken,
paasToken: paasToken,
hostCache: make(map[string]hostInfo),
httpClient: &http.Client{
Transport: http.DefaultTransport.(*http.Transport).Clone(),
Timeout: 15 * time.Minute,
},
}
for _, opt := range opts {
opt(dc)
}
return dc, nil
}
// Option can be passed to NewClient and customizes the created client instance.
type Option func(*dynatraceClient)
// SkipCertificateValidation creates an Option that specifies whether validation of the server's TLS
// certificate should be skipped. The default is false.
func SkipCertificateValidation(skip bool) Option {
return func(c *dynatraceClient) {
if skip {
t := c.httpClient.Transport.(*http.Transport)
if t.TLSClientConfig == nil {
t.TLSClientConfig = &tls.Config{} //nolint:gosec // fix is expected to be delivered soon
}
t.TLSClientConfig.InsecureSkipVerify = true
}
}
}
func Proxy(proxyURL string, noProxy string) Option {
return func(dtclient *dynatraceClient) {
parsedURL, err := url.Parse(proxyURL)
if err != nil {
log.Info("could not parse proxy URL!")
return
}
transport := dtclient.httpClient.Transport.(*http.Transport)
proxyConfig := httpproxy.Config{
HTTPProxy: parsedURL.String(),
HTTPSProxy: parsedURL.String(),
NoProxy: noProxy,
}
transport.Proxy = proxyWrapper(proxyConfig)
}
}
func proxyWrapper(proxyConfig httpproxy.Config) func(req *http.Request) (*url.URL, error) {
return func(req *http.Request) (*url.URL, error) {
return proxyConfig.ProxyFunc()(req.URL)
}
}
func Certs(certs []byte) Option {
return func(c *dynatraceClient) {
rootCAs := x509.NewCertPool()
if ok := rootCAs.AppendCertsFromPEM(certs); !ok {
log.Info("failed to append custom certs!")
}
t := c.httpClient.Transport.(*http.Transport)
if t.TLSClientConfig == nil {
t.TLSClientConfig = &tls.Config{} //nolint:gosec // fix is expected to be delivered soon
}
t.TLSClientConfig.RootCAs = rootCAs
}
}
func NetworkZone(networkZone string) Option {
return func(c *dynatraceClient) {
c.networkZone = networkZone
}
}
func HostGroup(hostGroup string) Option {
return func(c *dynatraceClient) {
c.hostGroup = hostGroup
}
}