restmapper.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. // TODO: move everything in this file to pkg/api/rest
  14. package meta
  15. import (
  16. "fmt"
  17. "sort"
  18. "strings"
  19. "k8s.io/apimachinery/pkg/runtime"
  20. "k8s.io/apimachinery/pkg/runtime/schema"
  21. )
  22. // Implements RESTScope interface
  23. type restScope struct {
  24. name RESTScopeName
  25. }
  26. func (r *restScope) Name() RESTScopeName {
  27. return r.name
  28. }
  29. var RESTScopeNamespace = &restScope{
  30. name: RESTScopeNameNamespace,
  31. }
  32. var RESTScopeRoot = &restScope{
  33. name: RESTScopeNameRoot,
  34. }
  35. // DefaultRESTMapper exposes mappings between the types defined in a
  36. // runtime.Scheme. It assumes that all types defined the provided scheme
  37. // can be mapped with the provided MetadataAccessor and Codec interfaces.
  38. //
  39. // The resource name of a Kind is defined as the lowercase,
  40. // English-plural version of the Kind string.
  41. // When converting from resource to Kind, the singular version of the
  42. // resource name is also accepted for convenience.
  43. //
  44. // TODO: Only accept plural for some operations for increased control?
  45. // (`get pod bar` vs `get pods bar`)
  46. type DefaultRESTMapper struct {
  47. defaultGroupVersions []schema.GroupVersion
  48. resourceToKind map[schema.GroupVersionResource]schema.GroupVersionKind
  49. kindToPluralResource map[schema.GroupVersionKind]schema.GroupVersionResource
  50. kindToScope map[schema.GroupVersionKind]RESTScope
  51. singularToPlural map[schema.GroupVersionResource]schema.GroupVersionResource
  52. pluralToSingular map[schema.GroupVersionResource]schema.GroupVersionResource
  53. }
  54. func (m *DefaultRESTMapper) String() string {
  55. return fmt.Sprintf("DefaultRESTMapper{kindToPluralResource=%v}", m.kindToPluralResource)
  56. }
  57. var _ RESTMapper = &DefaultRESTMapper{}
  58. // NewDefaultRESTMapper initializes a mapping between Kind and APIVersion
  59. // to a resource name and back based on the objects in a runtime.Scheme
  60. // and the Kubernetes API conventions. Takes a group name, a priority list of the versions
  61. // to search when an object has no default version (set empty to return an error),
  62. // and a function that retrieves the correct metadata for a given version.
  63. func NewDefaultRESTMapper(defaultGroupVersions []schema.GroupVersion) *DefaultRESTMapper {
  64. resourceToKind := make(map[schema.GroupVersionResource]schema.GroupVersionKind)
  65. kindToPluralResource := make(map[schema.GroupVersionKind]schema.GroupVersionResource)
  66. kindToScope := make(map[schema.GroupVersionKind]RESTScope)
  67. singularToPlural := make(map[schema.GroupVersionResource]schema.GroupVersionResource)
  68. pluralToSingular := make(map[schema.GroupVersionResource]schema.GroupVersionResource)
  69. // TODO: verify name mappings work correctly when versions differ
  70. return &DefaultRESTMapper{
  71. resourceToKind: resourceToKind,
  72. kindToPluralResource: kindToPluralResource,
  73. kindToScope: kindToScope,
  74. defaultGroupVersions: defaultGroupVersions,
  75. singularToPlural: singularToPlural,
  76. pluralToSingular: pluralToSingular,
  77. }
  78. }
  79. func (m *DefaultRESTMapper) Add(kind schema.GroupVersionKind, scope RESTScope) {
  80. plural, singular := UnsafeGuessKindToResource(kind)
  81. m.AddSpecific(kind, plural, singular, scope)
  82. }
  83. func (m *DefaultRESTMapper) AddSpecific(kind schema.GroupVersionKind, plural, singular schema.GroupVersionResource, scope RESTScope) {
  84. m.singularToPlural[singular] = plural
  85. m.pluralToSingular[plural] = singular
  86. m.resourceToKind[singular] = kind
  87. m.resourceToKind[plural] = kind
  88. m.kindToPluralResource[kind] = plural
  89. m.kindToScope[kind] = scope
  90. }
  91. // unpluralizedSuffixes is a list of resource suffixes that are the same plural and singular
  92. // This is only is only necessary because some bits of code are lazy and don't actually use the RESTMapper like they should.
  93. // TODO eliminate this so that different callers can correctly map to resources. This probably means updating all
  94. // callers to use the RESTMapper they mean.
  95. var unpluralizedSuffixes = []string{
  96. "endpoints",
  97. }
  98. // UnsafeGuessKindToResource converts Kind to a resource name.
  99. // Broken. This method only "sort of" works when used outside of this package. It assumes that Kinds and Resources match
  100. // and they aren't guaranteed to do so.
  101. func UnsafeGuessKindToResource(kind schema.GroupVersionKind) ( /*plural*/ schema.GroupVersionResource /*singular*/, schema.GroupVersionResource) {
  102. kindName := kind.Kind
  103. if len(kindName) == 0 {
  104. return schema.GroupVersionResource{}, schema.GroupVersionResource{}
  105. }
  106. singularName := strings.ToLower(kindName)
  107. singular := kind.GroupVersion().WithResource(singularName)
  108. for _, skip := range unpluralizedSuffixes {
  109. if strings.HasSuffix(singularName, skip) {
  110. return singular, singular
  111. }
  112. }
  113. switch string(singularName[len(singularName)-1]) {
  114. case "s":
  115. return kind.GroupVersion().WithResource(singularName + "es"), singular
  116. case "y":
  117. return kind.GroupVersion().WithResource(strings.TrimSuffix(singularName, "y") + "ies"), singular
  118. }
  119. return kind.GroupVersion().WithResource(singularName + "s"), singular
  120. }
  121. // ResourceSingularizer implements RESTMapper
  122. // It converts a resource name from plural to singular (e.g., from pods to pod)
  123. func (m *DefaultRESTMapper) ResourceSingularizer(resourceType string) (string, error) {
  124. partialResource := schema.GroupVersionResource{Resource: resourceType}
  125. resources, err := m.ResourcesFor(partialResource)
  126. if err != nil {
  127. return resourceType, err
  128. }
  129. singular := schema.GroupVersionResource{}
  130. for _, curr := range resources {
  131. currSingular, ok := m.pluralToSingular[curr]
  132. if !ok {
  133. continue
  134. }
  135. if singular.Empty() {
  136. singular = currSingular
  137. continue
  138. }
  139. if currSingular.Resource != singular.Resource {
  140. return resourceType, fmt.Errorf("multiple possible singular resources (%v) found for %v", resources, resourceType)
  141. }
  142. }
  143. if singular.Empty() {
  144. return resourceType, fmt.Errorf("no singular of resource %v has been defined", resourceType)
  145. }
  146. return singular.Resource, nil
  147. }
  148. // coerceResourceForMatching makes the resource lower case and converts internal versions to unspecified (legacy behavior)
  149. func coerceResourceForMatching(resource schema.GroupVersionResource) schema.GroupVersionResource {
  150. resource.Resource = strings.ToLower(resource.Resource)
  151. if resource.Version == runtime.APIVersionInternal {
  152. resource.Version = ""
  153. }
  154. return resource
  155. }
  156. func (m *DefaultRESTMapper) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
  157. resource := coerceResourceForMatching(input)
  158. hasResource := len(resource.Resource) > 0
  159. hasGroup := len(resource.Group) > 0
  160. hasVersion := len(resource.Version) > 0
  161. if !hasResource {
  162. return nil, fmt.Errorf("a resource must be present, got: %v", resource)
  163. }
  164. ret := []schema.GroupVersionResource{}
  165. switch {
  166. case hasGroup && hasVersion:
  167. // fully qualified. Find the exact match
  168. for plural, singular := range m.pluralToSingular {
  169. if singular == resource {
  170. ret = append(ret, plural)
  171. break
  172. }
  173. if plural == resource {
  174. ret = append(ret, plural)
  175. break
  176. }
  177. }
  178. case hasGroup:
  179. // given a group, prefer an exact match. If you don't find one, resort to a prefix match on group
  180. foundExactMatch := false
  181. requestedGroupResource := resource.GroupResource()
  182. for plural, singular := range m.pluralToSingular {
  183. if singular.GroupResource() == requestedGroupResource {
  184. foundExactMatch = true
  185. ret = append(ret, plural)
  186. }
  187. if plural.GroupResource() == requestedGroupResource {
  188. foundExactMatch = true
  189. ret = append(ret, plural)
  190. }
  191. }
  192. // if you didn't find an exact match, match on group prefixing. This allows storageclass.storage to match
  193. // storageclass.storage.k8s.io
  194. if !foundExactMatch {
  195. for plural, singular := range m.pluralToSingular {
  196. if !strings.HasPrefix(plural.Group, requestedGroupResource.Group) {
  197. continue
  198. }
  199. if singular.Resource == requestedGroupResource.Resource {
  200. ret = append(ret, plural)
  201. }
  202. if plural.Resource == requestedGroupResource.Resource {
  203. ret = append(ret, plural)
  204. }
  205. }
  206. }
  207. case hasVersion:
  208. for plural, singular := range m.pluralToSingular {
  209. if singular.Version == resource.Version && singular.Resource == resource.Resource {
  210. ret = append(ret, plural)
  211. }
  212. if plural.Version == resource.Version && plural.Resource == resource.Resource {
  213. ret = append(ret, plural)
  214. }
  215. }
  216. default:
  217. for plural, singular := range m.pluralToSingular {
  218. if singular.Resource == resource.Resource {
  219. ret = append(ret, plural)
  220. }
  221. if plural.Resource == resource.Resource {
  222. ret = append(ret, plural)
  223. }
  224. }
  225. }
  226. if len(ret) == 0 {
  227. return nil, &NoResourceMatchError{PartialResource: resource}
  228. }
  229. sort.Sort(resourceByPreferredGroupVersion{ret, m.defaultGroupVersions})
  230. return ret, nil
  231. }
  232. func (m *DefaultRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {
  233. resources, err := m.ResourcesFor(resource)
  234. if err != nil {
  235. return schema.GroupVersionResource{}, err
  236. }
  237. if len(resources) == 1 {
  238. return resources[0], nil
  239. }
  240. return schema.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: resource, MatchingResources: resources}
  241. }
  242. func (m *DefaultRESTMapper) KindsFor(input schema.GroupVersionResource) ([]schema.GroupVersionKind, error) {
  243. resource := coerceResourceForMatching(input)
  244. hasResource := len(resource.Resource) > 0
  245. hasGroup := len(resource.Group) > 0
  246. hasVersion := len(resource.Version) > 0
  247. if !hasResource {
  248. return nil, fmt.Errorf("a resource must be present, got: %v", resource)
  249. }
  250. ret := []schema.GroupVersionKind{}
  251. switch {
  252. // fully qualified. Find the exact match
  253. case hasGroup && hasVersion:
  254. kind, exists := m.resourceToKind[resource]
  255. if exists {
  256. ret = append(ret, kind)
  257. }
  258. case hasGroup:
  259. foundExactMatch := false
  260. requestedGroupResource := resource.GroupResource()
  261. for currResource, currKind := range m.resourceToKind {
  262. if currResource.GroupResource() == requestedGroupResource {
  263. foundExactMatch = true
  264. ret = append(ret, currKind)
  265. }
  266. }
  267. // if you didn't find an exact match, match on group prefixing. This allows storageclass.storage to match
  268. // storageclass.storage.k8s.io
  269. if !foundExactMatch {
  270. for currResource, currKind := range m.resourceToKind {
  271. if !strings.HasPrefix(currResource.Group, requestedGroupResource.Group) {
  272. continue
  273. }
  274. if currResource.Resource == requestedGroupResource.Resource {
  275. ret = append(ret, currKind)
  276. }
  277. }
  278. }
  279. case hasVersion:
  280. for currResource, currKind := range m.resourceToKind {
  281. if currResource.Version == resource.Version && currResource.Resource == resource.Resource {
  282. ret = append(ret, currKind)
  283. }
  284. }
  285. default:
  286. for currResource, currKind := range m.resourceToKind {
  287. if currResource.Resource == resource.Resource {
  288. ret = append(ret, currKind)
  289. }
  290. }
  291. }
  292. if len(ret) == 0 {
  293. return nil, &NoResourceMatchError{PartialResource: input}
  294. }
  295. sort.Sort(kindByPreferredGroupVersion{ret, m.defaultGroupVersions})
  296. return ret, nil
  297. }
  298. func (m *DefaultRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
  299. kinds, err := m.KindsFor(resource)
  300. if err != nil {
  301. return schema.GroupVersionKind{}, err
  302. }
  303. if len(kinds) == 1 {
  304. return kinds[0], nil
  305. }
  306. return schema.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds}
  307. }
  308. type kindByPreferredGroupVersion struct {
  309. list []schema.GroupVersionKind
  310. sortOrder []schema.GroupVersion
  311. }
  312. func (o kindByPreferredGroupVersion) Len() int { return len(o.list) }
  313. func (o kindByPreferredGroupVersion) Swap(i, j int) { o.list[i], o.list[j] = o.list[j], o.list[i] }
  314. func (o kindByPreferredGroupVersion) Less(i, j int) bool {
  315. lhs := o.list[i]
  316. rhs := o.list[j]
  317. if lhs == rhs {
  318. return false
  319. }
  320. if lhs.GroupVersion() == rhs.GroupVersion() {
  321. return lhs.Kind < rhs.Kind
  322. }
  323. // otherwise, the difference is in the GroupVersion, so we need to sort with respect to the preferred order
  324. lhsIndex := -1
  325. rhsIndex := -1
  326. for i := range o.sortOrder {
  327. if o.sortOrder[i] == lhs.GroupVersion() {
  328. lhsIndex = i
  329. }
  330. if o.sortOrder[i] == rhs.GroupVersion() {
  331. rhsIndex = i
  332. }
  333. }
  334. if rhsIndex == -1 {
  335. return true
  336. }
  337. return lhsIndex < rhsIndex
  338. }
  339. type resourceByPreferredGroupVersion struct {
  340. list []schema.GroupVersionResource
  341. sortOrder []schema.GroupVersion
  342. }
  343. func (o resourceByPreferredGroupVersion) Len() int { return len(o.list) }
  344. func (o resourceByPreferredGroupVersion) Swap(i, j int) { o.list[i], o.list[j] = o.list[j], o.list[i] }
  345. func (o resourceByPreferredGroupVersion) Less(i, j int) bool {
  346. lhs := o.list[i]
  347. rhs := o.list[j]
  348. if lhs == rhs {
  349. return false
  350. }
  351. if lhs.GroupVersion() == rhs.GroupVersion() {
  352. return lhs.Resource < rhs.Resource
  353. }
  354. // otherwise, the difference is in the GroupVersion, so we need to sort with respect to the preferred order
  355. lhsIndex := -1
  356. rhsIndex := -1
  357. for i := range o.sortOrder {
  358. if o.sortOrder[i] == lhs.GroupVersion() {
  359. lhsIndex = i
  360. }
  361. if o.sortOrder[i] == rhs.GroupVersion() {
  362. rhsIndex = i
  363. }
  364. }
  365. if rhsIndex == -1 {
  366. return true
  367. }
  368. return lhsIndex < rhsIndex
  369. }
  370. // RESTMapping returns a struct representing the resource path and conversion interfaces a
  371. // RESTClient should use to operate on the provided group/kind in order of versions. If a version search
  372. // order is not provided, the search order provided to DefaultRESTMapper will be used to resolve which
  373. // version should be used to access the named group/kind.
  374. func (m *DefaultRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {
  375. mappings, err := m.RESTMappings(gk, versions...)
  376. if err != nil {
  377. return nil, err
  378. }
  379. if len(mappings) == 0 {
  380. return nil, &NoKindMatchError{GroupKind: gk, SearchedVersions: versions}
  381. }
  382. // since we rely on RESTMappings method
  383. // take the first match and return to the caller
  384. // as this was the existing behavior.
  385. return mappings[0], nil
  386. }
  387. // RESTMappings returns the RESTMappings for the provided group kind. If a version search order
  388. // is not provided, the search order provided to DefaultRESTMapper will be used.
  389. func (m *DefaultRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {
  390. mappings := make([]*RESTMapping, 0)
  391. potentialGVK := make([]schema.GroupVersionKind, 0)
  392. hadVersion := false
  393. // Pick an appropriate version
  394. for _, version := range versions {
  395. if len(version) == 0 || version == runtime.APIVersionInternal {
  396. continue
  397. }
  398. currGVK := gk.WithVersion(version)
  399. hadVersion = true
  400. if _, ok := m.kindToPluralResource[currGVK]; ok {
  401. potentialGVK = append(potentialGVK, currGVK)
  402. break
  403. }
  404. }
  405. // Use the default preferred versions
  406. if !hadVersion && len(potentialGVK) == 0 {
  407. for _, gv := range m.defaultGroupVersions {
  408. if gv.Group != gk.Group {
  409. continue
  410. }
  411. potentialGVK = append(potentialGVK, gk.WithVersion(gv.Version))
  412. }
  413. }
  414. if len(potentialGVK) == 0 {
  415. return nil, &NoKindMatchError{GroupKind: gk, SearchedVersions: versions}
  416. }
  417. for _, gvk := range potentialGVK {
  418. //Ensure we have a REST mapping
  419. res, ok := m.kindToPluralResource[gvk]
  420. if !ok {
  421. continue
  422. }
  423. // Ensure we have a REST scope
  424. scope, ok := m.kindToScope[gvk]
  425. if !ok {
  426. return nil, fmt.Errorf("the provided version %q and kind %q cannot be mapped to a supported scope", gvk.GroupVersion(), gvk.Kind)
  427. }
  428. mappings = append(mappings, &RESTMapping{
  429. Resource: res,
  430. GroupVersionKind: gvk,
  431. Scope: scope,
  432. })
  433. }
  434. if len(mappings) == 0 {
  435. return nil, &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Group: gk.Group, Resource: gk.Kind}}
  436. }
  437. return mappings, nil
  438. }