/
properties.go
552 lines (454 loc) · 17.4 KB
/
properties.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
/*
Copyright 2021 Dynatrace LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package dynakube
import (
"fmt"
"net/url"
"strings"
"github.com/Dynatrace/dynatrace-operator/pkg/api"
"github.com/Dynatrace/dynatrace-operator/pkg/util/timeprovider"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
// MaxNameLength is the maximum length of a DynaKube's name, we tend to add suffixes to the name to avoid name collisions for resources related to the DynaKube. (example: dkName-activegate-<some-hash>)
// The limit is necessary because kubernetes uses the name of some resources (ActiveGate StatefulSet) for the label value, which has a limit of 63 characters. (see https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set)
MaxNameLength = 40
// PullSecretSuffix is the suffix appended to the DynaKube name to n.
PullSecretSuffix = "-pull-secret"
ActiveGateTenantSecretSuffix = "-activegate-tenant-secret"
OneAgentTenantSecretSuffix = "-oneagent-tenant-secret"
OneAgentConnectionInfoConfigMapSuffix = "-oneagent-connection-info"
ActiveGateConnectionInfoConfigMapSuffix = "-activegate-connection-info"
AuthTokenSecretSuffix = "-activegate-authtoken-secret"
PodNameOsAgent = "oneagent"
defaultActiveGateImage = "/linux/activegate:latest"
defaultSyntheticImage = "linux/dynatrace-synthetic"
)
// ApiUrl is a getter for dk.Spec.APIURL.
func (dk *DynaKube) ApiUrl() string {
return dk.Spec.APIURL
}
// ApiUrlHost returns the host of dk.Spec.APIURL
// E.g. if the APIURL is set to "https://my-tenant.dynatrace.com/api", it returns "my-tenant.dynatrace.com"
// If the URL cannot be parsed, it returns an empty string.
func (dk *DynaKube) ApiUrlHost() string {
parsedUrl, err := url.Parse(dk.ApiUrl())
if err != nil {
return ""
}
return parsedUrl.Host
}
// NeedsActiveGate returns true when a feature requires ActiveGate instances.
func (dk *DynaKube) NeedsActiveGate() bool {
return dk.DeprecatedActiveGateMode() ||
dk.ActiveGateMode() ||
dk.IsSyntheticMonitoringEnabled()
}
// ApplicationMonitoringMode returns true when application only section is used.
func (dk *DynaKube) ApplicationMonitoringMode() bool {
return dk.Spec.OneAgent != OneAgentSpec{} && dk.Spec.OneAgent.ApplicationMonitoring != nil
}
// CloudNativeFullstackMode returns true when cloud native fullstack section is used.
func (dk *DynaKube) CloudNativeFullstackMode() bool {
return dk.Spec.OneAgent != OneAgentSpec{} && dk.Spec.OneAgent.CloudNativeFullStack != nil
}
// HostMonitoringMode returns true when host monitoring section is used.
func (dk *DynaKube) HostMonitoringMode() bool {
return dk.Spec.OneAgent != OneAgentSpec{} && dk.Spec.OneAgent.HostMonitoring != nil
}
// ClassicFullStackMode returns true when classic fullstack section is used.
func (dk *DynaKube) ClassicFullStackMode() bool {
return dk.Spec.OneAgent != OneAgentSpec{} && dk.Spec.OneAgent.ClassicFullStack != nil
}
// NeedsOneAgent returns true when a feature requires OneAgent instances.
func (dk *DynaKube) NeedsOneAgent() bool {
return dk.ClassicFullStackMode() || dk.CloudNativeFullstackMode() || dk.HostMonitoringMode()
}
func (dk *DynaKube) OneAgentDaemonsetName() string {
return fmt.Sprintf("%s-%s", dk.Name, PodNameOsAgent)
}
func (dk *DynaKube) DeprecatedActiveGateMode() bool {
return dk.Spec.KubernetesMonitoring.Enabled || dk.Spec.Routing.Enabled
}
func (dk *DynaKube) ActiveGateMode() bool {
return len(dk.Spec.ActiveGate.Capabilities) > 0
}
func (dk *DynaKube) IsActiveGateMode(mode CapabilityDisplayName) bool {
for _, capability := range dk.Spec.ActiveGate.Capabilities {
if capability == mode {
return true
}
}
return false
}
func (dk *DynaKube) ActiveGateServiceAccountOwner() string {
if dk.IsKubernetesMonitoringActiveGateEnabled() {
return string(KubeMonCapability.DeepCopy().DisplayName)
} else {
return "activegate"
}
}
func (dk *DynaKube) ActiveGateServiceAccountName() string {
return "dynatrace-" + dk.ActiveGateServiceAccountOwner()
}
func (dk *DynaKube) IsKubernetesMonitoringActiveGateEnabled() bool {
return dk.IsActiveGateMode(KubeMonCapability.DisplayName) || dk.Spec.KubernetesMonitoring.Enabled
}
func (dk *DynaKube) IsRoutingActiveGateEnabled() bool {
return dk.IsActiveGateMode(RoutingCapability.DisplayName) || dk.Spec.Routing.Enabled
}
func (dk *DynaKube) IsApiActiveGateEnabled() bool {
return dk.IsActiveGateMode(DynatraceApiCapability.DisplayName)
}
func (dk *DynaKube) IsMetricsIngestActiveGateEnabled() bool {
return dk.IsActiveGateMode(MetricsIngestCapability.DisplayName)
}
func (dk *DynaKube) NeedsActiveGateServicePorts() bool {
return dk.IsRoutingActiveGateEnabled() ||
dk.IsApiActiveGateEnabled() ||
dk.IsMetricsIngestActiveGateEnabled()
}
func (dk *DynaKube) NeedsActiveGateService() bool {
return dk.NeedsActiveGateServicePorts()
}
func (dk *DynaKube) IsSyntheticMonitoringEnabled() bool {
return dk.FeatureSyntheticLocationEntityId() != ""
}
func (dk *DynaKube) HasActiveGateCaCert() bool {
return dk.ActiveGateMode() && dk.Spec.ActiveGate.TlsSecretName != ""
}
func (dk *DynaKube) NeedsOneAgentPrivileged() bool {
return dk.FeatureOneAgentPrivileged()
}
func (dk *DynaKube) NeedsOneAgentProbe() bool {
return dk.Status.OneAgent.Healthcheck != nil
}
// ShouldAutoUpdateOneAgent returns true if the Operator should update OneAgent instances automatically.
func (dk *DynaKube) ShouldAutoUpdateOneAgent() bool {
switch {
case dk.CloudNativeFullstackMode():
return dk.Spec.OneAgent.CloudNativeFullStack.AutoUpdate == nil || *dk.Spec.OneAgent.CloudNativeFullStack.AutoUpdate
case dk.HostMonitoringMode():
return dk.Spec.OneAgent.HostMonitoring.AutoUpdate == nil || *dk.Spec.OneAgent.HostMonitoring.AutoUpdate
case dk.ClassicFullStackMode():
return dk.Spec.OneAgent.ClassicFullStack.AutoUpdate == nil || *dk.Spec.OneAgent.ClassicFullStack.AutoUpdate
default:
return false
}
}
// ActivegateTenantSecret returns the name of the secret containing tenant UUID, token and communication endpoints for ActiveGate.
func (dk *DynaKube) ActivegateTenantSecret() string {
return dk.Name + ActiveGateTenantSecretSuffix
}
// OneagentTenantSecret returns the name of the secret containing the token for the OneAgent.
func (dk *DynaKube) OneagentTenantSecret() string {
return dk.Name + OneAgentTenantSecretSuffix
}
// ActiveGateAuthTokenSecret returns the name of the secret containing the ActiveGateAuthToken, which is mounted to the AGs.
func (dk *DynaKube) ActiveGateAuthTokenSecret() string {
return dk.Name + AuthTokenSecretSuffix
}
func (dk *DynaKube) ActiveGateConnectionInfoConfigMapName() string {
return dk.Name + ActiveGateConnectionInfoConfigMapSuffix
}
func (dk *DynaKube) OneAgentConnectionInfoConfigMapName() string {
return dk.Name + OneAgentConnectionInfoConfigMapSuffix
}
// PullSecretName returns the name of the pull secret to be used for immutable images.
func (dk *DynaKube) PullSecretName() string {
if dk.Spec.CustomPullSecret != "" {
return dk.Spec.CustomPullSecret
}
return dk.Name + PullSecretSuffix
}
// PullSecretWithoutData returns a secret which can be used to query the actual secrets data from the cluster.
func (dk *DynaKube) PullSecretWithoutData() corev1.Secret {
return corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: dk.PullSecretName(),
Namespace: dk.Namespace,
},
}
}
func (dk *DynaKube) NeedsReadOnlyOneAgents() bool {
return dk.HostMonitoringMode() || dk.CloudNativeFullstackMode()
}
func (dk *DynaKube) NeedsCSIDriver() bool {
isAppMonitoringWithCSI := dk.ApplicationMonitoringMode() &&
dk.Spec.OneAgent.ApplicationMonitoring.UseCSIDriver != nil &&
*dk.Spec.OneAgent.ApplicationMonitoring.UseCSIDriver
return dk.CloudNativeFullstackMode() || isAppMonitoringWithCSI || dk.HostMonitoringMode()
}
func (dk *DynaKube) NeedAppInjection() bool {
return dk.CloudNativeFullstackMode() || dk.ApplicationMonitoringMode()
}
func (dk *DynaKube) InitResources() *corev1.ResourceRequirements {
if dk.ApplicationMonitoringMode() {
return dk.Spec.OneAgent.ApplicationMonitoring.InitResources
} else if dk.CloudNativeFullstackMode() {
return dk.Spec.OneAgent.CloudNativeFullStack.InitResources
}
return nil
}
func (dk *DynaKube) NamespaceSelector() *metav1.LabelSelector {
return &dk.Spec.NamespaceSelector
}
func (dk *DynaKube) NodeSelector() map[string]string {
switch {
case dk.ClassicFullStackMode():
return dk.Spec.OneAgent.ClassicFullStack.NodeSelector
case dk.HostMonitoringMode():
return dk.Spec.OneAgent.HostMonitoring.NodeSelector
case dk.CloudNativeFullstackMode():
return dk.Spec.OneAgent.CloudNativeFullStack.NodeSelector
}
return nil
}
// ActiveGateImage provides the image reference set in Status for the ActiveGate.
// Format: repo@sha256:digest.
func (dk *DynaKube) ActiveGateImage() string {
return dk.Status.ActiveGate.ImageID
}
// DefaultActiveGateImage provides the image reference for the ActiveGate from tenant registry.
// Format: repo:tag.
func (dk *DynaKube) DefaultActiveGateImage() string {
apiUrlHost := dk.ApiUrlHost()
if apiUrlHost == "" {
return ""
}
return apiUrlHost + defaultActiveGateImage
}
func (dk *DynaKube) deprecatedActiveGateImage() string {
if dk.Spec.KubernetesMonitoring.Image != "" {
return dk.Spec.KubernetesMonitoring.Image
} else if dk.Spec.Routing.Image != "" {
return dk.Spec.Routing.Image
}
return ""
}
// CustomActiveGateImage provides the image reference for the ActiveGate provided in the Spec.
func (dk *DynaKube) CustomActiveGateImage() string {
if dk.DeprecatedActiveGateMode() {
return dk.deprecatedActiveGateImage()
}
return dk.Spec.ActiveGate.Image
}
// SyntheticImage provides the image reference set in Status for Synthetic.
// Format: repo@sha256:digest.
func (dk *DynaKube) SyntheticImage() string {
return dk.Status.Synthetic.ImageID
}
// CustomSyntheticImage provides the image reference for Synthetic provided in the feature-flags.
func (dk *DynaKube) CustomSyntheticImage() string {
return dk.FeatureCustomSyntheticImage()
}
// DefaultActiveGateImage provides the image reference for Synthetic from tenant registry.
// Format: repo:tag.
func (dk *DynaKube) DefaultSyntheticImage() string {
apiUrlHost := dk.ApiUrlHost()
if apiUrlHost == "" {
return ""
}
return fmt.Sprintf("%s/%s:%s",
apiUrlHost,
defaultSyntheticImage,
api.LatestTag)
}
// CodeModulesVersion provides version set in Status for the CodeModules.
func (dk *DynaKube) CodeModulesVersion() string {
return dk.Status.CodeModules.Version
}
// CodeModulesImage provides the image reference set in Status for the CodeModules.
// Format: repo@sha256:digest.
func (dk *DynaKube) CodeModulesImage() string {
return dk.Status.CodeModules.ImageID
}
// CustomCodeModulesImage provides the image reference for the CodeModules provided in the Spec.
func (dk *DynaKube) CustomCodeModulesImage() string {
if dk.CloudNativeFullstackMode() {
return dk.Spec.OneAgent.CloudNativeFullStack.CodeModulesImage
} else if dk.ApplicationMonitoringMode() && dk.NeedsCSIDriver() {
return dk.Spec.OneAgent.ApplicationMonitoring.CodeModulesImage
}
return ""
}
// CustomCodeModulesVersion provides the version for the CodeModules provided in the Spec.
func (dk *DynaKube) CustomCodeModulesVersion() string {
if !dk.ApplicationMonitoringMode() {
return ""
}
return dk.CustomOneAgentVersion()
}
// OneAgentImage provides the image reference set in Status for the OneAgent.
// Format: repo@sha256:digest.
func (dk *DynaKube) OneAgentImage() string {
return dk.Status.OneAgent.ImageID
}
// OneAgentVersion provides version set in Status for the OneAgent.
func (dk *DynaKube) OneAgentVersion() string {
return dk.Status.OneAgent.Version
}
// CustomOneAgentVersion provides the version for the OneAgent provided in the Spec.
func (dk *DynaKube) CustomOneAgentVersion() string {
switch {
case dk.ClassicFullStackMode():
return dk.Spec.OneAgent.ClassicFullStack.Version
case dk.CloudNativeFullstackMode():
return dk.Spec.OneAgent.CloudNativeFullStack.Version
case dk.ApplicationMonitoringMode():
return dk.Spec.OneAgent.ApplicationMonitoring.Version
case dk.HostMonitoringMode():
return dk.Spec.OneAgent.HostMonitoring.Version
}
return ""
}
// CustomOneAgentImage provides the image reference for the OneAgent provided in the Spec.
func (dk *DynaKube) CustomOneAgentImage() string {
switch {
case dk.ClassicFullStackMode():
return dk.Spec.OneAgent.ClassicFullStack.Image
case dk.HostMonitoringMode():
return dk.Spec.OneAgent.HostMonitoring.Image
case dk.CloudNativeFullstackMode():
return dk.Spec.OneAgent.CloudNativeFullStack.Image
}
return ""
}
// DefaultOneAgentImage provides the image reference for the OneAgent from tenant registry.
func (dk *DynaKube) DefaultOneAgentImage() string {
if dk.Spec.APIURL == "" {
return ""
}
tag := api.LatestTag
if version := dk.CustomOneAgentVersion(); version != "" {
truncatedVersion := truncateBuildDate(version)
tag = truncatedVersion
}
apiUrlHost := dk.ApiUrlHost()
if apiUrlHost == "" {
return ""
}
return fmt.Sprintf("%s/linux/oneagent:%s", apiUrlHost, tag)
}
func truncateBuildDate(version string) string {
const versionSeparator = "."
const buildDateIndex = 3
if strings.Count(version, versionSeparator) >= buildDateIndex {
splitVersion := strings.Split(version, versionSeparator)
truncatedVersion := strings.Join(splitVersion[:buildDateIndex], versionSeparator)
return truncatedVersion
}
return version
}
// Tokens returns the name of the Secret to be used for tokens.
func (dk *DynaKube) Tokens() string {
if tkns := dk.Spec.Tokens; tkns != "" {
return tkns
}
return dk.Name
}
// TenantUUIDFromApiUrl gets the tenantUUID from the ApiUrl present in the struct, if the tenant is aliased then the alias will be returned.
func (dk *DynaKube) TenantUUIDFromApiUrl() (string, error) {
return tenantUUID(dk.Spec.APIURL)
}
func runeIs(wanted rune) func(rune) bool {
return func(actual rune) bool {
return actual == wanted
}
}
func tenantUUID(apiUrl string) (string, error) {
parsedUrl, err := url.Parse(apiUrl)
if err != nil {
return "", errors.WithMessagef(err, "problem parsing tenant id from url %s", apiUrl)
}
// Path = "/e/<token>/api" -> ["e", "<tenant>", "api"]
subPaths := strings.FieldsFunc(parsedUrl.Path, runeIs('/'))
if len(subPaths) >= 3 && subPaths[0] == "e" && subPaths[2] == "api" {
return subPaths[1], nil
}
hostnameWithDomains := strings.FieldsFunc(parsedUrl.Hostname(), runeIs('.'))
if len(hostnameWithDomains) >= 1 {
return hostnameWithDomains[0], nil
}
return "", errors.Errorf("problem getting tenant id from API URL '%s'", apiUrl)
}
func (dk *DynaKube) HostGroup() string {
if dk.Spec.OneAgent.HostGroup != "" {
return dk.Spec.OneAgent.HostGroup
}
return dk.HostGroupAsParam()
}
func (dk *DynaKube) HostGroupAsParam() string {
var hostGroup string
var args []string
switch {
case dk.CloudNativeFullstackMode() && dk.Spec.OneAgent.CloudNativeFullStack.Args != nil:
args = dk.Spec.OneAgent.CloudNativeFullStack.Args
case dk.ClassicFullStackMode() && dk.Spec.OneAgent.ClassicFullStack.Args != nil:
args = dk.Spec.OneAgent.ClassicFullStack.Args
case dk.HostMonitoringMode() && dk.Spec.OneAgent.HostMonitoring.Args != nil:
args = dk.Spec.OneAgent.HostMonitoring.Args
}
for _, arg := range args {
key, value := splitArg(arg)
if key == "--set-host-group" {
hostGroup = value
break
}
}
return hostGroup
}
func splitArg(arg string) (key, value string) {
split := strings.Split(arg, "=")
const expectedLen = 2
if len(split) != expectedLen {
return
}
key = split[0]
value = split[1]
return
}
func getRawImageTag(imageURI string) string {
if !strings.Contains(imageURI, ":") {
return api.LatestTag
}
splitURI := strings.Split(imageURI, ":")
return splitURI[len(splitURI)-1]
}
func (dk *DynaKube) GetOneAgentEnvironment() []corev1.EnvVar {
switch {
case dk.CloudNativeFullstackMode():
return dk.Spec.OneAgent.CloudNativeFullStack.Env
case dk.ClassicFullStackMode():
return dk.Spec.OneAgent.ClassicFullStack.Env
case dk.HostMonitoringMode():
return dk.Spec.OneAgent.HostMonitoring.Env
}
return []corev1.EnvVar{}
}
// +kubebuilder:object:generate=false
type RequestAllowedChecker func(timeProvider *timeprovider.Provider) bool
func (dk *DynaKube) IsOneAgentConnectionInfoUpdateAllowed(timeProvider *timeprovider.Provider) bool {
return timeProvider.IsOutdated(&dk.Status.OneAgent.ConnectionInfoStatus.LastRequest, dk.FeatureApiRequestThreshold())
}
func (dk *DynaKube) IsActiveGateConnectionInfoUpdateAllowed(timeProvider *timeprovider.Provider) bool {
return timeProvider.IsOutdated(&dk.Status.ActiveGate.ConnectionInfoStatus.LastRequest, dk.FeatureApiRequestThreshold())
}
func (dk *DynaKube) IsTokenScopeVerificationAllowed(timeProvider *timeprovider.Provider) bool {
return timeProvider.IsOutdated(&dk.Status.DynatraceApi.LastTokenScopeRequest, dk.FeatureApiRequestThreshold())
}
func (dk *DynaKube) IsOneAgentCommunicationRouteClear() bool {
return len(dk.Status.OneAgent.ConnectionInfoStatus.CommunicationHosts) > 0
}