-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
RollableScalableResourceOperation.java
262 lines (219 loc) · 9.05 KB
/
RollableScalableResourceOperation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.kubernetes.client.dsl.internal.apps.v1;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesResourceList;
import io.fabric8.kubernetes.api.model.autoscaling.v1.Scale;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.KubernetesClientTimeoutException;
import io.fabric8.kubernetes.client.dsl.ImageEditReplacePatchable;
import io.fabric8.kubernetes.client.dsl.LogWatch;
import io.fabric8.kubernetes.client.dsl.Loggable;
import io.fabric8.kubernetes.client.dsl.Resource;
import io.fabric8.kubernetes.client.dsl.RollableScalableResource;
import io.fabric8.kubernetes.client.dsl.TimeoutImageEditReplacePatchable;
import io.fabric8.kubernetes.client.dsl.base.PatchContext;
import io.fabric8.kubernetes.client.dsl.base.PatchType;
import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperation;
import io.fabric8.kubernetes.client.dsl.internal.OperationContext;
import io.fabric8.kubernetes.client.dsl.internal.RollingOperationContext;
import io.fabric8.kubernetes.client.utils.Serialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.UnaryOperator;
/**
* Operations for resources that represent scalable, rolling-updatable sets of Pods.
*/
public abstract class RollableScalableResourceOperation<T extends HasMetadata, L extends KubernetesResourceList<T>, R extends Resource<T>>
extends HasMetadataOperation<T, L, R> implements RollableScalableResource<T>, TimeoutImageEditReplacePatchable<T> {
private static final Logger Log = LoggerFactory.getLogger(RollableScalableResourceOperation.class);
protected final RollingOperationContext rollingOperationContext;
final boolean rolling;
final long rollingTimeout;
final TimeUnit rollingTimeUnit;
protected RollableScalableResourceOperation(RollingOperationContext context, OperationContext superContext, Class<T> type,
Class<L> listType) {
super(superContext, type, listType);
this.rollingOperationContext = context;
this.rolling = context.getRolling();
this.rollingTimeout = context.getRollingTimeout();
this.rollingTimeUnit = context.getRollingTimeUnit();
}
protected abstract T withReplicas(int count);
protected abstract RollingUpdater<T, L> getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit);
// There are no common interfaces through which we could get these values.
protected abstract int getCurrentReplicas(T current);
protected abstract int getDesiredReplicas(T item);
protected abstract long getObservedGeneration(T current);
@Override
public T scale(int count) {
return scale(count, false);
}
@Override
public T scale(int count, boolean wait) {
T res = withReplicas(count);
if (wait) {
return waitUntilScaled(count);
}
return res;
}
@Override
public Scale scale() {
return handleScale(null);
}
@Override
public Scale scale(Scale scaleParam) {
return handleScale(scaleParam);
}
/**
* Let's wait until there are enough Ready pods.
*/
private T waitUntilScaled(final int count) {
final AtomicReference<Integer> replicasRef = new AtomicReference<>(0);
final String name = checkName(getItem());
final String namespace = checkNamespace(getItem());
try {
return waitUntilCondition(t -> {
//If the resource is gone, we shouldn't wait.
if (t == null) {
if (count == 0) {
return true;
}
throw new IllegalStateException("Can't wait for " + getType().getSimpleName() + ": " + name + " in namespace: "
+ namespace + " to scale. Resource is no longer available.");
}
int currentReplicas = getCurrentReplicas(t);
int desiredReplicas = getDesiredReplicas(t);
replicasRef.set(currentReplicas);
long generation = t.getMetadata().getGeneration() != null ? t.getMetadata().getGeneration() : -1;
long observedGeneration = getObservedGeneration(t);
if (observedGeneration >= generation && Objects.equals(desiredReplicas, currentReplicas)) {
return true;
}
Log.debug("Only {}/{} replicas scheduled for {}: {} in namespace: {} seconds so waiting...",
currentReplicas, desiredReplicas, t.getKind(), t.getMetadata().getName(), namespace);
return false;
}, getConfig().getScaleTimeout(), TimeUnit.MILLISECONDS);
} catch (KubernetesClientTimeoutException e) {
throw new KubernetesClientException(
String.format("%s/%s pod(s) ready for %s: %s in namespace: %s after waiting for %s seconds so giving up",
replicasRef.get(), count, getType().getSimpleName(), name, namespace,
TimeUnit.MILLISECONDS.toSeconds(getConfig().getScaleTimeout())),
e);
}
}
@Override
public T edit(UnaryOperator<T> function) {
if (!rolling) {
return super.edit(function);
}
try {
T oldObj = getMandatory();
T newObj = function.apply(Serialization.clone(oldObj));
return getRollingUpdater(rollingTimeout, rollingTimeUnit).rollUpdate(oldObj, newObj);
} catch (Exception e) {
throw KubernetesClientException.launderThrowable(e);
}
}
@Override
public T replace(T t) {
if (!rolling) {
return super.replace(t);
}
return getRollingUpdater(rollingTimeout, rollingTimeUnit).rollUpdate(getMandatory(), t);
}
@Override
public T patch(PatchContext patchContext, T item) {
if (!rolling || patchContext == null || patchContext.getPatchType() != PatchType.JSON) {
return super.patch(patchContext, item);
}
return getRollingUpdater(rollingTimeout, rollingTimeUnit).rollUpdate(getMandatory(), item);
}
public abstract RollableScalableResourceOperation<T, L, R> newInstance(RollingOperationContext context);
@Override
public Loggable withLogWaitTimeout(Integer logWaitTimeout) {
return newInstance(rollingOperationContext.withLogWaitTimeout(logWaitTimeout));
}
@Override
public Loggable inContainer(String id) {
return newInstance(rollingOperationContext.withContainerId(id));
}
@Override
public TimeoutImageEditReplacePatchable<T> rolling() {
return newInstance(rollingOperationContext.withRolling(true));
}
@Override
public ImageEditReplacePatchable<T> withTimeoutInMillis(long timeoutInMillis) {
return newInstance(rollingOperationContext.withRollingTimeout(timeoutInMillis).withRollingTimeUnit(TimeUnit.MILLISECONDS));
}
@Override
public ImageEditReplacePatchable<T> withTimeout(long timeout, TimeUnit unit) {
return newInstance(rollingOperationContext.withRollingTimeout(timeout).withRollingTimeUnit(unit));
}
@Override
public String getLog() {
return getLog(rollingOperationContext.getPodOperationContext().isPrettyOutput());
}
@Override
public LogWatch watchLog() {
return watchLog(null);
}
@Override
public T updateImage(String image) {
T value = get();
if (value == null) {
throw new KubernetesClientException("Resource doesn't exist");
}
List<Container> containers = getContainers(value);
if (containers.size() > 1) {
throw new KubernetesClientException("Image update is not supported for multicontainer pods");
}
if (containers.isEmpty()) {
throw new KubernetesClientException("Pod has no containers!");
}
Container container = containers.iterator().next();
return updateImage(Collections.singletonMap(container.getName(), image));
}
protected abstract List<Container> getContainers(T value);
@Override
public T updateImage(Map<String, String> containerToImageMap) {
T value = get();
if (value == null) {
throw new KubernetesClientException("Resource doesn't exist");
}
T base = Serialization.clone(value);
List<Container> containers = getContainers(value);
if (containers.isEmpty()) {
throw new KubernetesClientException("Pod has no containers!");
}
for (Container container : containers) {
if (containerToImageMap.containsKey(container.getName())) {
container.setImage(containerToImageMap.get(container.getName()));
}
}
return sendPatchedObject(base, value);
}
protected T sendPatchedObject(T oldObject, T updatedObject) {
return this.patch(null, oldObject, updatedObject, false);
}
}