storage.go 9.0 KB

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