blob: aad9a07f9ad27b6bcafb59badb1a6dac6d221bbb [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2014 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package names
18
19import (
20 "fmt"
21
22 utilrand "k8s.io/apimachinery/pkg/util/rand"
23)
24
25// NameGenerator generates names for objects. Some backends may have more information
26// available to guide selection of new names and this interface hides those details.
27type NameGenerator interface {
28 // GenerateName generates a valid name from the base name, adding a random suffix to the
29 // the base. If base is valid, the returned name must also be valid. The generator is
30 // responsible for knowing the maximum valid name length.
31 GenerateName(base string) string
32}
33
34// simpleNameGenerator generates random names.
35type simpleNameGenerator struct{}
36
37// SimpleNameGenerator is a generator that returns the name plus a random suffix of five alphanumerics
38// when a name is requested. The string is guaranteed to not exceed the length of a standard Kubernetes
39// name (63 characters)
40var SimpleNameGenerator NameGenerator = simpleNameGenerator{}
41
42const (
43 // TODO: make this flexible for non-core resources with alternate naming rules.
44 maxNameLength = 63
45 randomLength = 5
46 maxGeneratedNameLength = maxNameLength - randomLength
47)
48
49func (simpleNameGenerator) GenerateName(base string) string {
50 if len(base) > maxGeneratedNameLength {
51 base = base[:maxGeneratedNameLength]
52 }
53 return fmt.Sprintf("%s%s", base, utilrand.String(randomLength))
54}