Debian Codegraph @

pkg/storageversion/updater.go

raw
1 /*
2 Copyright 2020 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package storageversion
18
19 import (
20 "context"
21 "fmt"
22 "time"
23
24 "k8s.io/api/apiserverinternal/v1alpha1"
25 apierrors "k8s.io/apimachinery/pkg/api/errors"
26 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27 "k8s.io/apimachinery/pkg/runtime/schema"
28 "k8s.io/klog/v2"
29 )
30
31 // Client has the methods required to update the storage version.
32 type Client interface {
33 Create(context.Context, *v1alpha1.StorageVersion, metav1.CreateOptions) (*v1alpha1.StorageVersion, error)
34 UpdateStatus(context.Context, *v1alpha1.StorageVersion, metav1.UpdateOptions) (*v1alpha1.StorageVersion, error)
35 Get(context.Context, string, metav1.GetOptions) (*v1alpha1.StorageVersion, error)
36 }
37
38 // SetCommonEncodingVersion updates the CommonEncodingVersion and the AllEncodingVersionsEqual
39 // condition based on the StorageVersions.
40 func SetCommonEncodingVersion(sv *v1alpha1.StorageVersion) {
41 var oldCommonEncodingVersion *string
42 if sv.Status.CommonEncodingVersion != nil {
43 version := *sv.Status.CommonEncodingVersion
44 oldCommonEncodingVersion = &version
45 }
46 sv.Status.CommonEncodingVersion = nil
47 if len(sv.Status.StorageVersions) != 0 {
48 firstVersion := sv.Status.StorageVersions[0].EncodingVersion
49 agreed := true
50 for _, ssv := range sv.Status.StorageVersions {
51 if ssv.EncodingVersion != firstVersion {
52 agreed = false
53 break
54 }
55 }
56 if agreed {
57 sv.Status.CommonEncodingVersion = &firstVersion
58 }
59 }
60
61 condition := v1alpha1.StorageVersionCondition{
62 Type: v1alpha1.AllEncodingVersionsEqual,
63 Status: v1alpha1.ConditionFalse,
64 ObservedGeneration: sv.Generation,
65 LastTransitionTime: metav1.NewTime(time.Now()),
66 Reason: "CommonEncodingVersionUnset",
67 Message: "Common encoding version unset",
68 }
69 if sv.Status.CommonEncodingVersion != nil {
70 condition.Status = v1alpha1.ConditionTrue
71 condition.Reason = "CommonEncodingVersionSet"
72 condition.Message = "Common encoding version set"
73 }
74 forceTransition := false
75 if oldCommonEncodingVersion != nil && sv.Status.CommonEncodingVersion != nil &&
76 *oldCommonEncodingVersion != *sv.Status.CommonEncodingVersion {
77 forceTransition = true
78 }
79 setStatusCondition(&sv.Status.Conditions, condition, forceTransition)
80 }
81
82 func findStatusCondition(conditions []v1alpha1.StorageVersionCondition,
83 conditionType v1alpha1.StorageVersionConditionType) *v1alpha1.StorageVersionCondition {
84 for i := range conditions {
85 if conditions[i].Type == conditionType {
86 return &conditions[i]
87 }
88 }
89 return nil
90 }
91
92 // setStatusCondition sets the corresponding condition in conditions to newCondition.
93 // conditions must be non-nil.
94 // 1. if the condition of the specified type already exists: all fields of the existing condition are updated to
95 // newCondition, LastTransitionTime is set to now if the new status differs from the old status
96 // 2. if a condition of the specified type does not exist: LastTransitionTime is set to now() if unset,
97 // and newCondition is appended
98 //
99 // NOTE: forceTransition allows overwriting LastTransitionTime even when the status doesn't change.
100 func setStatusCondition(conditions *[]v1alpha1.StorageVersionCondition, newCondition v1alpha1.StorageVersionCondition,
101 forceTransition bool) {
102 if conditions == nil {
103 return
104 }
105
106 if newCondition.LastTransitionTime.IsZero() {
107 newCondition.LastTransitionTime = metav1.NewTime(time.Now())
108 }
109 existingCondition := findStatusCondition(*conditions, newCondition.Type)
110 if existingCondition == nil {
111 *conditions = append(*conditions, newCondition)
112 return
113 }
114
115 statusChanged := existingCondition.Status != newCondition.Status
116 if statusChanged || forceTransition {
117 existingCondition.LastTransitionTime = newCondition.LastTransitionTime
118 }
119 existingCondition.Status = newCondition.Status
120 existingCondition.Reason = newCondition.Reason
121 existingCondition.Message = newCondition.Message
122 existingCondition.ObservedGeneration = newCondition.ObservedGeneration
123 }
124
125 // updateStorageVersionFor updates the storage version object for the resource.
126 func updateStorageVersionFor(c Client, apiserverID string, gr schema.GroupResource, encodingVersion string, decodableVersions []string, servedVersions []string) error {
127 retries := 3
128 var retry int
129 var err error
130 for retry < retries {
131 err = singleUpdate(c, apiserverID, gr, encodingVersion, decodableVersions, servedVersions)
132 if err == nil {
133 return nil
134 }
135 if apierrors.IsAlreadyExists(err) || apierrors.IsConflict(err) {
136 time.Sleep(1 * time.Second)
137 continue
138 }
139 if err != nil {
140 klog.Errorf("retry %d, failed to update storage version for %v: %v", retry, gr, err)
141 retry++
142 time.Sleep(1 * time.Second)
143 }
144 }
145 return err
146 }
147
148 func singleUpdate(c Client, apiserverID string, gr schema.GroupResource, encodingVersion string, decodableVersions []string, servedVersions []string) error {
149 shouldCreate := false
150 name := fmt.Sprintf("%s.%s", gr.Group, gr.Resource)
151 sv, err := c.Get(context.TODO(), name, metav1.GetOptions{})
152 if err != nil && !apierrors.IsNotFound(err) {
153 return err
154 }
155 if apierrors.IsNotFound(err) {
156 shouldCreate = true
157 sv = &v1alpha1.StorageVersion{}
158 sv.ObjectMeta.Name = name
159 }
160 updatedSV := localUpdateStorageVersion(sv, apiserverID, encodingVersion, decodableVersions, servedVersions)
161 if shouldCreate {
162 createdSV, err := c.Create(context.TODO(), updatedSV, metav1.CreateOptions{})
163 if err != nil {
164 return err
165 }
166 // assign the calculated status to the object just created, then update status
167 createdSV.Status = updatedSV.Status
168 _, err = c.UpdateStatus(context.TODO(), createdSV, metav1.UpdateOptions{})
169 return err
170 }
171 _, err = c.UpdateStatus(context.TODO(), updatedSV, metav1.UpdateOptions{})
172 return err
173 }
174
175 // localUpdateStorageVersion updates the input storageversion with given server storageversion info.
176 // The function updates the input storageversion in place.
177 func localUpdateStorageVersion(sv *v1alpha1.StorageVersion, apiserverID, encodingVersion string, decodableVersions []string, servedVersions []string) *v1alpha1.StorageVersion {
178 newSSV := v1alpha1.ServerStorageVersion{
179 APIServerID: apiserverID,
180 EncodingVersion: encodingVersion,
181 DecodableVersions: decodableVersions,
182 ServedVersions: servedVersions,
183 }
184 foundSSV := false
185 for i, ssv := range sv.Status.StorageVersions {
186 if ssv.APIServerID == apiserverID {
187 sv.Status.StorageVersions[i] = newSSV
188 foundSSV = true
189 break
190 }
191 }
192 if !foundSSV {
193 sv.Status.StorageVersions = append(sv.Status.StorageVersions, newSSV)
194 }
195 SetCommonEncodingVersion(sv)
196 return sv
197 }