update_resources.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. Copyright 2018 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 utils
  14. import (
  15. "fmt"
  16. "time"
  17. "k8s.io/apimachinery/pkg/runtime/schema"
  18. "k8s.io/apimachinery/pkg/util/wait"
  19. scaleclient "k8s.io/client-go/scale"
  20. "k8s.io/kubectl/pkg/scale"
  21. )
  22. const (
  23. // Parameters for retrying updates/waits with linear backoff.
  24. // TODO: Try to move this to exponential backoff by modifying scale.Scale().
  25. updateRetryInterval = 5 * time.Second
  26. updateRetryTimeout = 1 * time.Minute
  27. waitRetryInterval = 5 * time.Second
  28. waitRetryTimeout = 5 * time.Minute
  29. )
  30. func RetryErrorCondition(condition wait.ConditionFunc) wait.ConditionFunc {
  31. return func() (bool, error) {
  32. done, err := condition()
  33. if err != nil && IsRetryableAPIError(err) {
  34. return false, nil
  35. }
  36. return done, err
  37. }
  38. }
  39. func ScaleResourceWithRetries(scalesGetter scaleclient.ScalesGetter, namespace, name string, size uint, gvr schema.GroupVersionResource) error {
  40. scaler := scale.NewScaler(scalesGetter)
  41. preconditions := &scale.ScalePrecondition{
  42. Size: -1,
  43. ResourceVersion: "",
  44. }
  45. waitForReplicas := scale.NewRetryParams(waitRetryInterval, waitRetryTimeout)
  46. cond := RetryErrorCondition(scale.ScaleCondition(scaler, preconditions, namespace, name, size, nil, gvr))
  47. err := wait.PollImmediate(updateRetryInterval, updateRetryTimeout, cond)
  48. if err == nil {
  49. err = scale.WaitForScaleHasDesiredReplicas(scalesGetter, gvr.GroupResource(), name, namespace, size, waitForReplicas)
  50. }
  51. if err != nil {
  52. return fmt.Errorf("Error while scaling %s to %d replicas: %v", name, size, err)
  53. }
  54. return nil
  55. }