generate.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package api
  14. import (
  15. "fmt"
  16. utilrand "k8s.io/kubernetes/pkg/util/rand"
  17. )
  18. // NameGenerator generates names for objects. Some backends may have more information
  19. // available to guide selection of new names and this interface hides those details.
  20. type NameGenerator interface {
  21. // GenerateName generates a valid name from the base name, adding a random suffix to the
  22. // the base. If base is valid, the returned name must also be valid. The generator is
  23. // responsible for knowing the maximum valid name length.
  24. GenerateName(base string) string
  25. }
  26. // GenerateName will resolve the object name of the provided ObjectMeta to a generated version if
  27. // necessary. It expects that validation for ObjectMeta has already completed (that Base is a
  28. // valid name) and that the NameGenerator generates a name that is also valid.
  29. func GenerateName(u NameGenerator, meta *ObjectMeta) {
  30. if len(meta.GenerateName) == 0 || len(meta.Name) != 0 {
  31. return
  32. }
  33. meta.Name = u.GenerateName(meta.GenerateName)
  34. }
  35. // simpleNameGenerator generates random names.
  36. type simpleNameGenerator struct{}
  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. const (
  42. // TODO: make this flexible for non-core resources with alternate naming rules.
  43. maxNameLength = 63
  44. randomLength = 5
  45. maxGeneratedNameLength = maxNameLength - randomLength
  46. )
  47. func (simpleNameGenerator) GenerateName(base string) string {
  48. if len(base) > maxGeneratedNameLength {
  49. base = base[:maxGeneratedNameLength]
  50. }
  51. return fmt.Sprintf("%s%s", base, utilrand.String(randomLength))
  52. }