Debian Codegraph @

pkg/storage/names/generate.go

raw
1 /*
2 Copyright 2014 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package names
18
19 import (
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.
27 type NameGenerator interface {
28 // GenerateName generates a valid name from the base name, adding a random suffix to
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.
35 type 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)
40 var SimpleNameGenerator NameGenerator = simpleNameGenerator{}
41
42 const (
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
49 func (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 }