storage.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /*
  2. Copyright 2016 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. // If you make changes to this file, you should also make the corresponding change in ReplicationController.
  14. package storage
  15. import (
  16. "context"
  17. "fmt"
  18. "k8s.io/apimachinery/pkg/api/errors"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/runtime"
  21. "k8s.io/apimachinery/pkg/runtime/schema"
  22. "k8s.io/apiserver/pkg/registry/generic"
  23. genericregistry "k8s.io/apiserver/pkg/registry/generic/registry"
  24. "k8s.io/apiserver/pkg/registry/rest"
  25. "k8s.io/kubernetes/pkg/apis/apps"
  26. appsv1beta1 "k8s.io/kubernetes/pkg/apis/apps/v1beta1"
  27. appsv1beta2 "k8s.io/kubernetes/pkg/apis/apps/v1beta2"
  28. "k8s.io/kubernetes/pkg/apis/autoscaling"
  29. autoscalingv1 "k8s.io/kubernetes/pkg/apis/autoscaling/v1"
  30. autoscalingvalidation "k8s.io/kubernetes/pkg/apis/autoscaling/validation"
  31. extensionsv1beta1 "k8s.io/kubernetes/pkg/apis/extensions/v1beta1"
  32. "k8s.io/kubernetes/pkg/printers"
  33. printersinternal "k8s.io/kubernetes/pkg/printers/internalversion"
  34. printerstorage "k8s.io/kubernetes/pkg/printers/storage"
  35. "k8s.io/kubernetes/pkg/registry/apps/replicaset"
  36. )
  37. // ReplicaSetStorage includes dummy storage for ReplicaSets and for Scale subresource.
  38. type ReplicaSetStorage struct {
  39. ReplicaSet *REST
  40. Status *StatusREST
  41. Scale *ScaleREST
  42. }
  43. func NewStorage(optsGetter generic.RESTOptionsGetter) ReplicaSetStorage {
  44. replicaSetRest, replicaSetStatusRest := NewREST(optsGetter)
  45. return ReplicaSetStorage{
  46. ReplicaSet: replicaSetRest,
  47. Status: replicaSetStatusRest,
  48. Scale: &ScaleREST{store: replicaSetRest.Store},
  49. }
  50. }
  51. type REST struct {
  52. *genericregistry.Store
  53. categories []string
  54. }
  55. // NewREST returns a RESTStorage object that will work against ReplicaSet.
  56. func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST) {
  57. store := &genericregistry.Store{
  58. NewFunc: func() runtime.Object { return &apps.ReplicaSet{} },
  59. NewListFunc: func() runtime.Object { return &apps.ReplicaSetList{} },
  60. PredicateFunc: replicaset.MatchReplicaSet,
  61. DefaultQualifiedResource: apps.Resource("replicasets"),
  62. CreateStrategy: replicaset.Strategy,
  63. UpdateStrategy: replicaset.Strategy,
  64. DeleteStrategy: replicaset.Strategy,
  65. TableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},
  66. }
  67. options := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: replicaset.GetAttrs}
  68. if err := store.CompleteWithOptions(options); err != nil {
  69. panic(err) // TODO: Propagate error up
  70. }
  71. statusStore := *store
  72. statusStore.UpdateStrategy = replicaset.StatusStrategy
  73. return &REST{store, []string{"all"}}, &StatusREST{store: &statusStore}
  74. }
  75. // Implement ShortNamesProvider
  76. var _ rest.ShortNamesProvider = &REST{}
  77. // ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.
  78. func (r *REST) ShortNames() []string {
  79. return []string{"rs"}
  80. }
  81. // Implement CategoriesProvider
  82. var _ rest.CategoriesProvider = &REST{}
  83. // Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.
  84. func (r *REST) Categories() []string {
  85. return r.categories
  86. }
  87. func (r *REST) WithCategories(categories []string) *REST {
  88. r.categories = categories
  89. return r
  90. }
  91. // StatusREST implements the REST endpoint for changing the status of a ReplicaSet
  92. type StatusREST struct {
  93. store *genericregistry.Store
  94. }
  95. func (r *StatusREST) New() runtime.Object {
  96. return &apps.ReplicaSet{}
  97. }
  98. // Get retrieves the object from the storage. It is required to support Patch.
  99. func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
  100. return r.store.Get(ctx, name, options)
  101. }
  102. // Update alters the status subset of an object.
  103. func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {
  104. // We are explicitly setting forceAllowCreate to false in the call to the underlying storage because
  105. // subresources should never allow create on update.
  106. return r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)
  107. }
  108. type ScaleREST struct {
  109. store *genericregistry.Store
  110. }
  111. // ScaleREST implements Patcher
  112. var _ = rest.Patcher(&ScaleREST{})
  113. var _ = rest.GroupVersionKindProvider(&ScaleREST{})
  114. func (r *ScaleREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind {
  115. switch containingGV {
  116. case extensionsv1beta1.SchemeGroupVersion:
  117. return extensionsv1beta1.SchemeGroupVersion.WithKind("Scale")
  118. case appsv1beta1.SchemeGroupVersion:
  119. return appsv1beta1.SchemeGroupVersion.WithKind("Scale")
  120. case appsv1beta2.SchemeGroupVersion:
  121. return appsv1beta2.SchemeGroupVersion.WithKind("Scale")
  122. default:
  123. return autoscalingv1.SchemeGroupVersion.WithKind("Scale")
  124. }
  125. }
  126. // New creates a new Scale object
  127. func (r *ScaleREST) New() runtime.Object {
  128. return &autoscaling.Scale{}
  129. }
  130. func (r *ScaleREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
  131. obj, err := r.store.Get(ctx, name, options)
  132. if err != nil {
  133. return nil, errors.NewNotFound(apps.Resource("replicasets/scale"), name)
  134. }
  135. rs := obj.(*apps.ReplicaSet)
  136. scale, err := scaleFromReplicaSet(rs)
  137. if err != nil {
  138. return nil, errors.NewBadRequest(fmt.Sprintf("%v", err))
  139. }
  140. return scale, err
  141. }
  142. func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {
  143. obj, err := r.store.Get(ctx, name, &metav1.GetOptions{})
  144. if err != nil {
  145. return nil, false, errors.NewNotFound(apps.Resource("replicasets/scale"), name)
  146. }
  147. rs := obj.(*apps.ReplicaSet)
  148. oldScale, err := scaleFromReplicaSet(rs)
  149. if err != nil {
  150. return nil, false, err
  151. }
  152. // TODO: should this pass admission?
  153. obj, err = objInfo.UpdatedObject(ctx, oldScale)
  154. if err != nil {
  155. return nil, false, err
  156. }
  157. if obj == nil {
  158. return nil, false, errors.NewBadRequest(fmt.Sprintf("nil update passed to Scale"))
  159. }
  160. scale, ok := obj.(*autoscaling.Scale)
  161. if !ok {
  162. return nil, false, errors.NewBadRequest(fmt.Sprintf("wrong object passed to Scale update: %v", obj))
  163. }
  164. if errs := autoscalingvalidation.ValidateScale(scale); len(errs) > 0 {
  165. return nil, false, errors.NewInvalid(autoscaling.Kind("Scale"), scale.Name, errs)
  166. }
  167. rs.Spec.Replicas = scale.Spec.Replicas
  168. rs.ResourceVersion = scale.ResourceVersion
  169. obj, _, err = r.store.Update(
  170. ctx,
  171. rs.Name,
  172. rest.DefaultUpdatedObjectInfo(rs),
  173. toScaleCreateValidation(createValidation),
  174. toScaleUpdateValidation(updateValidation),
  175. false,
  176. options,
  177. )
  178. if err != nil {
  179. return nil, false, err
  180. }
  181. rs = obj.(*apps.ReplicaSet)
  182. newScale, err := scaleFromReplicaSet(rs)
  183. if err != nil {
  184. return nil, false, errors.NewBadRequest(fmt.Sprintf("%v", err))
  185. }
  186. return newScale, false, err
  187. }
  188. func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc {
  189. return func(obj runtime.Object) error {
  190. scale, err := scaleFromReplicaSet(obj.(*apps.ReplicaSet))
  191. if err != nil {
  192. return err
  193. }
  194. return f(scale)
  195. }
  196. }
  197. func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc {
  198. return func(obj, old runtime.Object) error {
  199. newScale, err := scaleFromReplicaSet(obj.(*apps.ReplicaSet))
  200. if err != nil {
  201. return err
  202. }
  203. oldScale, err := scaleFromReplicaSet(old.(*apps.ReplicaSet))
  204. if err != nil {
  205. return err
  206. }
  207. return f(newScale, oldScale)
  208. }
  209. }
  210. // scaleFromReplicaSet returns a scale subresource for a replica set.
  211. func scaleFromReplicaSet(rs *apps.ReplicaSet) (*autoscaling.Scale, error) {
  212. selector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector)
  213. if err != nil {
  214. return nil, err
  215. }
  216. return &autoscaling.Scale{
  217. // TODO: Create a variant of ObjectMeta type that only contains the fields below.
  218. ObjectMeta: metav1.ObjectMeta{
  219. Name: rs.Name,
  220. Namespace: rs.Namespace,
  221. UID: rs.UID,
  222. ResourceVersion: rs.ResourceVersion,
  223. CreationTimestamp: rs.CreationTimestamp,
  224. },
  225. Spec: autoscaling.ScaleSpec{
  226. Replicas: rs.Spec.Replicas,
  227. },
  228. Status: autoscaling.ScaleStatus{
  229. Replicas: rs.Status.Replicas,
  230. Selector: selector.String(),
  231. },
  232. }, nil
  233. }