kubectl.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. // A set of common functions needed by cmd/kubectl and pkg/kubectl packages.
  14. package kubectl
  15. import (
  16. "errors"
  17. "fmt"
  18. "path"
  19. "strings"
  20. "k8s.io/kubernetes/pkg/api"
  21. "k8s.io/kubernetes/pkg/api/meta"
  22. "k8s.io/kubernetes/pkg/api/unversioned"
  23. )
  24. const (
  25. kubectlAnnotationPrefix = "kubectl.kubernetes.io/"
  26. )
  27. type NamespaceInfo struct {
  28. Namespace string
  29. }
  30. func listOfImages(spec *api.PodSpec) []string {
  31. images := make([]string, 0, len(spec.Containers))
  32. for _, container := range spec.Containers {
  33. images = append(images, container.Image)
  34. }
  35. return images
  36. }
  37. func makeImageList(spec *api.PodSpec) string {
  38. return strings.Join(listOfImages(spec), ",")
  39. }
  40. func NewThirdPartyResourceMapper(gvs []unversioned.GroupVersion, gvks []unversioned.GroupVersionKind) (meta.RESTMapper, error) {
  41. mapper := meta.NewDefaultRESTMapper(gvs, func(gv unversioned.GroupVersion) (*meta.VersionInterfaces, error) {
  42. for ix := range gvs {
  43. if gvs[ix].Group == gv.Group && gvs[ix].Version == gv.Version {
  44. return &meta.VersionInterfaces{
  45. ObjectConvertor: api.Scheme,
  46. MetadataAccessor: meta.NewAccessor(),
  47. }, nil
  48. }
  49. }
  50. groupVersions := make([]string, 0, len(gvs))
  51. for ix := range gvs {
  52. groupVersions = append(groupVersions, gvs[ix].String())
  53. }
  54. return nil, fmt.Errorf("unsupported storage version: %s (valid: %s)", gv.String(), strings.Join(groupVersions, ", "))
  55. })
  56. for ix := range gvks {
  57. mapper.Add(gvks[ix], meta.RESTScopeNamespace)
  58. }
  59. return mapper, nil
  60. }
  61. // OutputVersionMapper is a RESTMapper that will prefer mappings that
  62. // correspond to a preferred output version (if feasible)
  63. type OutputVersionMapper struct {
  64. meta.RESTMapper
  65. // output versions takes a list of preferred GroupVersions. Only the first
  66. // hit for a given group will have effect. This allows different output versions
  67. // depending upon the group of the kind being requested
  68. OutputVersions []unversioned.GroupVersion
  69. }
  70. // RESTMapping implements meta.RESTMapper by prepending the output version to the preferred version list.
  71. func (m OutputVersionMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (*meta.RESTMapping, error) {
  72. for _, preferredVersion := range m.OutputVersions {
  73. if gk.Group == preferredVersion.Group {
  74. mapping, err := m.RESTMapper.RESTMapping(gk, preferredVersion.Version)
  75. if err == nil {
  76. return mapping, nil
  77. }
  78. break
  79. }
  80. }
  81. return m.RESTMapper.RESTMapping(gk, versions...)
  82. }
  83. // ShortcutExpander is a RESTMapper that can be used for Kubernetes
  84. // resources. It expands the resource first, then invokes the wrapped RESTMapper
  85. type ShortcutExpander struct {
  86. RESTMapper meta.RESTMapper
  87. }
  88. var _ meta.RESTMapper = &ShortcutExpander{}
  89. func (e ShortcutExpander) KindFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error) {
  90. return e.RESTMapper.KindFor(expandResourceShortcut(resource))
  91. }
  92. func (e ShortcutExpander) KindsFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionKind, error) {
  93. return e.RESTMapper.KindsFor(expandResourceShortcut(resource))
  94. }
  95. func (e ShortcutExpander) ResourcesFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error) {
  96. return e.RESTMapper.ResourcesFor(expandResourceShortcut(resource))
  97. }
  98. func (e ShortcutExpander) ResourceFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error) {
  99. return e.RESTMapper.ResourceFor(expandResourceShortcut(resource))
  100. }
  101. func (e ShortcutExpander) RESTMapping(gk unversioned.GroupKind, versions ...string) (*meta.RESTMapping, error) {
  102. return e.RESTMapper.RESTMapping(gk, versions...)
  103. }
  104. func (e ShortcutExpander) RESTMappings(gk unversioned.GroupKind) ([]*meta.RESTMapping, error) {
  105. return e.RESTMapper.RESTMappings(gk)
  106. }
  107. func (e ShortcutExpander) ResourceSingularizer(resource string) (string, error) {
  108. return e.RESTMapper.ResourceSingularizer(expandResourceShortcut(unversioned.GroupVersionResource{Resource: resource}).Resource)
  109. }
  110. func (e ShortcutExpander) AliasesForResource(resource string) ([]string, bool) {
  111. return e.RESTMapper.AliasesForResource(expandResourceShortcut(unversioned.GroupVersionResource{Resource: resource}).Resource)
  112. }
  113. // shortForms is the list of short names to their expanded names
  114. var shortForms = map[string]string{
  115. // Please keep this alphabetized
  116. // If you add an entry here, please also take a look at pkg/kubectl/cmd/cmd.go
  117. // and add an entry to valid_resources when appropriate.
  118. "cm": "configmaps",
  119. "cs": "componentstatuses",
  120. "csr": "certificatesigningrequests",
  121. "deploy": "deployments",
  122. "ds": "daemonsets",
  123. "ep": "endpoints",
  124. "ev": "events",
  125. "hpa": "horizontalpodautoscalers",
  126. "ing": "ingresses",
  127. "limits": "limitranges",
  128. "no": "nodes",
  129. "ns": "namespaces",
  130. "po": "pods",
  131. "psp": "podSecurityPolicies",
  132. "pvc": "persistentvolumeclaims",
  133. "pv": "persistentvolumes",
  134. "quota": "resourcequotas",
  135. "rc": "replicationcontrollers",
  136. "rs": "replicasets",
  137. "sa": "serviceaccounts",
  138. "svc": "services",
  139. }
  140. // Look-up for resource short forms by value
  141. func ResourceShortFormFor(resource string) (string, bool) {
  142. var alias string
  143. exists := false
  144. for k, val := range shortForms {
  145. if val == resource {
  146. alias = k
  147. exists = true
  148. }
  149. }
  150. return alias, exists
  151. }
  152. // expandResourceShortcut will return the expanded version of resource
  153. // (something that a pkg/api/meta.RESTMapper can understand), if it is
  154. // indeed a shortcut. Otherwise, will return resource unmodified.
  155. func expandResourceShortcut(resource unversioned.GroupVersionResource) unversioned.GroupVersionResource {
  156. if expanded, ok := shortForms[resource.Resource]; ok {
  157. // don't change the group or version that's already been specified
  158. resource.Resource = expanded
  159. }
  160. return resource
  161. }
  162. // ResourceAliases returns the resource shortcuts and plural forms for the given resources.
  163. func ResourceAliases(rs []string) []string {
  164. as := make([]string, 0, len(rs))
  165. plurals := make(map[string]struct{}, len(rs))
  166. for _, r := range rs {
  167. var plural string
  168. switch {
  169. case r == "endpoints":
  170. plural = r // exception. "endpoint" does not exist. Why?
  171. case strings.HasSuffix(r, "y"):
  172. plural = r[0:len(r)-1] + "ies"
  173. case strings.HasSuffix(r, "s"):
  174. plural = r + "es"
  175. default:
  176. plural = r + "s"
  177. }
  178. as = append(as, plural)
  179. plurals[plural] = struct{}{}
  180. }
  181. for sf, r := range shortForms {
  182. if _, found := plurals[r]; found {
  183. as = append(as, sf)
  184. }
  185. }
  186. return as
  187. }
  188. // parseFileSource parses the source given. Acceptable formats include:
  189. //
  190. // 1. source-path: the basename will become the key name
  191. // 2. source-name=source-path: the source-name will become the key name and source-path is the path to the key file
  192. //
  193. // Key names cannot include '='.
  194. func parseFileSource(source string) (keyName, filePath string, err error) {
  195. numSeparators := strings.Count(source, "=")
  196. switch {
  197. case numSeparators == 0:
  198. return path.Base(source), source, nil
  199. case numSeparators == 1 && strings.HasPrefix(source, "="):
  200. return "", "", fmt.Errorf("key name for file path %v missing.", strings.TrimPrefix(source, "="))
  201. case numSeparators == 1 && strings.HasSuffix(source, "="):
  202. return "", "", fmt.Errorf("file path for key name %v missing.", strings.TrimSuffix(source, "="))
  203. case numSeparators > 1:
  204. return "", "", errors.New("Key names or file paths cannot contain '='.")
  205. default:
  206. components := strings.Split(source, "=")
  207. return components[0], components[1], nil
  208. }
  209. }
  210. // parseLiteralSource parses the source key=val pair
  211. func parseLiteralSource(source string) (keyName, value string, err error) {
  212. // leading equal is invalid
  213. if strings.Index(source, "=") == 0 {
  214. return "", "", fmt.Errorf("invalid literal source %v, expected key=value", source)
  215. }
  216. // split after the first equal (so values can have the = character)
  217. items := strings.SplitN(source, "=", 2)
  218. if len(items) != 2 {
  219. return "", "", fmt.Errorf("invalid literal source %v, expected key=value", source)
  220. }
  221. return items[0], items[1], nil
  222. }