autoscale.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. Copyright 2015 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 versioned
  14. import (
  15. "fmt"
  16. autoscalingv1 "k8s.io/api/autoscaling/v1"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. "k8s.io/apimachinery/pkg/runtime"
  19. "k8s.io/kubernetes/pkg/kubectl/generate"
  20. )
  21. // HorizontalPodAutoscalerGeneratorV1 supports stable generation of a horizontal pod autoscaler.
  22. type HorizontalPodAutoscalerGeneratorV1 struct {
  23. Name string
  24. ScaleRefKind string
  25. ScaleRefName string
  26. ScaleRefAPIVersion string
  27. MinReplicas int32
  28. MaxReplicas int32
  29. CPUPercent int32
  30. }
  31. // Ensure it supports the generator pattern that uses parameters specified during construction.
  32. var _ generate.StructuredGenerator = &HorizontalPodAutoscalerGeneratorV1{}
  33. // StructuredGenerate outputs a horizontal pod autoscaler object using the configured fields.
  34. func (s *HorizontalPodAutoscalerGeneratorV1) StructuredGenerate() (runtime.Object, error) {
  35. if err := s.validate(); err != nil {
  36. return nil, err
  37. }
  38. scaler := autoscalingv1.HorizontalPodAutoscaler{
  39. ObjectMeta: metav1.ObjectMeta{
  40. Name: s.Name,
  41. },
  42. Spec: autoscalingv1.HorizontalPodAutoscalerSpec{
  43. ScaleTargetRef: autoscalingv1.CrossVersionObjectReference{
  44. Kind: s.ScaleRefKind,
  45. Name: s.ScaleRefName,
  46. APIVersion: s.ScaleRefAPIVersion,
  47. },
  48. MaxReplicas: s.MaxReplicas,
  49. },
  50. }
  51. if s.MinReplicas > 0 {
  52. v := int32(s.MinReplicas)
  53. scaler.Spec.MinReplicas = &v
  54. }
  55. if s.CPUPercent >= 0 {
  56. c := int32(s.CPUPercent)
  57. scaler.Spec.TargetCPUUtilizationPercentage = &c
  58. }
  59. return &scaler, nil
  60. }
  61. // validate check if the caller has set the right fields.
  62. func (s HorizontalPodAutoscalerGeneratorV1) validate() error {
  63. if len(s.Name) == 0 {
  64. return fmt.Errorf("name must be specified")
  65. }
  66. if s.MaxReplicas < 1 {
  67. return fmt.Errorf("'max' is a required parameter and must be at least 1")
  68. }
  69. if s.MinReplicas > s.MaxReplicas {
  70. return fmt.Errorf("'max' must be greater than or equal to 'min'")
  71. }
  72. return nil
  73. }