status.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. Copyright 2021 The Rook Authors. All rights reserved.
  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 v1
  14. import (
  15. "time"
  16. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  17. )
  18. // SetStatusCondition sets the corresponding condition in conditions to newCondition.
  19. // conditions must be non-nil.
  20. // 1. if the condition of the specified type already exists (all fields of the existing condition are updated to
  21. // newCondition, LastTransitionTime is set to now if the new status differs from the old status)
  22. // 2. if a condition of the specified type does not exist (LastTransitionTime is set to now() if unset, and newCondition is appended)
  23. func SetStatusCondition(conditions *[]Condition, newCondition Condition) {
  24. if conditions == nil {
  25. return
  26. }
  27. now := metav1.NewTime(time.Now())
  28. existingCondition := FindStatusCondition(*conditions, newCondition.Type)
  29. if existingCondition == nil {
  30. if newCondition.LastTransitionTime.IsZero() {
  31. newCondition.LastTransitionTime = now
  32. newCondition.LastHeartbeatTime = now
  33. }
  34. *conditions = append(*conditions, newCondition)
  35. return
  36. }
  37. if existingCondition.Status != newCondition.Status {
  38. existingCondition.Status = newCondition.Status
  39. if !newCondition.LastTransitionTime.IsZero() {
  40. existingCondition.LastTransitionTime = newCondition.LastTransitionTime
  41. } else {
  42. existingCondition.LastTransitionTime = now
  43. }
  44. }
  45. existingCondition.Reason = newCondition.Reason
  46. existingCondition.Message = newCondition.Message
  47. if !newCondition.LastHeartbeatTime.IsZero() {
  48. existingCondition.LastHeartbeatTime = newCondition.LastHeartbeatTime
  49. } else {
  50. existingCondition.LastHeartbeatTime = now
  51. }
  52. }
  53. // FindStatusCondition finds the conditionType in conditions.
  54. func FindStatusCondition(conditions []Condition, conditionType ConditionType) *Condition {
  55. for i := range conditions {
  56. if conditions[i].Type == conditionType {
  57. return &conditions[i]
  58. }
  59. }
  60. return nil
  61. }