forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
namer.go
68 lines (58 loc) · 1.84 KB
/
namer.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
package apihelpers
import (
"fmt"
"hash/fnv"
kvalidation "k8s.io/apimachinery/pkg/util/validation"
)
// GetName returns a name given a base ("deployment-5") and a suffix ("deploy")
// It will first attempt to join them with a dash. If the resulting name is longer
// than maxLength: if the suffix is too long, it will truncate the base name and add
// an 8-character hash of the [base]-[suffix] string. If the suffix is not too long,
// it will truncate the base, add the hash of the base and return [base]-[hash]-[suffix]
func GetName(base, suffix string, maxLength int) string {
if maxLength <= 0 {
return ""
}
name := fmt.Sprintf("%s-%s", base, suffix)
if len(name) <= maxLength {
return name
}
baseLength := maxLength - 10 /*length of -hash-*/ - len(suffix)
// if the suffix is too long, ignore it
if baseLength < 0 {
prefix := base[0:min(len(base), max(0, maxLength-9))]
// Calculate hash on initial base-suffix string
shortName := fmt.Sprintf("%s-%s", prefix, hash(name))
return shortName[:min(maxLength, len(shortName))]
}
prefix := base[0:baseLength]
// Calculate hash on initial base-suffix string
return fmt.Sprintf("%s-%s-%s", prefix, hash(base), suffix)
}
// GetPodName calls GetName with the length restriction for pods
func GetPodName(base, suffix string) string {
return GetName(base, suffix, kvalidation.DNS1123SubdomainMaxLength)
}
// max returns the greater of its 2 inputs
func max(a, b int) int {
if b > a {
return b
}
return a
}
// min returns the lesser of its 2 inputs
func min(a, b int) int {
if b < a {
return b
}
return a
}
// hash calculates the hexadecimal representation (8-chars)
// of the hash of the passed in string using the FNV-a algorithm
func hash(s string) string {
hash := fnv.New32a()
hash.Write([]byte(s))
intHash := hash.Sum32()
result := fmt.Sprintf("%08x", intHash)
return result
}