/
helpers.go
76 lines (64 loc) · 2.24 KB
/
helpers.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
//go:build !no_logs
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package kubernetes
import (
"strings"
)
// KubeAllowedEncodeStringAlphaNums holds the charactes allowed in replicaset names from as parent deployment
// Taken from https://github.com/kow3ns/kubernetes/blob/96067e6d7b24a05a6a68a0d94db622957448b5ab/staging/src/k8s.io/apimachinery/pkg/util/rand/rand.go#L76
const KubeAllowedEncodeStringAlphaNums = "bcdfghjklmnpqrstvwxz2456789"
// Digits holds the digits used for naming replicasets in kubenetes < 1.8
const Digits = "1234567890"
// ParseDeploymentForReplicaSet gets the deployment name from a replicaset,
// or returns an empty string if no parent deployment is found.
func ParseDeploymentForReplicaSet(name string) string {
lastDash := strings.LastIndexAny(name, "-")
if lastDash == -1 {
// No dash
return ""
}
suffix := name[lastDash+1:]
if len(suffix) < 3 {
// Suffix is variable length but we cutoff at 3+ characters
return ""
}
if !StringInRuneset(suffix, Digits) && !StringInRuneset(suffix, KubeAllowedEncodeStringAlphaNums) {
// Invalid suffix
return ""
}
return name[:lastDash]
}
// ParseCronJobForJob gets the cronjob name from a job,
// or returns an empty string if no parent cronjob is found.
// https://github.com/kubernetes/kubernetes/blob/b4e3bd381bd4d7c0db1959341b39558b45187345/pkg/controller/cronjob/utils.go#L156
func ParseCronJobForJob(name string) string {
lastDash := strings.LastIndexAny(name, "-")
if lastDash == -1 {
// No dash
return ""
}
suffix := name[lastDash+1:]
if len(suffix) < 3 {
// Suffix is variable length but we cutoff at 3+ characters
return ""
}
if !StringInRuneset(suffix, Digits) {
// Invalid suffix
return ""
}
return name[:lastDash]
}
// StringInRuneset tests whether all runes of a string are in a given subset
// returns false if any rune in the string is not found in the subset
func StringInRuneset(name, subset string) bool {
for _, r := range name {
if !strings.ContainsRune(subset, r) {
// Found an unexpected rune in suffix
return false
}
}
return true
}