proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/extended/leaderelection/LeaderElectorBuilder.java
LeaderElectorBuilder
validate
class LeaderElectorBuilder { private final KubernetesClient client; private final Executor executor; private LeaderElectionConfig leaderElectionConfig; public LeaderElectorBuilder(KubernetesClient client, Executor executor) { this.client = client; this.executor = executor; } public LeaderElectorBuilder withConfig(LeaderElectionConfig leaderElectionConfig) { this.leaderElectionConfig = validate(leaderElectionConfig); return this; } public LeaderElector build() { return new LeaderElector(client, leaderElectionConfig, executor); } private static LeaderElectionConfig validate(LeaderElectionConfig leaderElectionConfig) {<FILL_FUNCTION_BODY>} }
Objects.requireNonNull(leaderElectionConfig, "LeaderElectionConfig is required"); Objects.requireNonNull(leaderElectionConfig.getName(), "name is required"); Objects.requireNonNull(leaderElectionConfig.getLeaseDuration(), "leaseDuration is required"); Objects.requireNonNull(leaderElectionConfig.getRenewDeadline(), "renewDeadLine is required"); Objects.requireNonNull(leaderElectionConfig.getRetryPeriod(), "retryPeriod is required"); Objects.requireNonNull(leaderElectionConfig.getLeaderCallbacks(), "leaderCallbacks are required"); Objects.requireNonNull(leaderElectionConfig.getLock(), "lock is required"); if (leaderElectionConfig.getLeaseDuration().compareTo(leaderElectionConfig.getRenewDeadline()) <= 0) { throw new IllegalArgumentException("leaseDuration must be greater than renewDeadLine"); } final Duration maxRetryPeriod = leaderElectionConfig.getRetryPeriod().plusMillis( (long) Math.ceil(leaderElectionConfig.getRetryPeriod().toMillis() * JITTER_FACTOR)); if (leaderElectionConfig.getRenewDeadline().compareTo(maxRetryPeriod) <= 0) { throw new IllegalArgumentException("renewDeadline must be greater than retryPeriod + retryPeriod*JITTER_FACTOR"); } if (leaderElectionConfig.getLeaseDuration().toMillis() < 1L) { throw new IllegalArgumentException("leaseDuration must be greater than zero"); } if (leaderElectionConfig.getRenewDeadline().toMillis() < 1L) { throw new IllegalArgumentException("renewDeadline must be greater than zero"); } if (leaderElectionConfig.getRetryPeriod().toMillis() < 1L) { throw new IllegalArgumentException("retryPeriod must be greater than zero"); } return leaderElectionConfig;
203
506
709
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/extended/leaderelection/resourcelock/ConfigMapLock.java
ConfigMapLock
toRecord
class ConfigMapLock extends ResourceLock<ConfigMap> { private static final Logger LOGGER = LoggerFactory.getLogger(ConfigMapLock.class); public ConfigMapLock(String configMapNamespace, String configMapName, String identity) { super(configMapNamespace, configMapName, identity); } public ConfigMapLock(ObjectMeta meta, String identity) { super(meta, identity); } @Override protected Class<ConfigMap> getKind() { return ConfigMap.class; } @Override protected LeaderElectionRecord toRecord(ConfigMap resource) {<FILL_FUNCTION_BODY>} @Override protected ConfigMap toResource(LeaderElectionRecord leaderElectionRecord, ObjectMetaBuilder meta) { return new ConfigMapBuilder() .withMetadata( meta.addToAnnotations(LEADER_ELECTION_RECORD_ANNOTATION_KEY, Serialization.asJson(leaderElectionRecord)).build()) .build(); } }
return Optional.ofNullable(resource.getMetadata().getAnnotations()) .map(annotations -> annotations.get(LEADER_ELECTION_RECORD_ANNOTATION_KEY)) .map(annotation -> { try { return Serialization.unmarshal(annotation, LeaderElectionRecord.class); } catch (KubernetesClientException ex) { LOGGER.error("Error deserializing LeaderElectionRecord from ConfigMap", ex); return null; } }) .orElse(null);
259
140
399
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String) ,public void <init>(ObjectMeta, java.lang.String) ,public synchronized void create(io.fabric8.kubernetes.client.KubernetesClient, io.fabric8.kubernetes.client.extended.leaderelection.resourcelock.LeaderElectionRecord) ,public java.lang.String describe() ,public synchronized io.fabric8.kubernetes.client.extended.leaderelection.resourcelock.LeaderElectionRecord get(io.fabric8.kubernetes.client.KubernetesClient) ,public java.lang.String identity() ,public synchronized void update(io.fabric8.kubernetes.client.KubernetesClient, io.fabric8.kubernetes.client.extended.leaderelection.resourcelock.LeaderElectionRecord) <variables>private final non-sealed java.lang.String identity,private final non-sealed ObjectMeta meta,private ConfigMap resource
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/extended/leaderelection/resourcelock/LeaderElectionRecord.java
LeaderElectionRecord
equals
class LeaderElectionRecord { private final String holderIdentity; private final Duration leaseDuration; @JsonFormat(timezone = "UTC", pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'") private final ZonedDateTime acquireTime; @JsonFormat(timezone = "UTC", pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'") private final ZonedDateTime renewTime; private final int leaderTransitions; @JsonCreator public LeaderElectionRecord( @JsonProperty("holderIdentity") String holderIdentity, @JsonProperty("leaseDuration") Duration leaseDuration, @JsonProperty("acquireTime") ZonedDateTime acquireTime, @JsonProperty("renewTime") ZonedDateTime renewTime, @JsonProperty("leaderTransitions") int leaderTransitions) { this.holderIdentity = holderIdentity; this.leaseDuration = Objects.requireNonNull(leaseDuration, "leaseDuration is required"); this.acquireTime = Objects.requireNonNull(acquireTime, "acquireTime is required"); this.renewTime = Objects.requireNonNull(renewTime, "renewTime is required"); this.leaderTransitions = leaderTransitions; } public String getHolderIdentity() { return holderIdentity; } public Duration getLeaseDuration() { return leaseDuration; } public ZonedDateTime getAcquireTime() { return acquireTime; } public ZonedDateTime getRenewTime() { return renewTime; } public int getLeaderTransitions() { return leaderTransitions; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(holderIdentity, leaseDuration, acquireTime, renewTime, leaderTransitions); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LeaderElectionRecord that = (LeaderElectionRecord) o; return leaderTransitions == that.leaderTransitions && Objects.equals(holderIdentity, that.holderIdentity) && Objects.equals(leaseDuration, that.leaseDuration) && Objects.equals(acquireTime, that.acquireTime) && Objects.equals(renewTime, that.renewTime);
498
138
636
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/extended/leaderelection/resourcelock/LeaseLock.java
LeaseLock
toRecord
class LeaseLock extends ResourceLock<Lease> { public LeaseLock(String leaseNamespace, String leaseName, String identity) { super(leaseNamespace, leaseName, identity); } public LeaseLock(ObjectMeta meta, String identity) { super(meta, identity); } @Override protected Class<Lease> getKind() { return Lease.class; } @Override protected Lease toResource(LeaderElectionRecord leaderElectionRecord, ObjectMetaBuilder meta) { return new LeaseBuilder().withMetadata(meta.build()) .withNewSpec() .withHolderIdentity(leaderElectionRecord.getHolderIdentity()) .withLeaseDurationSeconds((int) leaderElectionRecord.getLeaseDuration().get(ChronoUnit.SECONDS)) .withAcquireTime(leaderElectionRecord.getAcquireTime()) .withRenewTime(leaderElectionRecord.getRenewTime()) .withLeaseTransitions(leaderElectionRecord.getLeaderTransitions()) .endSpec() .build(); } @Override protected LeaderElectionRecord toRecord(Lease resource) {<FILL_FUNCTION_BODY>} }
return Optional.ofNullable(resource.getSpec()).map(spec -> new LeaderElectionRecord( spec.getHolderIdentity(), Duration.ofSeconds(spec.getLeaseDurationSeconds()), spec.getAcquireTime(), spec.getRenewTime(), Optional.ofNullable(spec.getLeaseTransitions()).orElse(0))).orElse(null);
315
101
416
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String) ,public void <init>(ObjectMeta, java.lang.String) ,public synchronized void create(io.fabric8.kubernetes.client.KubernetesClient, io.fabric8.kubernetes.client.extended.leaderelection.resourcelock.LeaderElectionRecord) ,public java.lang.String describe() ,public synchronized io.fabric8.kubernetes.client.extended.leaderelection.resourcelock.LeaderElectionRecord get(io.fabric8.kubernetes.client.KubernetesClient) ,public java.lang.String identity() ,public synchronized void update(io.fabric8.kubernetes.client.KubernetesClient, io.fabric8.kubernetes.client.extended.leaderelection.resourcelock.LeaderElectionRecord) <variables>private final non-sealed java.lang.String identity,private final non-sealed ObjectMeta meta,private Lease resource
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/extended/leaderelection/resourcelock/ResourceLock.java
ResourceLock
get
class ResourceLock<T extends HasMetadata> implements Lock { private final ObjectMeta meta; private final String identity; private T resource; public ResourceLock(String namespace, String name, String identity) { this(new ObjectMetaBuilder().withNamespace(namespace).withName(name).build(), identity); } public ResourceLock(ObjectMeta meta, String identity) { this.meta = meta; Objects.requireNonNull(meta.getNamespace(), "namespace is required"); Objects.requireNonNull(meta.getName(), "name is required"); this.identity = Objects.requireNonNull(identity, "identity is required"); } protected abstract Class<T> getKind(); @Override public synchronized LeaderElectionRecord get(KubernetesClient client) {<FILL_FUNCTION_BODY>} @Override public synchronized void create(KubernetesClient client, LeaderElectionRecord leaderElectionRecord) { resource = client.resource(toResource(leaderElectionRecord, getObjectMeta(null))).create(); } @Override public synchronized void update(KubernetesClient client, LeaderElectionRecord leaderElectionRecord) { Objects.requireNonNull(resource, "get or create must be called first"); client.resource(toResource(leaderElectionRecord, getObjectMeta(resource.getMetadata().getResourceVersion()))) .patch(PatchContext.of(PatchType.JSON_MERGE)); } /** * Convert the record to a resource * * @param leaderElectionRecord * @param meta not null * @return */ protected abstract T toResource(LeaderElectionRecord leaderElectionRecord, ObjectMetaBuilder meta); protected abstract LeaderElectionRecord toRecord(T resource); protected ObjectMetaBuilder getObjectMeta(String version) { return new ObjectMetaBuilder(meta).withResourceVersion(version); } /** * {@inheritDoc} */ @Override public String identity() { return identity; } /** * {@inheritDoc} */ @Override public String describe() { return String.format("%sLock: %s - %s (%s)", getKind().getSimpleName(), meta.getNamespace(), meta.getName(), identity); } void setResource(T resource) { this.resource = resource; } }
resource = client.resources(getKind()).inNamespace(meta.getNamespace()).withName(meta.getName()).get(); if (resource != null) { return toRecord(resource); } return null;
608
57
665
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/extended/run/RunConfigUtil.java
RunConfigUtil
argsFromConfig
class RunConfigUtil { private static final String DEFAULT_RESTART_POLICY = "Always"; private RunConfigUtil() { } public static ObjectMeta getObjectMetadataFromRunConfig(RunConfig generatorRunConfig) { ObjectMetaBuilder objectMetaBuilder = new ObjectMetaBuilder(); if (generatorRunConfig.getName() != null) { objectMetaBuilder.withName(generatorRunConfig.getName()); objectMetaBuilder.addToLabels("run", generatorRunConfig.getName()); } if (generatorRunConfig.getLabels() != null) { objectMetaBuilder.addToLabels(generatorRunConfig.getLabels()); } return objectMetaBuilder.build(); } public static PodSpec getPodSpecFromRunConfig(RunConfig generatorRunConfig) { PodSpecBuilder podSpecBuilder = new PodSpecBuilder(); if (generatorRunConfig.getRestartPolicy() != null) { podSpecBuilder.withRestartPolicy(generatorRunConfig.getRestartPolicy()); } else { podSpecBuilder.withRestartPolicy(DEFAULT_RESTART_POLICY); } if (generatorRunConfig.getServiceAccount() != null) { podSpecBuilder.withServiceAccountName(generatorRunConfig.getServiceAccount()); } podSpecBuilder.addToContainers(containerFromConfig(generatorRunConfig)); return podSpecBuilder.build(); } static Container containerFromConfig(RunConfig runConfig) { final ContainerBuilder containerBuilder = new ContainerBuilder(); containerBuilder.withName(runConfig.getName()); containerBuilder.withImage(runConfig.getImage()); containerBuilder.withImagePullPolicy(runConfig.getImagePullPolicy()); containerBuilder.withArgs(argsFromConfig(runConfig)); containerBuilder.withCommand(commandFromConfig(runConfig)); if (runConfig.getEnv() != null) { containerBuilder.withEnv(KubernetesResourceUtil.convertMapToEnvVarList(runConfig.getEnv())); } if (runConfig.getPort() > 0) { containerBuilder.withPorts(new ContainerPortBuilder() .withContainerPort(runConfig.getPort()) .build()); } if (runConfig.getLimits() != null) { containerBuilder.editOrNewResources() .addToLimits(runConfig.getLimits()) .endResources(); } if (runConfig.getRequests() != null) { containerBuilder.editOrNewResources() .addToRequests(runConfig.getRequests()) .endResources(); } return containerBuilder.build(); } private static String[] argsFromConfig(RunConfig runConfig) {<FILL_FUNCTION_BODY>} private static String[] commandFromConfig(RunConfig runConfig) { if (isNotNullOrEmpty(runConfig.getCommand())) { final List<String> command = new ArrayList<>(Collections.singletonList(runConfig.getCommand())); if (runConfig.getArgs() != null) { command.addAll(runConfig.getArgs()); } return command.toArray(new String[0]); } return new String[0]; } }
if (isNullOrEmpty(runConfig.getCommand()) && runConfig.getArgs() != null) { return runConfig.getArgs().toArray(new String[0]); } return new String[0];
818
58
876
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/extension/ExtensibleResourceAdapter.java
ExtensibleResourceAdapter
init
class ExtensibleResourceAdapter<T> extends ResourceAdapter<T> implements ExtensibleResource<T> { protected ExtensibleResource<T> resource; protected Client client; public ExtensibleResourceAdapter() { } public abstract ExtensibleResourceAdapter<T> newInstance(); public ExtensibleResourceAdapter<T> init(ExtensibleResource<T> resource, Client client) {<FILL_FUNCTION_BODY>} @Override public ExtensibleResource<T> lockResourceVersion(String resourceVersion) { return newInstance().init(resource.lockResourceVersion(resourceVersion), client); } @Override public ExtensibleResource<T> withResourceVersion(String resourceVersion) { return newInstance().init(resource.withResourceVersion(resourceVersion), client); } @Override public ExtensibleResource<T> fromServer() { return newInstance().init(resource.fromServer(), client); } @Override public ExtensibleResource<T> withGracePeriod(long gracePeriodSeconds) { return newInstance().init(resource.withGracePeriod(gracePeriodSeconds), client); } @Override public ExtensibleResource<T> withPropagationPolicy(DeletionPropagation propagationPolicy) { return newInstance().init(resource.withPropagationPolicy(propagationPolicy), client); } @Override public ExtensibleResource<T> withIndexers(Map<String, Function<T, List<String>>> indexers) { return newInstance().init(resource.withIndexers(indexers), client); } @Override public ExtensibleResource<T> dryRun(boolean isDryRun) { return newInstance().init(resource.dryRun(isDryRun), client); } @Override public ExtensibleResource<T> withLimit(Long limit) { return newInstance().init(resource.withLimit(limit), client); } @Override public <C extends Client> C inWriteContext(Class<C> clazz) { return resource.inWriteContext(clazz); } @Override public ExtensibleResource<T> lockResourceVersion() { return newInstance().init(resource.lockResourceVersion(), client); } @Override public T getItem() { return resource.getItem(); } @Override public ExtensibleResource<T> fieldValidation(Validation fieldValidation) { return newInstance().init(resource.fieldValidation(fieldValidation), client); } @Override public ExtensibleResource<T> fieldManager(String manager) { return newInstance().init(resource.fieldManager(manager), client); } @Override public ExtensibleResource<T> forceConflicts() { return newInstance().init(resource.forceConflicts(), client); } @Override public ExtensibleResource<T> withTimeout(long timeout, TimeUnit unit) { return newInstance().init(resource.withTimeout(timeout, unit), client); } @Override public ExtensibleResource<T> withTimeoutInMillis(long timeoutInMillis) { return withTimeout(timeoutInMillis, TimeUnit.MILLISECONDS); } @Override public ExtensibleResource<T> unlock() { return newInstance().init(resource.unlock(), client); } @Override public ExtensibleResource<T> subresource(String subresource) { return newInstance().init(resource.subresource(subresource), client); } }
super.resource = resource; this.resource = resource; this.client = client; return this;
912
32
944
<methods>public void <init>() ,public void <init>(Resource<T>) ,public T accept(Consumer<T>) ,public T create() ,public T create(T) ,public T createOr(Function<NonDeletingOperation<T>,T>) ,public T createOrReplace() ,public T createOrReplace(T) ,public List<StatusDetails> delete() ,public List<StatusDetails> delete(T) ,public WritableOperation<T> dryRun() ,public WritableOperation<T> dryRun(boolean) ,public T edit(UnaryOperator<T>) ,public transient T edit(Visitor[]) ,public T edit(Class<V>, Visitor<V>) ,public T editStatus(UnaryOperator<T>) ,public ServerSideApplicable<T> fieldManager(java.lang.String) ,public NonDeletingOperation<T> fieldValidation(io.fabric8.kubernetes.client.dsl.FieldValidateable.Validation) ,public ServerSideApplicable<T> forceConflicts() ,public Gettable<T> fromServer() ,public T get() ,public Resource<T> getResource() ,public SharedIndexInformer<T> inform() ,public SharedIndexInformer<T> inform(ResourceEventHandler<? super T>) ,public SharedIndexInformer<T> inform(ResourceEventHandler<? super T>, long) ,public CompletableFuture<List<T>> informOnCondition(Predicate<List<T>>) ,public boolean isReady() ,public T item() ,public ReplaceDeletable<T> lockResourceVersion(java.lang.String) ,public ReplaceDeletable<T> lockResourceVersion() ,public T patch(T) ,public T patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, T) ,public T patch(java.lang.String) ,public T patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, java.lang.String) ,public T patch() ,public T patch(io.fabric8.kubernetes.client.dsl.base.PatchContext) ,public T patchStatus(T) ,public T patchStatus() ,public T replace() ,public T replace(T) ,public T replaceStatus() ,public T replaceStatus(T) ,public T require() throws io.fabric8.kubernetes.client.ResourceNotFoundException,public SharedIndexInformer<T> runnableInformer(long) ,public Scale scale() ,public T scale(int) ,public T scale(int, boolean) ,public Scale scale(Scale) ,public T serverSideApply() ,public EditReplacePatchable<T> subresource(java.lang.String) ,public NonDeletingOperation<T> unlock() ,public T update() ,public T updateStatus(T) ,public T updateStatus() ,public T waitUntilCondition(Predicate<T>, long, java.util.concurrent.TimeUnit) ,public T waitUntilReady(long, java.util.concurrent.TimeUnit) ,public io.fabric8.kubernetes.client.Watch watch(Watcher<T>) ,public io.fabric8.kubernetes.client.Watch watch(ListOptions, Watcher<T>) ,public io.fabric8.kubernetes.client.Watch watch(java.lang.String, Watcher<T>) ,public PropagationPolicyConfigurable<? extends io.fabric8.kubernetes.client.dsl.Deletable> withGracePeriod(long) ,public Informable<T> withIndexers(Map<java.lang.String,Function<T,List<java.lang.String>>>) ,public Informable<T> withLimit(java.lang.Long) ,public GracePeriodConfigurable<? extends io.fabric8.kubernetes.client.dsl.Deletable> withPropagationPolicy(io.fabric8.kubernetes.api.model.DeletionPropagation) ,public Watchable<T> withResourceVersion(java.lang.String) ,public io.fabric8.kubernetes.client.dsl.Deletable withTimeout(long, java.util.concurrent.TimeUnit) ,public io.fabric8.kubernetes.client.dsl.Deletable withTimeoutInMillis(long) <variables>Resource<T> resource
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/http/AbstractBasicBuilder.java
AbstractBasicBuilder
header
class AbstractBasicBuilder<T extends BasicBuilder> implements BasicBuilder { private URI uri; private final Map<String, List<String>> headers = new HashMap<>(); @Override public T uri(URI uri) { this.uri = uri; return (T) this; } @Override public T header(String name, String value) {<FILL_FUNCTION_BODY>} @Override public T setHeader(String name, String value) { headers.put(name, new ArrayList<>(Collections.singletonList(value))); return (T) this; } protected final URI getUri() { return uri; } protected final Map<String, List<String>> getHeaders() { return headers; } protected final void setHeaders(Map<String, List<String>> headers) { this.headers.clear(); headers.forEach((header, values) -> values.forEach(value -> header(header, value))); } }
headers.compute(name, (k, v) -> { if (v == null) { v = new ArrayList<>(); } v.add(value); return v; }); return (T) this;
256
63
319
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/http/BufferUtil.java
BufferUtil
copy
class BufferUtil { private BufferUtil() { // utils class } /** * Convert a ByteBuffer to a byte array. * * @param buffer The buffer to convert in flush mode. The buffer is not altered. * @return An array of bytes duplicated from the buffer. */ public static byte[] toArray(ByteBuffer buffer) { if (buffer.hasArray()) { byte[] array = buffer.array(); int from = buffer.arrayOffset() + buffer.position(); return Arrays.copyOfRange(array, from, from + buffer.remaining()); } else { byte[] to = new byte[buffer.remaining()]; buffer.slice().get(to); return to; } } public static byte[] toArray(Collection<ByteBuffer> buffers) { final byte[] ret = new byte[buffers.stream().mapToInt(ByteBuffer::remaining).sum()]; int offset = 0; for (ByteBuffer buffer : buffers) { buffer.slice().get(ret, offset, buffer.remaining()); offset += buffer.remaining(); } return ret; } /** * Copy of a ByteBuffer into a heap buffer * * @param buffer The buffer to copy. * @return A copy of the provided buffer. */ public static ByteBuffer copy(ByteBuffer buffer) {<FILL_FUNCTION_BODY>} /** * Very rudimentary method to check if the provided ByteBuffer contains text. * * @return true if the buffer contains text, false otherwise. */ public static boolean isPlainText(ByteBuffer originalBuffer) { if (originalBuffer == null) { return false; } final ByteBuffer buffer = originalBuffer.asReadOnlyBuffer(); final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder(); try { decoder.decode(buffer); return true; } catch (CharacterCodingException ex) { return false; } } }
if (buffer == null) { return null; } final int position = buffer.position(); ByteBuffer clone = ByteBuffer.allocate(buffer.remaining()); clone.put(buffer); clone.flip(); buffer.position(position); return clone;
523
75
598
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/http/ByteArrayBodyHandler.java
ByteArrayBodyHandler
onBodyDone
class ByteArrayBodyHandler implements AsyncBody.Consumer<List<ByteBuffer>> { private final List<ByteBuffer> buffers = Collections.synchronizedList(new LinkedList<>()); private final CompletableFuture<byte[]> result = new CompletableFuture<>(); @Override public void consume(List<ByteBuffer> value, AsyncBody asyncBody) throws Exception { this.buffers.addAll(value); asyncBody.consume(); } protected void onResponse(HttpResponse<AsyncBody> response) { AsyncBody asyncBody = response.body(); asyncBody.done().whenComplete(this::onBodyDone); asyncBody.consume(); } private void onBodyDone(Void v, Throwable t) {<FILL_FUNCTION_BODY>} public CompletableFuture<byte[]> getResult() { return result; } }
if (t != null) { result.completeExceptionally(t); } else { byte[] bytes = null; synchronized (buffers) { bytes = toArray(buffers); } result.complete(bytes); } buffers.clear();
227
76
303
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/http/HttpClientReadableByteChannel.java
HttpClientReadableByteChannel
onResponse
class HttpClientReadableByteChannel implements ReadableByteChannel, AsyncBody.Consumer<List<ByteBuffer>> { private final LinkedList<ByteBuffer> buffers = new LinkedList<>(); private Throwable failed; private boolean closed; private boolean done; private CompletableFuture<AsyncBody> asyncBodyFuture = new CompletableFuture<>(); private ByteBuffer currentBuffer; private ReentrantLock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); @Override public void consume(List<ByteBuffer> value, AsyncBody asyncBody) throws Exception { doLockedAndSignal(() -> this.buffers.addAll(value)); } protected void onResponse(HttpResponse<AsyncBody> response) {<FILL_FUNCTION_BODY>} private void onBodyDone(Void v, Throwable t) { doLockedAndSignal(() -> { if (t != null) { failed = t; } done = true; return null; }); } <T> T doLockedAndSignal(Supplier<T> run) { lock.lock(); try { condition.signalAll(); return run.get(); } finally { lock.unlock(); } } @Override public void close() { if (doLockedAndSignal(() -> { if (this.closed) { return false; } this.closed = true; return true; })) { asyncBodyFuture.thenAccept(AsyncBody::cancel); } } @Override public synchronized boolean isOpen() { return !closed; } @Override public int read(ByteBuffer arg0) throws IOException { lock.lock(); try { if (closed) { throw new ClosedChannelException(); } int read = 0; while (arg0.hasRemaining()) { while (currentBuffer == null || !currentBuffer.hasRemaining()) { if (buffers.isEmpty()) { if (failed != null) { throw new IOException("channel already closed with exception", failed); } if (read > 0) { return read; } if (done) { return -1; } lock.unlock(); try { // relinquish the lock to consume more this.asyncBodyFuture.thenAccept(AsyncBody::consume); } finally { lock.lock(); } try { while (!done && buffers.isEmpty()) { condition.await(); // block until more buffers are delivered } } catch (InterruptedException e) { close(); Thread.currentThread().interrupt(); throw new ClosedByInterruptException(); } } currentBuffer = buffers.poll(); } int remaining = Math.min(arg0.remaining(), currentBuffer.remaining()); for (int i = 0; i < remaining; i++) { arg0.put(currentBuffer.get()); } read += remaining; } return read; } finally { if (lock.isHeldByCurrentThread()) { lock.unlock(); } } } }
AsyncBody asyncBody = response.body(); asyncBodyFuture.complete(asyncBody); asyncBody.done().whenComplete(this::onBodyDone); asyncBody.consume(); // pre-fetch the first results doLockedAndSignal(() -> null);
839
70
909
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/http/HttpLoggingInterceptor.java
DeferredLoggingConsumer
processAsyncBody
class DeferredLoggingConsumer implements AsyncBody.Consumer<List<ByteBuffer>> { private static final long MAX_BODY_SIZE = 2097152L; // 2MiB private final HttpLogger httpLogger; private final HttpRequest originalRequest; private final AsyncBody.Consumer<List<ByteBuffer>> originalConsumer; private final AtomicLong responseBodySize; private final Queue<ByteBuffer> responseBody; private final AtomicBoolean bodyTruncated = new AtomicBoolean(); public DeferredLoggingConsumer(HttpLogger httpLogger, HttpRequest originalRequest, AsyncBody.Consumer<List<ByteBuffer>> originalConsumer) { this.httpLogger = httpLogger; this.originalRequest = originalRequest; this.originalConsumer = originalConsumer; responseBodySize = new AtomicLong(0); responseBody = new ConcurrentLinkedQueue<>(); } @Override public void consume(List<ByteBuffer> value, AsyncBody asyncBody) throws Exception { try { value.stream().forEach(bb -> { if (responseBodySize.addAndGet(bb.remaining()) < MAX_BODY_SIZE && !bodyTruncated.get() && BufferUtil.isPlainText(bb)) { responseBody.add(copy(bb)); } else { bodyTruncated.set(true); } }); } finally { originalConsumer.consume(value, asyncBody); } } @Override public <U> U unwrap(Class<U> target) { return Optional.ofNullable(AsyncBody.Consumer.super.unwrap(target)).orElse(originalConsumer.unwrap(target)); } /** * Registers the asyncBody.done() callback. * * @param asyncBody the AsyncBody instance to register the callback on the done() future. * @param response */ private void processAsyncBody(AsyncBody asyncBody, HttpResponse<?> response) {<FILL_FUNCTION_BODY>} }
asyncBody.done().whenComplete((Void v, Throwable throwable) -> { httpLogger.logStart(); // TODO: we also have access to the response.request, which may be different than originalRequest httpLogger.logRequest(originalRequest); httpLogger.logResponse(response); httpLogger.logResponseBody(responseBody, responseBodySize.get(), bodyTruncated.get()); httpLogger.logEnd(); responseBody.clear(); });
518
120
638
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/http/SendAsyncUtils.java
SendAsyncUtils
inputStream
class SendAsyncUtils { private SendAsyncUtils() { // just utils } static CompletableFuture<HttpResponse<Reader>> reader(HttpRequest request, HttpClient client) { return inputStream(request, client) .thenApply(res -> new HttpResponseAdapter<>(res, new InputStreamReader(res.body(), StandardCharsets.UTF_8))); } static CompletableFuture<HttpResponse<InputStream>> inputStream(HttpRequest request, HttpClient client) {<FILL_FUNCTION_BODY>} static CompletableFuture<HttpResponse<byte[]>> bytes(HttpRequest request, HttpClient client) { ByteArrayBodyHandler byteArrayBodyHandler = new ByteArrayBodyHandler(); CompletableFuture<HttpResponse<AsyncBody>> futureResponse = client.consumeBytes(request, byteArrayBodyHandler); return futureResponse.thenCompose(res -> { byteArrayBodyHandler.onResponse(res); return byteArrayBodyHandler.getResult() .thenApply(b -> new HttpResponseAdapter<>(res, b)); }); } static CompletableFuture<HttpResponse<String>> string(HttpRequest request, HttpClient client) { return bytes(request, client) .thenApply(res -> new HttpResponseAdapter<>(res, new String(res.body(), StandardCharsets.UTF_8))); } }
HttpClientReadableByteChannel byteChannel = new HttpClientReadableByteChannel(); CompletableFuture<HttpResponse<AsyncBody>> futureResponse = client.consumeBytes(request, byteChannel); return futureResponse.thenApply(res -> { byteChannel.onResponse(res); return new HttpResponseAdapter<>(res, Channels.newInputStream(byteChannel)); });
335
94
429
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/http/StandardHttpClientBuilder.java
StandardHttpClientBuilder
sslContext
class StandardHttpClientBuilder<C extends HttpClient, F extends HttpClient.Factory, T extends StandardHttpClientBuilder<C, F, ?>> implements HttpClient.Builder { protected LinkedHashMap<String, Interceptor> interceptors = new LinkedHashMap<>(); protected Duration connectTimeout; protected SSLContext sslContext; protected String proxyAuthorization; protected InetSocketAddress proxyAddress; protected boolean followRedirects; protected boolean preferHttp11; protected TlsVersion[] tlsVersions; protected boolean authenticatorNone; protected C client; protected F clientFactory; protected TrustManager[] trustManagers; protected KeyManager[] keyManagers; protected LinkedHashMap<Class<?>, Object> tags = new LinkedHashMap<>(); protected ProxyType proxyType = ProxyType.HTTP; // for backwards compatibility if the builder is manually configured protected StandardHttpClientBuilder(F clientFactory) { this.clientFactory = clientFactory; // TODO: Find better place or solution if (LoggerFactory.getLogger(HttpLoggingInterceptor.class).isTraceEnabled()) { interceptors.put("HttpLogging", new HttpLoggingInterceptor()); } } @Override public T connectTimeout(long connectTimeout, TimeUnit unit) { this.connectTimeout = Duration.ofNanos(unit.toNanos(connectTimeout)); return (T) this; } @Override public T addOrReplaceInterceptor(String name, Interceptor interceptor) { if (interceptor == null) { interceptors.remove(name); } else { interceptors.put(name, interceptor); } return (T) this; } @Override public T authenticatorNone() { this.authenticatorNone = true; return (T) this; } @Override public T sslContext(KeyManager[] keyManagers, TrustManager[] trustManagers) {<FILL_FUNCTION_BODY>} @Override public T followAllRedirects() { this.followRedirects = true; return (T) this; } @Override public T proxyAddress(InetSocketAddress proxyAddress) { this.proxyAddress = proxyAddress; return (T) this; } @Override public T proxyAuthorization(String credentials) { this.proxyAuthorization = credentials; return (T) this; } @Override public T proxyType(ProxyType type) { this.proxyType = type; return (T) this; } @Override public T tlsVersions(TlsVersion... tlsVersions) { this.tlsVersions = tlsVersions; return (T) this; } @Override public T preferHttp11() { this.preferHttp11 = true; return (T) this; } public T clientFactory(F clientFactory) { this.clientFactory = clientFactory; return (T) this; } @Override public DerivedClientBuilder tag(Object value) { if (value != null) { this.tags.put(value.getClass(), value); } return this; } protected abstract T newInstance(F clientFactory); public T copy(C client) { T copy = newInstance(clientFactory); copy.connectTimeout = this.connectTimeout; copy.sslContext = this.sslContext; copy.trustManagers = this.trustManagers; copy.keyManagers = this.keyManagers; copy.interceptors = new LinkedHashMap<>(this.interceptors); copy.proxyAddress = this.proxyAddress; copy.proxyAuthorization = this.proxyAuthorization; copy.tlsVersions = this.tlsVersions; copy.preferHttp11 = this.preferHttp11; copy.followRedirects = this.followRedirects; copy.authenticatorNone = this.authenticatorNone; copy.client = client; copy.tags = new LinkedHashMap<>(this.tags); copy.proxyType = this.proxyType; return copy; } protected void addProxyAuthInterceptor() { if (proxyAuthorization != null) { this.interceptors.put("PROXY-AUTH", new Interceptor() { @Override public void before(BasicBuilder builder, HttpRequest httpRequest, RequestTags tags) { builder.setHeader(StandardHttpHeaders.PROXY_AUTHORIZATION, proxyAuthorization); } }); } } }
this.sslContext = SSLUtils.sslContext(keyManagers, trustManagers); this.keyManagers = keyManagers; this.trustManagers = trustManagers; return (T) this;
1,199
56
1,255
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/http/StandardHttpRequest.java
Builder
build
class Builder extends AbstractBasicBuilder<Builder> implements HttpRequest.Builder { private String method = "GET"; private BodyContent body; private String bodyAsString; private boolean expectContinue; private String contentType; protected Duration timeout; protected boolean forStreaming; public Builder() { } public Builder(StandardHttpRequest original) { super.uri(original.uri()); super.setHeaders(original.headers()); method = original.method; bodyAsString = original.bodyString; body = original.body; expectContinue = original.expectContinue; contentType = original.contentType; timeout = original.timeout; forStreaming = original.forStreaming; } @Override public StandardHttpRequest build() {<FILL_FUNCTION_BODY>} @Override public HttpRequest.Builder timeout(long timeout, TimeUnit unit) { this.timeout = Duration.ofNanos(unit.toNanos(timeout)); return this; } @Override public HttpRequest.Builder forStreaming() { this.forStreaming = true; return this; } @Override public HttpRequest.Builder uri(String uri) { return super.uri(URI.create(uri)); } @Override public HttpRequest.Builder url(URL url) { try { return super.uri(url.toURI()); } catch (URISyntaxException e) { throw KubernetesClientException.launderThrowable(e); } } @Override public HttpRequest.Builder post(String contentType, byte[] writeValueAsBytes) { method = METHOD_POST; this.contentType = contentType; body = new ByteArrayBodyContent(writeValueAsBytes); return this; } @Override public HttpRequest.Builder method(String method, String contentType, String body) { this.method = method; this.contentType = contentType; this.bodyAsString = body; if (body != null) { this.body = new StringBodyContent(body); } return this; } @Override public HttpRequest.Builder method(String method, String contentType, InputStream stream, long length) { this.method = method; this.contentType = contentType; this.body = new InputStreamBodyContent(stream, length); return this; } @Override public HttpRequest.Builder expectContinue() { expectContinue = true; return this; } }
return new StandardHttpRequest(getHeaders(), Objects.requireNonNull(getUri()), method, bodyAsString, body, expectContinue, contentType, timeout, forStreaming);
664
47
711
<methods>public void <init>() ,public void <init>(Map<java.lang.String,List<java.lang.String>>) ,public List<java.lang.String> headers(java.lang.String) ,public Map<java.lang.String,List<java.lang.String>> headers() <variables>public static final java.lang.String CONTENT_LENGTH,public static final java.lang.String CONTENT_TYPE,public static final java.lang.String EXPECT,public static final java.lang.String EXPECT_CONTINUE,public static final java.lang.String PROXY_AUTHORIZATION,public static final java.lang.String RETRY_AFTER,private final non-sealed Map<java.lang.String,List<java.lang.String>> headers
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/informers/cache/Lister.java
Lister
get
class Lister<T> { private final String namespace; private final String indexName; private final Indexer<T> indexer; public Lister(Indexer<T> indexer) { this(indexer, null, Cache.NAMESPACE_INDEX); } public Lister(Indexer<T> indexer, String namespace) { this(indexer, namespace, Cache.NAMESPACE_INDEX); } public Lister(Indexer<T> indexer, String namespace, String indexName) { this.indexer = indexer; this.namespace = namespace; this.indexName = indexName; } public List<T> list() { if ((namespace == null || namespace.isEmpty())) { return indexer.list(); } else { return indexer.byIndex(this.indexName, namespace); } } public T get(String name) {<FILL_FUNCTION_BODY>} public Lister<T> namespace(String namespace) { return new Lister<>(this.indexer, namespace, Cache.NAMESPACE_INDEX); } }
String key = name; if (namespace != null && !namespace.isEmpty()) { key = namespace + "/" + name; } return indexer.getByKey(key);
294
51
345
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/informers/cache/ReducedStateItemStore.java
KeyState
restore
class KeyState { final Function<HasMetadata, String> keyFunction; final Function<String, String[]> keyFieldFunction; final List<String[]> keyFields; /** * The key function must decompose a given key into the given fields - in field order * * @param keyFieldFunction to convert a key into fields * @param keyFields the fields represented by the key */ public KeyState(Function<HasMetadata, String> keyFunction, Function<String, String[]> keyFieldFunction, String[]... keyFields) { this.keyFunction = keyFunction; this.keyFieldFunction = keyFieldFunction; this.keyFields = Arrays.asList(keyFields); } } public static final KeyState NAME_KEY_STATE = new KeyState(Cache::metaNamespaceKeyFunc, k -> { int index = k.indexOf("/"); if (index == -1) { return new String[] { null, k }; } return new String[] { k.substring(0, index), k.substring(index + 1) }; }, new String[] { METADATA, "namespace" }, new String[] { METADATA, "name" }); public static final KeyState UID_KEY_STATE = new KeyState(Cache::metaUidKeyFunc, k -> new String[] { k }, new String[] { METADATA, "uid" }); /** * Create a state store with only the fields specified. * <p> * metadata.resourceVersion - will automatically be saved as will * the necessary key fields. * <p> * If you are using custom indexers, then the fields used by those * indexes must be added to the valueFields - otherwise the indexer won't be able to delete the * index entries when the item is removed. * <p> * For example in level event handling systems all you may need beyond the * key is the ownerReferences. You would use withValueFields("metadata.ownerReferences") * for that. * <p> * NOTE: If you use this feature, you should only use the informer cache/store for basic * existence checks and maintain your own cache of full resource objects. * <p> * Only simple names are allowed in field paths - '.' is reserved as the separator. * <p> * Whatever is provided as the {@link KeyState} should match the keyFunction provided to the informer. * * @param keyState information about the key fields/function * @param typeClass the expected type * @param valueFields the additional fields to save */ public ReducedStateItemStore(KeyState keyState, Class<V> typeClass, KubernetesSerialization serialization, String... valueFields) { this.keyState = keyState; fields.add(new String[] { METADATA, "resourceVersion" }); if (valueFields != null) { for (int i = 0; i < valueFields.length; i++) { fields.add(valueFields[i].split("\\.")); } } this.typeClass = typeClass; this.serialization = serialization; } Object[] store(V value) { if (value == null) { return null; } Map<String, Object> raw = serialization.convertValue(value, Map.class); return fields.stream().map(f -> GenericKubernetesResource.get(raw, (Object[]) f)).toArray(); } V restore(String key, Object[] values) {<FILL_FUNCTION_BODY>
if (values == null) { return null; } Map<String, Object> raw = new HashMap<>(); applyFields(values, raw, this.fields); String[] keyParts = this.keyState.keyFieldFunction.apply(key); applyFields(keyParts, raw, this.keyState.keyFields); return serialization.convertValue(raw, typeClass);
904
103
1,007
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/internal/KubeConfigUtils.java
KubeConfigUtils
getNamedUserIndexFromConfig
class KubeConfigUtils { private KubeConfigUtils() { } public static Config parseConfig(File file) throws IOException { return Serialization.unmarshal(new FileInputStream(file), Config.class); } public static Config parseConfigFromString(String contents) { return Serialization.unmarshal(contents, Config.class); } /** * Returns the current context in the given config * * @param config Config object * @return returns context in config if found, otherwise null */ public static NamedContext getCurrentContext(Config config) { String contextName = config.getCurrentContext(); if (contextName != null) { List<NamedContext> contexts = config.getContexts(); if (contexts != null) { for (NamedContext context : contexts) { if (contextName.equals(context.getName())) { return context; } } } } return null; } /** * Returns the current user token for the config and current context * * @param config Config object * @param context Context object * @return returns current user based upon provided parameters. */ public static String getUserToken(Config config, Context context) { AuthInfo authInfo = getUserAuthInfo(config, context); if (authInfo != null) { return authInfo.getToken(); } return null; } /** * Returns the current {@link AuthInfo} for the current context and user * * @param config Config object * @param context Context object * @return {@link AuthInfo} for current context */ public static AuthInfo getUserAuthInfo(Config config, Context context) { AuthInfo authInfo = null; if (config != null && context != null) { String user = context.getUser(); if (user != null) { List<NamedAuthInfo> users = config.getUsers(); if (users != null) { authInfo = users.stream() .filter(u -> u.getName().equals(user)) .findAny() .map(NamedAuthInfo::getUser) .orElse(null); } } } return authInfo; } /** * Returns the current {@link Cluster} for the current context * * @param config {@link Config} config object * @param context {@link Context} context object * @return current {@link Cluster} for current context */ public static Cluster getCluster(Config config, Context context) { Cluster cluster = null; if (config != null && context != null) { String clusterName = context.getCluster(); if (clusterName != null) { List<NamedCluster> clusters = config.getClusters(); if (clusters != null) { cluster = clusters.stream() .filter(c -> c.getName().equals(clusterName)) .findAny() .map(NamedCluster::getCluster) .orElse(null); } } } return cluster; } /** * Get User index from Config object * * @param config {@link io.fabric8.kubernetes.api.model.Config} Kube Config * @param userName username inside Config * @return index of user in users array */ public static int getNamedUserIndexFromConfig(Config config, String userName) {<FILL_FUNCTION_BODY>} /** * Modify KUBECONFIG file * * @param kubeConfig modified {@link io.fabric8.kubernetes.api.model.Config} object * @param kubeConfigPath path to KUBECONFIG * @throws IOException in case of failure while writing to file */ public static void persistKubeConfigIntoFile(Config kubeConfig, String kubeConfigPath) throws IOException { try (FileWriter writer = new FileWriter(kubeConfigPath)) { writer.write(Serialization.asYaml(kubeConfig)); } } }
for (int i = 0; i < config.getUsers().size(); i++) { if (config.getUsers().get(i).getName().equals(userName)) { return i; } } return -1;
1,043
63
1,106
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/internal/PKCS1Util.java
Asn1Object
validateSequence
class Asn1Object { private final int type; private final byte[] value; private final int tag; public Asn1Object(int tag, byte[] value) { this.tag = tag; this.type = tag & 0x1F; this.value = value; } public byte[] getValue() { return value; } BigInteger getInteger() throws IOException { if (type != 0x02) { throw new IOException("Invalid DER: object is not integer"); //$NON-NLS-1$ } return new BigInteger(value); } void validateSequence() throws IOException {<FILL_FUNCTION_BODY>} }
if (type != 0x10) { throw new IOException("Invalid DER: not a sequence"); } if ((tag & 0x20) != 0x20) { throw new IOException("Invalid DER: can't parse primitive entity"); }
187
73
260
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/internal/SSLUtils.java
SSLUtils
keyManagers
class SSLUtils { private static final Logger LOG = LoggerFactory.getLogger(SSLUtils.class); private SSLUtils() { //Utility } public static boolean isHttpsAvailable(Config config) { HttpsURLConnection conn = null; try { URL url = new URL(Config.HTTPS_PROTOCOL_PREFIX + config.getMasterUrl()); conn = (HttpsURLConnection) url.openConnection(); SSLContext sslContext = SSLUtils.sslContext(config); conn.setSSLSocketFactory(sslContext.getSocketFactory()); conn.setConnectTimeout(1000); conn.setReadTimeout(1000); conn.connect(); return true; } catch (Throwable t) { LOG.warn("SSL handshake failed. Falling back to insecure connection."); } finally { if (conn != null) { conn.disconnect(); } } return false; } public static SSLContext sslContext(Config config) throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, InvalidKeySpecException, KeyManagementException { return sslContext(keyManagers(config), trustManagers(config)); } public static SSLContext sslContext(KeyManager[] keyManagers, TrustManager[] trustManagers) { SSLContext sslContext = null; NoSuchAlgorithmException noSuch = null; // v1.3 is not supported on all vms, and of course there may be later versions added. // so try to find one starting with the latest for (TlsVersion version : TlsVersion.values()) { try { sslContext = SSLContext.getInstance(version.javaName()); break; } catch (NoSuchAlgorithmException e) { if (noSuch == null) { noSuch = e; } continue; } } if (sslContext == null) { throw KubernetesClientException.launderThrowable(noSuch); } try { sslContext.init(keyManagers, trustManagers, new SecureRandom()); return sslContext; } catch (KeyManagementException e) { throw KubernetesClientException.launderThrowable(e); } } public static TrustManager[] trustManagers(Config config) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { return trustManagers(config.getCaCertData(), config.getCaCertFile(), config.isTrustCerts(), config.getTrustStoreFile(), config.getTrustStorePassphrase()); } public static TrustManager[] trustManagers(String certData, String certFile, boolean isTrustCerts, String trustStoreFile, String trustStorePassphrase) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore trustStore = null; if (isTrustCerts) { return new TrustManager[] { new X509ExtendedTrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String s) { //not needed } @Override public void checkServerTrusted(X509Certificate[] chain, String s) { //not needed } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { //not needed } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { //not needed } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { //not needed } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { //not needed } } }; } else if (Utils.isNotNullOrEmpty(certData) || Utils.isNotNullOrEmpty(certFile)) { trustStore = createTrustStore(certData, certFile, trustStoreFile, trustStorePassphrase); } tmf.init(trustStore); return tmf.getTrustManagers(); } public static KeyManager[] keyManagers(Config config) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, CertificateException, InvalidKeySpecException, IOException { return keyManagers(config.getClientCertData(), config.getClientCertFile(), config.getClientKeyData(), config.getClientKeyFile(), config.getClientKeyAlgo(), config.getClientKeyPassphrase(), config.getKeyStoreFile(), config.getKeyStorePassphrase()); } public static KeyManager[] keyManagers(String certData, String certFile, String keyData, String keyFile, String algo, String passphrase, String keyStoreFile, String keyStorePassphrase) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, CertificateException, InvalidKeySpecException, IOException {<FILL_FUNCTION_BODY>} public static KeyManager[] keyManagers(InputStream certInputStream, InputStream keyInputStream, String algo, String passphrase, String keyStoreFile, String keyStorePassphrase) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, CertificateException, InvalidKeySpecException, IOException { KeyStore keyStore = createKeyStore(certInputStream, keyInputStream, algo, passphrase.toCharArray(), keyStoreFile, keyStorePassphrase.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, passphrase.toCharArray()); return kmf.getKeyManagers(); } }
KeyManager[] keyManagers = null; if ((Utils.isNotNullOrEmpty(certData) || Utils.isNotNullOrEmpty(certFile)) && (Utils.isNotNullOrEmpty(keyData) || Utils.isNotNullOrEmpty(keyFile))) { KeyStore keyStore = createKeyStore(certData, certFile, keyData, keyFile, algo, passphrase, keyStoreFile, keyStorePassphrase); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, passphrase.toCharArray()); keyManagers = kmf.getKeyManagers(); } return keyManagers;
1,564
170
1,734
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/readiness/Readiness.java
ReadinessHolder
isReadinessApplicable
class ReadinessHolder { public static final Readiness INSTANCE = new Readiness(); } public static Readiness getInstance() { return ReadinessHolder.INSTANCE; } /** * Checks if the provided {@link HasMetadata} is marked as ready by the cluster. * * <p> * A "Readiable" resources is a subjective trait for Kubernetes Resources. Many Resources, such as ConfigMaps, * Secrets, etc. become ready as soon as they've been created in the cluster. * * <p> * However, other resources such as Pods, Endpoints, Deployments, and controllers in general, only become * ready when their desired state matches their actual state. * * <p> * This method returns true for those "Readiable" resources once they are considered ready (even if the resource * exists in the cluster). For "non-Readiable" resources, this method returns true once the resources are created in * the cluster (in addition it logs a warning stating that the given resource is not considered "Readiable"). * * @param item resource to be checked for Readiness. * @return true if it's a Readiable Resource and is ready, or it's a non-readiable resource and has been created. false * otherwise. */ public boolean isReady(HasMetadata item) { if (isReadinessApplicable(item)) { return isResourceReady(item); } else { return handleNonReadinessApplicableResource(item); } } protected boolean isReadinessApplicable(HasMetadata item) {<FILL_FUNCTION_BODY>
return (item instanceof Deployment || item instanceof io.fabric8.kubernetes.api.model.extensions.Deployment || item instanceof ReplicaSet || item instanceof Pod || item instanceof ReplicationController || item instanceof Endpoints || item instanceof Node || item instanceof StatefulSet);
415
78
493
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/ApiVersionUtil.java
ApiVersionUtil
apiGroup
class ApiVersionUtil { private ApiVersionUtil() { throw new IllegalStateException("Utility class"); } /** * Extracts apiGroupName from apiGroupVersion when in resource for apiGroupName/apiGroupVersion combination * * @param <T> Template argument provided * @param item resource which is being used * @param apiGroup apiGroupName present if any * @return Just the apiGroupName part without apiGroupVersion */ public static <T> String apiGroup(T item, String apiGroup) {<FILL_FUNCTION_BODY>} /** * Returns the api version falling back to the items apiGroupVersion if not null. * * @param <T> type of parameter * @param item item to be processed * @param apiVersion apiVersion string * @return returns api version */ public static <T> String apiVersion(T item, String apiVersion) { if (item instanceof HasMetadata && Utils.isNotNullOrEmpty(((HasMetadata) item).getApiVersion())) { return trimVersion(((HasMetadata) item).getApiVersion()); } else if (apiVersion != null && !apiVersion.isEmpty()) { return trimVersion(apiVersion); } return null; } /** * Separates apiGroupVersion for apiGroupName/apiGroupVersion combination. * * @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo. * @return Just the apiGroupVersion part without the apiGroupName. */ public static String trimVersion(String apiVersion) { if (apiVersion != null) { final int slash = apiVersion.indexOf('/'); if (slash > 0) { return apiVersion.substring(slash + 1); } } return apiVersion; } /** * Separates apiGroupName for apiGroupName/apiGroupVersion combination. * * @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo. * @return Just the apiGroupName part without the apiGroupName, or apiVersion if no separator is found. */ public static String trimGroup(String apiVersion) { if (apiVersion != null) { final int slash = apiVersion.indexOf('/'); if (slash > 0) { return apiVersion.substring(0, slash); } } return apiVersion; } /** * Separates apiGroupName for apiGroupName/apiGroupVersion combination. * * @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo. * @return Just the apiGroupName part without the apiGroupName, or null if no separator is found. */ public static String trimGroupOrNull(String apiVersion) { if (apiVersion != null && apiVersion.contains("/")) { return trimGroup(apiVersion); } return null; } /** * Join group and version strings to form apiVersion key in Kubernetes objects * * @param group ApiGroup for resource * @param version ApiVersion for resource * @return version if group is null or empty, joined string otherwise. */ public static String joinApiGroupAndVersion(String group, String version) { if (Utils.isNullOrEmpty(group)) { return version; } return group + "/" + version; } }
if (item instanceof HasMetadata && Utils.isNotNullOrEmpty(((HasMetadata) item).getApiVersion())) { return trimGroupOrNull(((HasMetadata) item).getApiVersion()); } else if (apiGroup != null && !apiGroup.isEmpty()) { return trimGroup(apiGroup); } return null;
850
85
935
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/AsyncUtils.java
AsyncUtils
retryWithExponentialBackoff
class AsyncUtils { private AsyncUtils() { } /** * Returns the provided {@link CompletableFuture} that will complete exceptionally with a {@link TimeoutException} * if the provided {@link Duration} timeout period is exceeded. * * @param future the future to add a timeout to. * @param timeout the timeout duration. * @return the provided future with a timeout. * @param <T> the result type returned by the future. */ public static <T> CompletableFuture<T> withTimeout(CompletableFuture<T> future, Duration timeout) { if (timeout != null && timeout.toMillis() > 0) { final Future<?> scheduled = Utils.schedule(Runnable::run, () -> future.completeExceptionally(new TimeoutException()), timeout.toMillis(), TimeUnit.MILLISECONDS); future.whenComplete((v, t) -> scheduled.cancel(true)); } return future; } /** * Returns a new {@link CompletableFuture} that will complete once the action provided by the action supplier completes. * The action will be retried with an exponential backoff using the {@link ExponentialBackoffIntervalCalculator} as * long as the {@link ShouldRetry} predicate returns true. * Each action retrieval retry will time out after the provided timeout {@link Duration}. * * @param action the action supplier. * @param onCancel consumes the intermediate result in case the returned future is cancelled or each time the action is * retried. * @param timeout the timeout duration. * @param retryIntervalCalculator the retry interval calculator. * @param shouldRetry the predicate to compute if the action is to be retried. * @return a new {@link CompletableFuture} that will complete once the action provided by the action supplier completes. * @param <T> the result type returned by the future. */ public static <T> CompletableFuture<T> retryWithExponentialBackoff(Supplier<CompletableFuture<T>> action, Consumer<T> onCancel, Duration timeout, ExponentialBackoffIntervalCalculator retryIntervalCalculator, ShouldRetry<T> shouldRetry) { final CompletableFuture<T> result = new CompletableFuture<>(); retryWithExponentialBackoff(result, action, onCancel, timeout, retryIntervalCalculator, shouldRetry); return result; } private static <T> void retryWithExponentialBackoff(CompletableFuture<T> result, Supplier<CompletableFuture<T>> action, Consumer<T> onCancel, Duration timeout, ExponentialBackoffIntervalCalculator retryIntervalCalculator, ShouldRetry<T> shouldRetry) {<FILL_FUNCTION_BODY>} @FunctionalInterface public interface ShouldRetry<T> { boolean shouldRetry(T result, Throwable exception, long retryInterval); } }
withTimeout(action.get(), timeout).whenComplete((r, t) -> { if (retryIntervalCalculator.shouldRetry() && !result.isDone()) { final long retryInterval = retryIntervalCalculator.nextReconnectInterval(); if (shouldRetry.shouldRetry(r, t, retryInterval)) { if (r != null) { onCancel.accept(r); } Utils.schedule(Runnable::run, () -> retryWithExponentialBackoff(result, action, onCancel, timeout, retryIntervalCalculator, shouldRetry), retryInterval, TimeUnit.MILLISECONDS); return; } } if (t != null) { result.completeExceptionally(t); } else if (!result.complete(r)) { onCancel.accept(r); } });
742
227
969
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/BackwardsCompatibilityInterceptor.java
ResourceKey
afterFailure
class ResourceKey { private final String kind; private final String path; private final String group; private final String version; public ResourceKey(String kind, String path, String group, String version) { this.kind = kind; this.path = path; this.group = group; this.version = version; } public String getKind() { return kind; } public String getPath() { return path; } public String getGroup() { return group; } public String getVersion() { return version; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceKey key = (ResourceKey) o; return Objects.equals(path, key.path) && Objects.equals(group, key.group) && Objects.equals(version, key.version); } @Override public int hashCode() { return Objects.hash(path, group, version); } } static { notFoundTransformations.put(new ResourceKey("Deployment", "deployments", "apps", "v1"), new ResourceKey("Deployment", "deployments", "extensions", "v1beta1")); notFoundTransformations.put(new ResourceKey("StatefulSet", "statefulsets", "apps", "v1"), new ResourceKey("StatefulSet", "statefulsets", "apps", "v1beta1")); notFoundTransformations.put(new ResourceKey("DaemonSets", "daemonsets", "apps", "v1"), new ResourceKey("DaemonSet", "daemonsets", "extensions", "v1beta1")); notFoundTransformations.put(new ResourceKey("ReplicaSets", "replicasets", "apps", "v1"), new ResourceKey("ReplicaSet", "replicasets", "extensions", "v1beta1")); notFoundTransformations .put(new ResourceKey("NetworkPolicy", "networkpolicies", "networking.k8s.io", "v1"), new ResourceKey("NetworkPolicy", "networkpolicies", "extensions", "v1beta1")); notFoundTransformations .put(new ResourceKey("StorageClass", "storageclasses", "storage.k8s.io", "v1"), new ResourceKey("StorageClass", "storageclasses", "extensions", "v1beta1")); notFoundTransformations.put(new ResourceKey("RoleBinding", "rolebindings", "rbac.authorization.k8s.io", "v1"), new ResourceKey("RoleBinding", "rolebindings", "rbac.authorization.k8s.io", "v1beta1")); notFoundTransformations.put(new ResourceKey("Role", "roles", "rbac.authorization.k8s.io", "v1"), new ResourceKey("Role", "roles", "rbac.authorization.k8s.io", "v1beta1")); notFoundTransformations.put(new ResourceKey("ClusterRoleBinding", "clusterrolebindings", "rbac.authorization.k8s.io", "v1"), new ResourceKey("ClusterRoleBinding", "clusterrolebindings", "rbac.authorization.k8s.io", "v1beta1")); notFoundTransformations.put(new ResourceKey("ClusterRole", "clusterroles", "rbac.authorization.k8s.io", "v1"), new ResourceKey("ClusterRole", "clusterroles", "rbac.authorization.k8s.io", "v1beta1")); notFoundTransformations.put(new ResourceKey("CronJob", "cronjobs", "batch", "v1"), new ResourceKey("CronJob", "cronjobs", "batch", "v1beta1")); notFoundTransformations.put(new ResourceKey("CronJob", "cronjobs", "batch", "v1beta1"), new ResourceKey("CronJob", "cronjobs", "batch", "v2alpha1")); notFoundTransformations.put(new ResourceKey("Template", "template", "", "v1"), new ResourceKey("Template", "template", "template.openshift.io", "v1")); badRequestTransformations.put(new ResourceKey("Deployment", "deployments", "apps", "v1beta1"), new ResourceKey("Deployment", "deployments", "extensions", "v1beta1")); responseCodeToTransformations.put(400, badRequestTransformations); responseCodeToTransformations.put(404, notFoundTransformations); /** * OpenShift versions prior to 3.10 use the /oapi endpoint for Openshift specific resources. * However, since 3.10 /apis/{group} is being used. This has been removed completely in 4.x * versions of OpenShift. Hence, this code is to handle those cases. */ openshiftOAPITransformations.put("routes", new ResourceKey("Route", "routes", "route.openshift.io", "v1")); openshiftOAPITransformations.put("templates", new ResourceKey("Template", "templates", "template.openshift.io", "v1")); openshiftOAPITransformations.put("buildconfigs", new ResourceKey("BuildConfig", "buildconfigs", "build.openshift.io", "v1")); openshiftOAPITransformations.put("deploymentconfigs", new ResourceKey("DeploymentConfig", "deploymentconfigs", "apps.openshift.io", "v1")); openshiftOAPITransformations.put("imagestreams", new ResourceKey("ImageStream", "imagestreams", "image.openshift.io", "v1")); openshiftOAPITransformations.put("imagestreamtags", new ResourceKey("ImageStream", "imagestreamtags", "image.openshift.io", "v1")); openshiftOAPITransformations.put("securitycontextconstraints", new ResourceKey("SecurityContextConstraints", "securitycontextconstraints", "security.openshift.io", "v1")); } @Override public CompletableFuture<Boolean> afterFailure(Builder builder, HttpResponse<?> response, RequestTags tags) {<FILL_FUNCTION_BODY>
ResourceKey target = findNewTarget(builder, response); if (target == null) { return CompletableFuture.completedFuture(false); } HttpRequest request = response.request(); if (request.bodyString() != null && !request.method().equalsIgnoreCase(PATCH)) { JsonNode object = Serialization.unmarshal(request.bodyString(), JsonNode.class); if (object.get("apiVersion") != null) { ((ObjectNode) object).put("apiVersion", target.group + "/" + target.version); switch (request.method()) { case "POST": builder.post(JSON, Serialization.asJson(object)); break; case "PUT": builder.put(JSON, Serialization.asJson(object)); break; case "DELETE": builder.delete(JSON, Serialization.asJson(object)); break; default: return CompletableFuture.completedFuture(false); } } } return CompletableFuture.completedFuture(true);
1,618
270
1,888
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/CachedSingleThreadScheduler.java
CachedSingleThreadScheduler
startExecutor
class CachedSingleThreadScheduler { public static final long DEFAULT_TTL_MILLIS = TimeUnit.SECONDS.toMillis(10); private final long ttlMillis; private ScheduledThreadPoolExecutor executor; public CachedSingleThreadScheduler() { this(DEFAULT_TTL_MILLIS); } public CachedSingleThreadScheduler(long ttlMillis) { this.ttlMillis = ttlMillis; } public synchronized ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { startExecutor(); return executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); } public synchronized ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { startExecutor(); return executor.schedule(command, delay, unit); } private void startExecutor() {<FILL_FUNCTION_BODY>} /** * if the queue is empty since we're locked that means there's nothing pending. * since there is only a single thread, that means this running task is holding * it, so we can shut ourselves down */ private synchronized void shutdownCheck() { if (executor.getQueue().isEmpty()) { executor.shutdownNow(); executor = null; } } synchronized boolean hasExecutor() { return executor != null; } }
if (executor == null) { // start the executor and add a ttl task executor = new ScheduledThreadPoolExecutor(1, Utils.daemonThreadFactory(this)); executor.setRemoveOnCancelPolicy(true); executor.scheduleWithFixedDelay(this::shutdownCheck, ttlMillis, ttlMillis, TimeUnit.MILLISECONDS); }
398
102
500
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/ExponentialBackoffIntervalCalculator.java
ExponentialBackoffIntervalCalculator
from
class ExponentialBackoffIntervalCalculator { //we were using the same default in multiple places, so it has been moved here for now private static final int MAX_RETRY_INTERVAL_EXPONENT = 5; public static final int UNLIMITED_RETRIES = -1; private final int initialInterval; // other calculators express this as max wait private final int maxRetryIntervalExponent; private final int maxRetries; final AtomicInteger currentReconnectAttempt = new AtomicInteger(); public ExponentialBackoffIntervalCalculator(int initialInterval, int maxRetries) { this.initialInterval = initialInterval; this.maxRetries = maxRetries; this.maxRetryIntervalExponent = MAX_RETRY_INTERVAL_EXPONENT; } public long getInterval(int retryIndex) { int exponentOfTwo = retryIndex; if (exponentOfTwo > maxRetryIntervalExponent) { exponentOfTwo = maxRetryIntervalExponent; } return (long) initialInterval * (1 << exponentOfTwo); } public void resetReconnectAttempts() { currentReconnectAttempt.set(0); } public final long nextReconnectInterval() { int exponentOfTwo = currentReconnectAttempt.getAndIncrement(); return getInterval(exponentOfTwo); } public int getCurrentReconnectAttempt() { return currentReconnectAttempt.get(); } public boolean shouldRetry() { return maxRetries < 0 || currentReconnectAttempt.get() < maxRetries; } public static ExponentialBackoffIntervalCalculator from(RequestConfig requestConfig) {<FILL_FUNCTION_BODY>} }
final int requestRetryBackoffInterval = Optional.ofNullable(requestConfig) .map(RequestConfig::getRequestRetryBackoffInterval) .orElse(Config.DEFAULT_REQUEST_RETRY_BACKOFFINTERVAL); final int requestRetryBackoffLimit = Optional.ofNullable(requestConfig) .map(RequestConfig::getRequestRetryBackoffLimit) .orElse(Config.DEFAULT_REQUEST_RETRY_BACKOFFLIMIT); return new ExponentialBackoffIntervalCalculator(requestRetryBackoffInterval, requestRetryBackoffLimit);
447
141
588
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/HttpClientUtils.java
HeaderInterceptor
createApplicableInterceptors
class HeaderInterceptor implements Interceptor { private final Config config; private HeaderInterceptor(Config config) { this.config = config; } @Override public void before(BasicBuilder builder, HttpRequest request, RequestTags tags) { if (config.getCustomHeaders() != null && !config.getCustomHeaders().isEmpty()) { for (Map.Entry<String, String> entry : config.getCustomHeaders().entrySet()) { builder.header(entry.getKey(), entry.getValue()); } } if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) { builder.setHeader("User-Agent", config.getUserAgent()); } } } private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class); private static final String HEADER_INTERCEPTOR = "HEADER"; private static final String KUBERNETES_BACKWARDS_COMPATIBILITY_INTERCEPTOR_DISABLE = "kubernetes.backwardsCompatibilityInterceptor.disable"; private static final String BACKWARDS_COMPATIBILITY_DISABLE_DEFAULT = "true"; private static final Pattern IPV4_PATTERN = Pattern.compile( "(http://|https://)?(?<ipAddressOrSubnet>(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])(\\/([1-2]\\d|3[0-2]|\\d))?)(\\D+|$)"); private static final Pattern INVALID_HOST_PATTERN = Pattern.compile("[^\\da-zA-Z.\\-/:]+"); private HttpClientUtils() { } static URI getProxyUri(URL master, Config config) throws URISyntaxException { String proxy = config.getHttpsProxy(); if (master.getProtocol().equals("http")) { proxy = config.getHttpProxy(); } if (proxy != null) { URI proxyUrl = new URI(proxy); if (proxyUrl.getPort() < 0) { throw new IllegalArgumentException("Failure in creating proxy URL. Proxy port is required!"); } return proxyUrl; } return null; } public static Map<String, io.fabric8.kubernetes.client.http.Interceptor> createApplicableInterceptors(Config config, HttpClient.Factory factory) {<FILL_FUNCTION_BODY>
Map<String, io.fabric8.kubernetes.client.http.Interceptor> interceptors = new LinkedHashMap<>(); // Header Interceptor interceptors.put(HEADER_INTERCEPTOR, new HeaderInterceptor(config)); // Impersonator Interceptor interceptors.put(ImpersonatorInterceptor.NAME, new ImpersonatorInterceptor(config.getRequestConfig())); // Token Refresh Interceptor interceptors.put(TokenRefreshInterceptor.NAME, new TokenRefreshInterceptor(config, factory, Instant.now())); // Backwards Compatibility Interceptor String shouldDisableBackwardsCompatibilityInterceptor = Utils .getSystemPropertyOrEnvVar(KUBERNETES_BACKWARDS_COMPATIBILITY_INTERCEPTOR_DISABLE, BACKWARDS_COMPATIBILITY_DISABLE_DEFAULT); if (!Boolean.parseBoolean(shouldDisableBackwardsCompatibilityInterceptor)) { interceptors.put(BackwardsCompatibilityInterceptor.NAME, new BackwardsCompatibilityInterceptor()); } return interceptors;
669
293
962
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/IOHelpers.java
IOHelpers
copy
class IOHelpers { private IOHelpers() { throw new IllegalStateException("Utility class"); } public static String readFully(InputStream in, Charset charset) throws IOException { Reader r = new BufferedReader(new InputStreamReader(in, charset)); return readFully(r); } public static String readFully(InputStream in) throws IOException { return readFully(in, Charset.defaultCharset()); } public static String readFully(Reader r) throws IOException { try (StringWriter w = new StringWriter()) { copy(r, w); return w.toString(); } } private static void copy(Reader reader, Writer writer) throws IOException {<FILL_FUNCTION_BODY>} /** * @deprecated will be removed in future versions */ @Deprecated public static boolean isJSONValid(String json) { try { ObjectMapper objectMapper = Serialization.jsonMapper(); objectMapper.readTree(json); } catch (JsonProcessingException e) { return false; } return true; } /** * @deprecated will be removed in future versions */ @Deprecated public static String convertYamlToJson(String yaml) { return Serialization.asJson(Serialization.unmarshal(yaml, JsonNode.class)); } /** * @deprecated will be removed in future versions */ @Deprecated public static String convertToJson(String jsonOrYaml) { if (isJSONValid(jsonOrYaml)) { return jsonOrYaml; } return convertYamlToJson(jsonOrYaml); } }
char[] buffer = new char[8192]; int len; for (;;) { len = reader.read(buffer); if (len > 0) { writer.write(buffer, 0, len); } else { writer.flush(); break; } }
437
81
518
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/ImpersonatorInterceptor.java
ImpersonatorInterceptor
before
class ImpersonatorInterceptor implements Interceptor { public static final String IMPERSONATE_USER = "Impersonate-User"; public static final String NAME = "IMPERSONATOR"; private final RequestConfig requestConfig; public ImpersonatorInterceptor(RequestConfig requestConfig) { this.requestConfig = requestConfig; } @Override public void before(BasicBuilder builder, HttpRequest request, RequestTags tags) {<FILL_FUNCTION_BODY>} }
RequestConfig config = Optional.ofNullable(tags.getTag(RequestConfig.class)).orElse(requestConfig); if (isNotNullOrEmpty(config.getImpersonateUsername())) { builder.header(IMPERSONATE_USER, config.getImpersonateUsername()); String[] impersonateGroups = config.getImpersonateGroups(); if (isNotNullOrEmpty(impersonateGroups)) { for (String group : impersonateGroups) { builder.header("Impersonate-Group", group); } } Map<String, List<String>> impersonateExtras = config.getImpersonateExtras(); if (isNotNullOrEmpty(impersonateExtras)) { Collection<?> keys = impersonateExtras.keySet(); for (Object key : keys) { List<String> values = impersonateExtras.get(key); if (values != null) { for (String value : values) { builder.header("Impersonate-Extra-" + key, value); } } } } }
129
284
413
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/InputStreamPumper.java
InputStreamPumper
asInterruptible
class InputStreamPumper { private static final int DEFAULT_BUFFER_SIZE = 8192; private InputStreamPumper() { } private static final Logger LOGGER = LoggerFactory.getLogger(InputStreamPumper.class); public interface Writable { void write(byte[] b, int off, int len) throws IOException; } /** * Relies on {@link InputStream#available()} and a Thread sleep to ensure that the reads are interruptible. */ public static InputStream asInterruptible(InputStream is) {<FILL_FUNCTION_BODY>} /** * See InputStream.transferTo(java.io.OutputStream) in Java 9 or later */ public static void transferTo(InputStream in, Writable out) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int length; while ((length = in.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, length); } } /** * Pumps the given {@link InputStream} into the {@link Writable} target via a task started in the given {@link Executor}. * <br> * The input is not closed by this call. * <br> * If the {@link InputStream} is not interruptible, such as System.in, use {@link #asInterruptible(InputStream)} to decorate * the stream for this call. */ public static CompletableFuture<?> pump(InputStream in, Writable out, Executor executor) { return CompletableFuture.runAsync(() -> { try { InputStreamPumper.transferTo(in, out); } catch (InterruptedIOException e) { LOGGER.debug("Interrupted while pumping stream.", e); } catch (Exception e) { if (!Thread.currentThread().isInterrupted()) { LOGGER.error("Error while pumping stream.", e); } else { LOGGER.debug("Interrupted while pumping stream."); } } }, executor); } static class WritableOutputStream extends OutputStream { Writable writer; WritableOutputStream(Writable writer) { this.writer = writer; } @Override public void write(byte[] b, int off, int len) throws IOException { writer.write(b, off, len); } @Override public void write(int b) throws IOException { throw new UnsupportedOperationException(); } } public static OutputStream writableOutputStream(Writable writer, Integer bufferSize) { return new BufferedOutputStream(new WritableOutputStream(writer), Utils.getNonNullOrElse(bufferSize, DEFAULT_BUFFER_SIZE)); } }
return new InputStream() { @Override public int read() { throw new UnsupportedOperationException(); } @Override public int read(byte[] b, int off, int len) throws IOException { while (!Thread.currentThread().isInterrupted()) { if (is.available() > 0) { return is.read(b, off, len); } try { // The default sleep interval of 50 milliseconds came from the previous // incarnation of this code. If this needs tweaked, it can be changed to a parameter. Thread.sleep(50); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } throw new IOException(); } };
716
204
920
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/IpAddressMatcher.java
IpAddressMatcher
matches
class IpAddressMatcher { private static final Logger logger = LoggerFactory.getLogger(IpAddressMatcher.class); private final int nMaskBits; private final InetAddress requiredAddress; /** * Takes a specific IP address or a range specified using the IP/Netmask (e.g. * 192.168.1.0/24 or 202.24.0.0/14). * * @param ipAddress the address or range of addresses from which the request must * come. */ public IpAddressMatcher(String ipAddress) { if (ipAddress.indexOf('/') > 0) { String[] addressWithMask = ipAddress.split("\\/"); ipAddress = addressWithMask[0]; this.nMaskBits = Integer.parseInt(addressWithMask[1]); } else { this.nMaskBits = -1; } this.requiredAddress = parseAddress(ipAddress); } public boolean matches(String address) {<FILL_FUNCTION_BODY>} private InetAddress parseAddress(String address) { try { return InetAddress.getByName(address); } catch (UnknownHostException e) { // Log error only when address is not generated by client as default parameters if (!Config.DEFAULT_MASTER_URL.contains(address)) { logger.error("Failed to resolve hostname: {}", address); } return null; } } }
InetAddress remoteAddress = parseAddress(address); if (remoteAddress == null || requiredAddress == null) { return false; } if (!this.requiredAddress.getClass().equals(remoteAddress.getClass())) { return false; } if (this.nMaskBits < 0) { return remoteAddress.equals(this.requiredAddress); } byte[] remAddr = remoteAddress.getAddress(); byte[] reqAddr = this.requiredAddress.getAddress(); int nMaskFullBytes = this.nMaskBits / 8; byte finalByte = (byte) (0xFF00 >> (this.nMaskBits & 0x07)); for (int i = 0; i < nMaskFullBytes; i++) { if (remAddr[i] != reqAddr[i]) { return false; } } if (finalByte != 0) { return (remAddr[nMaskFullBytes] & finalByte) == (reqAddr[nMaskFullBytes] & finalByte); } return true;
389
271
660
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/KubernetesVersionFactory.java
KubernetesVersion
compareTo
class KubernetesVersion extends Version { public static final VersionFactory<KubernetesVersion> FACTORY = new VersionFactory<KubernetesVersion>() { private final Pattern versionPattern = Pattern.compile("v([0-9]+)((alpha|beta)([0-9]+)?)*"); @Override public KubernetesVersion create(String version) { if (version == null) { return null; } Matcher matcher = versionPattern.matcher(version); if (!matcher.matches()) { return null; } Integer majorValue = getInt(matcher.group(1)); String qualifierValue = matcher.group(3); Integer minorValue = getInt(matcher.group(4)); return new KubernetesVersion(majorValue, qualifierValue, minorValue, version); } private Integer getInt(String value) { if (value == null) { return null; } try { return Integer.parseInt(value); } catch (NumberFormatException e) { return null; } } }; private final Integer major; private final Optional<String> qualifier; private final Optional<Integer> minor; private KubernetesVersion(Integer major, String qualifier, Integer minor, String version) { super(version); this.major = major; this.qualifier = Optional.ofNullable(qualifier); this.minor = Optional.ofNullable(minor); } public Integer getMajor() { return major; } public Optional<String> getQualifier() { return qualifier; } public Optional<Integer> getMinor() { return minor; } public boolean isStable() { return qualifier.orElse(null) == null; } @Override public boolean isKubernetes() { return true; } /** * Compares this version to another version and returns whether this version has a * higher, equal or lower priority than the version that it is being compared to. * <p> * The Kubernetes specs at <a href= * "https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definition-versioning/#version-priority"> * Version Priority</a> state the following: * </p> * <ul> * <li>Entries that follow Kubernetes version patterns are sorted before those that do not.</li> * <li>For entries that follow Kubernetes version patterns, the numeric portions of the version string is sorted largest to * smallest.</li> * <li>If the strings beta or alpha follow the first numeric portion, they sorted in that order, after the equivalent string * without the beta * or alpha suffix (which is presumed to be the GA version).</li> * <li>If another number follows the beta, or alpha, those numbers are also sorted from largest to smallest.</li> * <li>Strings that don’t fit the above format are sorted alphabetically and the numeric portions are not treated specially. * Notice that in the example below, foo1 is sorted above foo10. * This is different from the sorting of the numeric portion of entries that do follow the Kubernetes version patterns.</li> * </ul> * * @param other the version to compare this version to * @return -1 if this version has a lower, 1 if it has a higher or 0 if the priorities are equal * */ @Override public int compareTo(Version other) {<FILL_FUNCTION_BODY>} private int compareMajor(KubernetesVersion other) { return major.compareTo(other.major); } private int compareMinor(KubernetesVersion other) { if (minor.isPresent()) { if (!other.minor.isPresent()) { return 1; } return minor.get().compareTo(other.minor.orElse(null)); } else { if (!other.minor.isPresent()) { return 0; } return -1; } } }
if (other == this) { return 0; } if (other instanceof NonKubernetesVersion) { return 1; } if (!(other instanceof KubernetesVersion)) { return 1; } KubernetesVersion otherKube = (KubernetesVersion) other; if (qualifier.isPresent()) { if (!otherKube.qualifier.isPresent()) { return -1; } int qualifierComparison = qualifier.get().compareTo(otherKube.qualifier.orElse(null)); if (qualifierComparison != 0) { return qualifierComparison; } int majorComparison = compareMajor(otherKube); if (majorComparison != 0) { return majorComparison; } return compareMinor(otherKube); } else { if (!otherKube.qualifier.isPresent()) { return compareMajor(otherKube); } else { return 1; } }
1,084
261
1,345
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/KubernetesVersionPriority.java
KubernetesVersionPriority
sortByPriority
class KubernetesVersionPriority { private KubernetesVersionPriority() { } /** * Returns the version with the highest priority for the given list of versions. * * @param versions the versions to pick the version with the highest priority from * @return the version with the highest priority * @see CustomResourceDefinitionVersion#getName() * @see CustomResourceDefinitionSpec#getVersions() * @see KubernetesVersionPriority */ public static String highestPriority(List<String> versions) { List<Version> byPriority = sortByPriority(versions); if (byPriority.isEmpty()) { return null; } return byPriority.get(0).getFull(); } private static List<Version> sortByPriority(List<String> versions) { if (versions == null || versions.isEmpty()) { return Collections.emptyList(); } return versions.stream() .map(KubernetesVersionFactory::create) .sorted(Collections.reverseOrder()) .collect(Collectors.toList()); } /** * Returns a sorted list of resources, for example, {@link CustomResourceDefinitionVersion}s, * ordered from highest to lowest priority. * * @param resources the resources to sort * @param versionProvider a function to provide the version from the resource * @param <T> the resource type * @return the sorted list of resources * @see CustomResourceDefinitionVersion#getName() * @see CustomResourceDefinitionSpec#getVersions() * @see KubernetesVersionPriority */ public static <T> List<T> sortByPriority(List<T> resources, Function<T, String> versionProvider) {<FILL_FUNCTION_BODY>} }
Utils.checkNotNull(versionProvider, "versionProvider function can't be null"); if (resources == null || resources.isEmpty()) { return Collections.emptyList(); } return resources.stream() .sorted(Comparator.comparing(o -> KubernetesVersionFactory.create(versionProvider.apply(o)), Comparator.reverseOrder())) .collect(Collectors.toList());
438
107
545
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/PodStatusUtil.java
PodStatusUtil
getContainerStatus
class PodStatusUtil { private static final String POD_RUNNING = "Running"; private static final String POD_INITIALIZING = "PodInitializing"; private static final String CONTAINER_COMPLETED = "Completed"; private PodStatusUtil() { } /** * Returns {@code true} if the given pod is running. Returns {@code false} otherwise. * * The definition when a pod is considered running can be found at * <a href= * "https://github.com/openshift/origin/blob/master/vendor/k8s.io/api/core/v1/types.go#L3564">k8s.io/api/core/v1/types.go#L3564</a> * It states: * "PodRunning means the pod has been bound to a node and all of the containers have been started. * At least one container is still running or is in the process of being restarted." * * The logic is taken from <a href= * "https://github.com/openshift/origin/blob/master/vendor/k8s.io/kubernetes/pkg/printers/internalversion/printers.go#L695-L781">(kubernetes/printers.go) * printPod()</a> * and <a href= * "https://github.com/openshift/origin-web-console/blob/master/app/scripts/filters/resources.js#L1012-L1088">(openshift-web-console/resources.js) * podStatus()</a> * * @param pod the pod to return the running status for * @return returns true if the pod is running */ public static boolean isRunning(Pod pod) { if (isInStatus(POD_RUNNING, pod)) { return true; } if (hasDeletionTimestamp(pod) || isInitializing(pod)) { return false; } if (hasRunningContainer(pod)) { return !hasCompletedContainer(pod) || Readiness.isPodReady(pod); } return false; } private static boolean isInStatus(String expected, Pod pod) { if (pod == null || pod.getStatus() == null || expected == null) { return false; } return expected.equals(pod.getStatus().getPhase()) || expected.equals(pod.getStatus().getReason()); } private static boolean hasDeletionTimestamp(Pod pod) { if (pod == null) { return false; } return pod.getMetadata() != null && pod.getMetadata().getDeletionTimestamp() != null; } /** * Returns {@code true} if the given pod has at least 1 container that's initializing. * * @param pod the pod to return the initializing status for * @return returns true if the pod is initializing */ public static boolean isInitializing(Pod pod) { if (pod == null) { return false; } return pod.getStatus().getInitContainerStatuses().stream() .anyMatch(PodStatusUtil::isInitializing); } /** * Returns {@code true} if the given container status is terminated with an non-0 exit code or is waiting. * Returns {@code false} otherwise. */ private static boolean isInitializing(ContainerStatus status) { if (status == null) { return true; } ContainerState state = status.getState(); if (state == null) { return true; } if (isTerminated(state)) { return hasNonNullExitCode(state); } else if (isWaiting(state)) { return !isWaitingInitializing(state); } else { return true; } } private static boolean isTerminated(ContainerState state) { return state == null || state.getTerminated() != null; } private static boolean hasNonNullExitCode(ContainerState state) { return state.getTerminated() != null && state.getTerminated().getExitCode() != 0; } private static boolean isWaiting(ContainerState state) { return state == null || state.getWaiting() != null; } private static boolean isWaitingInitializing(ContainerState state) { return state != null && state.getWaiting() != null && POD_INITIALIZING.equals(state.getWaiting().getReason()); } private static boolean hasRunningContainer(Pod pod) { return getContainerStatus(pod).stream() .anyMatch(PodStatusUtil::isRunning); } private static boolean isRunning(ContainerStatus status) { return status.getReady() != null && status.getState() != null && status.getState().getRunning() != null; } private static boolean hasCompletedContainer(Pod pod) { return getContainerStatus(pod).stream() .anyMatch(PodStatusUtil::isCompleted); } private static boolean isCompleted(ContainerStatus status) { return status.getState() != null && status.getState().getTerminated() != null && CONTAINER_COMPLETED.equals(status.getState().getTerminated().getReason()); } /** * Returns the container status for all containers of the given pod. Returns an empty list * if the pod has no status * * @param pod the pod to return the container status for * @return list of container status * * @see Pod#getStatus() * @see PodStatus#getContainerStatuses() */ public static List<ContainerStatus> getContainerStatus(Pod pod) {<FILL_FUNCTION_BODY>} }
if (pod == null || pod.getStatus() == null) { return Collections.emptyList(); } return pod.getStatus().getContainerStatuses();
1,518
47
1,565
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/ReflectUtils.java
ReflectUtils
objectMetadata
class ReflectUtils { private ReflectUtils() { throw new IllegalStateException("Utility class"); } public static ObjectMeta objectMetadata(Object obj) throws ReflectiveOperationException {<FILL_FUNCTION_BODY>} public static String namespace(Object obj) throws ReflectiveOperationException { if (obj == null) { return ""; } return objectMetadata(obj).getNamespace(); } public static ListMeta listMetadata(Object listObj) throws ReflectiveOperationException { if (listObj instanceof KubernetesResourceList) { return ((KubernetesResourceList<?>) listObj).getMetadata(); } try { Method mdField = listObj.getClass().getMethod("getMetadata"); return (ListMeta) mdField.invoke(listObj); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new ReflectiveOperationException(e); } } public static <ApiType> List<ApiType> getItems(Object listObj) throws ReflectiveOperationException { if (listObj instanceof KubernetesResourceList) { return ((KubernetesResourceList) listObj).getItems(); } try { Method getItemsMethod = listObj.getClass().getMethod("getItems"); return (List<ApiType>) getItemsMethod.invoke(listObj); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new ReflectiveOperationException(e); } } }
if (obj == null) { return null; } if (obj instanceof HasMetadata) { return ((HasMetadata) obj).getMetadata(); } try { Method mdField = obj.getClass().getMethod("getMetadata"); return (ObjectMeta) mdField.invoke(obj); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new ReflectiveOperationException(e); }
387
116
503
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/Serialization.java
Serialization
yamlMapper
class Serialization { private Serialization() { } /** * Create an instance that mimics the old behavior * - scans the classpath for KubernetesResources, and provides a static mapper / UnmatchedFieldTypeModule * * Future versions will further override the KubernetesDeserializer initialization as * it will no longer be expected to use Serialization with KubernetesResources. */ private static final KubernetesSerialization kubernetesSerialization = new KubernetesSerialization(); /** * @deprecated use {@link KubernetesSerialization#getUnmatchedFieldTypeModule()} instead */ @Deprecated public static final UnmatchedFieldTypeModule UNMATCHED_FIELD_TYPE_MODULE = kubernetesSerialization .getUnmatchedFieldTypeModule(); private static volatile ObjectMapper YAML_MAPPER; /** * {@link ObjectMapper} singleton instance used internally by the Kubernetes client. * * <p> * The ObjectMapper has an {@link UnmatchedFieldTypeModule} module registered. This module allows the client * to work with Resources that contain properties that don't match the target field type. This is especially useful * and necessary to work with OpenShift Templates. * * <p> * n.b. the use of this module gives precedence to properties present in the additionalProperties Map present * in most KubernetesResource instances. If a property is both defined in the Map and in the original field, the * one from the additionalProperties Map will be serialized. * * @deprecated the static mapper should not be used directly */ @Deprecated public static ObjectMapper jsonMapper() { return kubernetesSerialization.getMapper(); } /** * {@link ObjectMapper} singleton instance used internally by the Kubernetes client. * * <p> * The ObjectMapper has an {@link UnmatchedFieldTypeModule} module registered. This module allows the client * to work with Resources that contain properties that don't match the target field type. This is especially useful * and necessary to work with OpenShift Templates. * * <p> * n.b. the use of this module gives precedence to properties present in the additionalProperties Map present * in most KubernetesResource instances. If a property is both defined in the Map and in the original field, the * one from the additionalProperties Map will be serialized. * * @deprecated use {@link #asYaml(Object)} or one of the unmarshal methods */ @Deprecated public static ObjectMapper yamlMapper() {<FILL_FUNCTION_BODY>} /** * Allow application to clear out the YAML mapper in order to allow its garbage collection. * This is useful because in a lot of cases the YAML mapper is only need at application startup * when the client is created, so there is no reason to keep the very heavy (in terms of memory) mapper * around indefinitely. * * @deprecated to be removed in later versions */ @Deprecated public static void clearYamlMapper() { YAML_MAPPER = null; } /** * Returns a JSON representation of the given object. * * <p> * If the provided object contains a JsonAnyGetter annotated method with a Map that contains an entry that * overrides a field of the provided object, the Map entry will take precedence upon serialization. Properties won't * be duplicated. * * @param object the object to serialize. * @param <T> the type of the object being serialized. * @return a String containing a JSON representation of the provided object. */ public static <T> String asJson(T object) { return kubernetesSerialization.asJson(object); } /** * Returns a YAML representation of the given object. * * <p> * If the provided object contains a JsonAnyGetter annotated method with a Map that contains an entry that * overrides a field of the provided object, the Map entry will take precedence upon serialization. Properties won't * be duplicated. * * @param object the object to serialize. * @param <T> the type of the object being serialized. * @return a String containing a JSON representation of the provided object. */ public static <T> String asYaml(T object) { return kubernetesSerialization.asYaml(object); } /** * Unmarshals a stream. * <p> * The type is assumed to be {@link KubernetesResource} * * @param is The {@link InputStream}. * @param <T> The target type. * * @return returns de-serialized object * * @deprecated use {@link KubernetesSerialization} instead */ @Deprecated public static <T> T unmarshal(InputStream is) { return kubernetesSerialization.unmarshal(is); } /** * Unmarshals a {@link String} * <p> * The type is assumed to be {@link KubernetesResource} * * @param str The {@link String}. * @param <T> template argument denoting type * @return returns de-serialized object * * @deprecated use {@link KubernetesSerialization} instead */ @Deprecated public static <T> T unmarshal(String str) { return kubernetesSerialization.unmarshal(str); } /** * Unmarshals a {@link String} * * @param str The {@link String}. * @param type The target type. * @param <T> template argument denoting type * @return returns de-serialized object */ public static <T> T unmarshal(String str, final Class<T> type) { return kubernetesSerialization.unmarshal(str, type); } /** * Unmarshals an {@link InputStream}. * * @param is The {@link InputStream}. * @param type The type. * @param <T> Template argument denoting type * @return returns de-serialized object */ public static <T> T unmarshal(InputStream is, final Class<T> type) { return kubernetesSerialization.unmarshal(is, type); } /** * Unmarshals an {@link InputStream}. * * @param is The {@link InputStream}. * @param type The {@link TypeReference}. * @param <T> Template argument denoting type * @return returns de-serialized object * * @deprecated use {@link KubernetesSerialization#unmarshal(InputStream, TypeReference)} */ @Deprecated public static <T> T unmarshal(InputStream is, TypeReference<T> type) { return kubernetesSerialization.unmarshal(is, type); } /** * Create a copy of the resource via serialization. * * @return a deep clone of the resource * @throws IllegalArgumentException if the cloning cannot be performed */ public static <T> T clone(T resource) { return kubernetesSerialization.clone(resource); } }
if (YAML_MAPPER == null) { synchronized (Serialization.class) { if (YAML_MAPPER == null) { YAML_MAPPER = new ObjectMapper( new YAMLFactory().disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID)); YAML_MAPPER.registerModules(UNMATCHED_FIELD_TYPE_MODULE); } } } return YAML_MAPPER;
1,848
125
1,973
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/TokenRefreshInterceptor.java
TokenRefreshInterceptor
before
class TokenRefreshInterceptor implements Interceptor { public static final String AUTHORIZATION = "Authorization"; public static final String NAME = "TOKEN"; protected final Config config; private final Function<Config, CompletableFuture<String>> remoteRefresh; private static final int REFRESH_INTERVAL_MINUTE = 1; private volatile Instant latestRefreshTimestamp; public TokenRefreshInterceptor(Config config, HttpClient.Factory factory, Instant latestRefreshTimestamp) { this(config, latestRefreshTimestamp, newestConfig -> OpenIDConnectionUtils.resolveOIDCTokenFromAuthConfig(config, newestConfig.getAuthProvider().getConfig(), factory.newBuilder())); } public TokenRefreshInterceptor(Config config, Instant latestRefreshTimestamp, Function<Config, CompletableFuture<String>> remoteRefresh) { this.config = config; this.remoteRefresh = remoteRefresh; this.latestRefreshTimestamp = latestRefreshTimestamp; } @Override public void before(BasicBuilder headerBuilder, HttpRequest request, RequestTags tags) {<FILL_FUNCTION_BODY>} private static String getEffectiveOauthToken(Config config) { if (config.getOauthTokenProvider() != null) { return config.getOauthTokenProvider().getToken(); } if (config.getOauthToken() != null) { return config.getOauthToken(); } return config.getAutoOAuthToken(); } protected boolean useBasicAuth() { return isBasicAuth(); } final protected boolean isBasicAuth() { return Utils.isNotNullOrEmpty(config.getUsername()) && Utils.isNotNullOrEmpty(config.getPassword()); } private boolean isTimeToRefresh() { return latestRefreshTimestamp.plus(REFRESH_INTERVAL_MINUTE, ChronoUnit.MINUTES).isBefore(Instant.now()); } @Override public CompletableFuture<Boolean> afterFailure(BasicBuilder headerBuilder, HttpResponse<?> response, RequestTags tags) { if (shouldFail(response)) { return CompletableFuture.completedFuture(false); } return refreshToken(headerBuilder); } protected boolean shouldFail(HttpResponse<?> response) { return useBasicAuth() || response.code() != HttpURLConnection.HTTP_UNAUTHORIZED; } private CompletableFuture<Boolean> refreshToken(BasicBuilder headerBuilder) { if (config.getOauthTokenProvider() != null) { String tokenFromProvider = config.getOauthTokenProvider().getToken(); return CompletableFuture.completedFuture(overrideNewAccessTokenToConfig(tokenFromProvider, headerBuilder)); } if (config.getOauthToken() != null) { return CompletableFuture.completedFuture(false); } Config newestConfig = config.refresh(); final CompletableFuture<String> newAccessToken = extractNewAccessTokenFrom(newestConfig); return newAccessToken.thenApply(token -> overrideNewAccessTokenToConfig(token, headerBuilder)); } private CompletableFuture<String> extractNewAccessTokenFrom(Config newestConfig) { if (useRemoteRefresh(newestConfig)) { // TODO: determine the appropriate fall-back behavior. If the result here is null, do we use the non-remote token return remoteRefresh.apply(newestConfig); } return CompletableFuture.completedFuture(getEffectiveOauthToken(newestConfig)); } protected boolean useRemoteRefresh(Config newestConfig) { // TODO: in a hard failure scenario, should we skip the expired check return isAuthProviderOidc(newestConfig) && OpenIDConnectionUtils.idTokenExpired(newestConfig); } private boolean overrideNewAccessTokenToConfig(String newAccessToken, BasicBuilder headerBuilder) { if (Utils.isNotNullOrEmpty(newAccessToken)) { headerBuilder.setHeader(AUTHORIZATION, "Bearer " + newAccessToken); config.setAutoOAuthToken(newAccessToken); updateLatestRefreshTimestamp(); return true; } return false; } private void updateLatestRefreshTimestamp() { latestRefreshTimestamp = Instant.now(); } private static boolean isAuthProviderOidc(Config newestConfig) { return newestConfig.getAuthProvider() != null && newestConfig.getAuthProvider().getName().equalsIgnoreCase("oidc"); } }
if (useBasicAuth()) { headerBuilder.header(AUTHORIZATION, HttpClientUtils.basicCredentials(config.getUsername(), config.getPassword())); return; } String token = getEffectiveOauthToken(config); if (Utils.isNotNullOrEmpty(token)) { headerBuilder.header(AUTHORIZATION, "Bearer " + token); } else if (useRemoteRefresh(config)) { // trigger a 401, rather than attempting an unauthenticated request headerBuilder.header(AUTHORIZATION, "Bearer invalid"); } if (isTimeToRefresh()) { refreshToken(headerBuilder); }
1,160
177
1,337
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/URLUtils.java
URLBuilder
addQueryParameter
class URLBuilder { private final StringBuilder url; public URLBuilder(String url) { this.url = new StringBuilder(url); } public URLBuilder(URL url) { this(url.toString()); } public URLBuilder addQueryParameter(String key, String value) {<FILL_FUNCTION_BODY>} public URL build() { try { return new URL(toString()); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage(), e); } } @Override public String toString() { return this.url.toString(); } }
if (url.indexOf("?") == -1) { url.append("?"); } else { url.append("&"); } url.append(encodeToUTF(key).replaceAll("[+]", "%20")).append("=").append(encodeToUTF(value).replaceAll("[+]", "%20")); return this;
171
94
265
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/CreateOnlyResourceOperation.java
CreateOnlyResourceOperation
create
class CreateOnlyResourceOperation<I, O> extends OperationSupport implements InOutCreateable<I, O> { protected Class<O> type; protected CreateOnlyResourceOperation(OperationContext ctx) { super(ctx); } public Class<O> getType() { return type; } protected O handleCreate(I resource) throws ExecutionException, InterruptedException, IOException { return handleCreate(resource, getType()); } @Override public O create(I item) {<FILL_FUNCTION_BODY>} }
try { return handleCreate(item); } catch (ExecutionException | IOException e) { throw KubernetesClientException.launderThrowable(e); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(ie); }
143
84
227
<methods>public void <init>(io.fabric8.kubernetes.client.Client) ,public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public static Status createStatus(HttpResponse<?>, io.fabric8.kubernetes.client.utils.KubernetesSerialization) ,public static Status createStatus(int, java.lang.String) ,public java.lang.String getAPIGroupName() ,public java.lang.String getAPIGroupVersion() ,public io.fabric8.kubernetes.client.Config getConfig() ,public io.fabric8.kubernetes.client.utils.KubernetesSerialization getKubernetesSerialization() ,public java.lang.String getName() ,public java.lang.String getNamespace() ,public java.net.URL getNamespacedUrl(java.lang.String) throws java.net.MalformedURLException,public java.net.URL getNamespacedUrl() throws java.net.MalformedURLException,public io.fabric8.kubernetes.client.dsl.internal.OperationContext getOperationContext() ,public io.fabric8.kubernetes.client.RequestConfig getRequestConfig() ,public java.lang.String getResourceT() ,public java.net.URL getResourceURLForPatchOperation(java.net.URL, io.fabric8.kubernetes.client.dsl.base.PatchContext) throws java.net.MalformedURLException,public java.net.URL getResourceURLForWriteOperation(java.net.URL) throws java.net.MalformedURLException,public transient java.net.URL getResourceUrl(java.lang.String, java.lang.String, java.lang.String[]) throws java.net.MalformedURLException,public java.net.URL getResourceUrl(java.lang.String, java.lang.String) throws java.net.MalformedURLException,public java.net.URL getResourceUrl() throws java.net.MalformedURLException,public R1 handleRaw(Class<R1>, java.lang.String, java.lang.String, java.lang.Object) ,public boolean isResourceNamespaced() ,public static io.fabric8.kubernetes.client.KubernetesClientException requestException(io.fabric8.kubernetes.client.http.HttpRequest, java.lang.Throwable, java.lang.String) ,public static io.fabric8.kubernetes.client.KubernetesClientException requestException(io.fabric8.kubernetes.client.http.HttpRequest, java.lang.Exception) ,public static io.fabric8.kubernetes.client.KubernetesClientException requestFailure(io.fabric8.kubernetes.client.http.HttpRequest, Status) ,public static io.fabric8.kubernetes.client.KubernetesClientException requestFailure(io.fabric8.kubernetes.client.http.HttpRequest, Status, java.lang.String) ,public transient R1 restCall(Class<R1>, java.lang.String[]) <variables>private static final java.lang.String CLIENT_STATUS_FLAG,private static final java.lang.String FIELD_MANAGER_PARAM,public static final java.lang.String JSON,public static final java.lang.String JSON_MERGE_PATCH,public static final java.lang.String JSON_PATCH,private static final Logger LOG,public static final java.lang.String STRATEGIC_MERGE_JSON_PATCH,protected java.lang.String apiGroupName,protected java.lang.String apiGroupVersion,protected final non-sealed io.fabric8.kubernetes.client.Config config,protected io.fabric8.kubernetes.client.dsl.internal.OperationContext context,protected boolean dryRun,protected final non-sealed io.fabric8.kubernetes.client.http.HttpClient httpClient,protected java.lang.String name,protected java.lang.String namespace,protected final non-sealed java.lang.String resourceT,protected java.lang.String subresource
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/DefaultOperationInfo.java
DefaultOperationInfo
forOperationType
class DefaultOperationInfo implements OperationInfo { private final String kind; private final String operationType; private final String name; private final String namespace; private final String group; private final String plural; private final String version; public DefaultOperationInfo(String kind, String operationType, String name, String namespace, String group, String plural, String version) { this.kind = kind; this.name = name; this.namespace = namespace; this.operationType = operationType; this.group = group; this.plural = plural; this.version = version; } @Override public String getKind() { return kind; } @Override public String getName() { return name; } @Override public String getNamespace() { return namespace; } @Override public String getOperationType() { return operationType; } @Override public OperationInfo forOperationType(String type) {<FILL_FUNCTION_BODY>} @Override public String getGroup() { return group; } @Override public String getPlural() { return plural; } @Override public String getVersion() { return version; } }
return new DefaultOperationInfo(kind, type, name, namespace, group, plural, version);
337
25
362
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/ExecWatchInputStream.java
ExecWatchInputStream
consume
class ExecWatchInputStream extends InputStream { private static final int BUFFER_SIZE = 1 << 15; private final LinkedList<ByteBuffer> buffers = new LinkedList<>(); private boolean complete; private boolean closed; private Throwable failed; private ByteBuffer currentBuffer; private final Runnable request; private final int bufferSize; public ExecWatchInputStream(Runnable request) { this(request, BUFFER_SIZE); } public ExecWatchInputStream(Runnable request, int bufferSize) { this.request = request; this.bufferSize = bufferSize; } void onExit(Integer exitCode, Throwable t) { synchronized (buffers) { if (complete) { return; } complete = true; if (t != null) { failed = t; } else if (exitCode != null && exitCode != 0) { failed = new KubernetesClientException("process exited with a non-zero exit code: " + exitCode); } buffers.notifyAll(); } } void consume(List<ByteBuffer> value) {<FILL_FUNCTION_BODY>} private ByteBuffer current() throws IOException { synchronized (buffers) { while (currentBuffer == null || !currentBuffer.hasRemaining()) { // Check whether the stream is closed or exhausted if (closed) { throw new IOException("closed", failed); } if (buffers.isEmpty()) { if (complete) { if (failed != null) { throw new IOException("closed", failed); } return null; } requestMoreIfNeeded(); } currentBuffer = buffers.poll(); if (currentBuffer == null && !complete) { try { buffers.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new InterruptedIOException(); } } } return currentBuffer; } } /** * Adapted from HttpResponseInputStream */ @Override public int read(byte[] bytes, int off, int len) throws IOException { // get the buffer to read from, possibly blocking if // none is available ByteBuffer buffer = current(); if (buffer == null) { return -1; } // don't attempt to read more than what is available // in the current buffer. int read = Math.min(buffer.remaining(), len); assert read > 0 && read <= buffer.remaining(); // buffer.get() will do the boundary check for us. buffer.get(bytes, off, read); return read; } @Override public int read() throws IOException { byte[] single = new byte[1]; if (read(single) == -1) { return -1; } return single[0] & 0xFF; } @Override public void close() throws IOException { synchronized (buffers) { if (this.closed) { return; } this.closed = true; requestMoreIfNeeded(); this.buffers.clear(); buffers.notifyAll(); } } private void requestMoreIfNeeded() { if (currentBuffer != null) { this.currentBuffer = null; this.request.run(); } } }
synchronized (buffers) { if (closed) { // even if closed there may be other streams // so keep pulling request.run(); return; } assert !complete || failed == null; buffers.addAll(value); buffers.notifyAll(); if ((currentBuffer != null ? currentBuffer.remaining() : 0) + buffers.stream().mapToInt(ByteBuffer::remaining).sum() < bufferSize) { request.run(); } }
888
134
1,022
<methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public byte[] readAllBytes() throws java.io.IOException,public byte[] readNBytes(int) throws java.io.IOException,public int readNBytes(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public void skipNBytes(long) throws java.io.IOException,public long transferTo(java.io.OutputStream) throws java.io.IOException<variables>private static final int DEFAULT_BUFFER_SIZE,private static final int MAX_BUFFER_SIZE,private static final int MAX_SKIP_BUFFER_SIZE
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/LogWatchCallback.java
LogWatchCallback
callAndWait
class LogWatchCallback implements LogWatch, AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(LogWatchCallback.class); private final OutputStream out; private WritableByteChannel outChannel; private volatile InputStream output; private final AtomicBoolean closed = new AtomicBoolean(false); private final CompletableFuture<AsyncBody> asyncBody = new CompletableFuture<>(); private final SerialExecutor serialExecutor; public LogWatchCallback(OutputStream out, OperationContext context) { this.out = out; if (out != null) { outChannel = Channels.newChannel(out); } this.serialExecutor = new SerialExecutor(context.getExecutor()); } @Override public void close() { cleanUp(); } private void cleanUp() { if (!closed.compareAndSet(false, true)) { return; } asyncBody.thenAccept(AsyncBody::cancel); serialExecutor.shutdownNow(); } public LogWatchCallback callAndWait(HttpClient client, URL url) {<FILL_FUNCTION_BODY>} @Override public InputStream getOutput() { return output; } public void onFailure(Throwable u) { //If we have closed the watch ignore everything if (closed.get()) { return; } LOGGER.error("Log Callback Failure.", u); cleanUp(); } }
HttpRequest request = client.newHttpRequestBuilder().url(url).build(); if (out == null) { // we can pass the input stream directly to the consumer client.sendAsync(request, InputStream.class).whenComplete((r, e) -> { if (e != null) { onFailure(e); } if (r != null) { this.output = r.body(); } }).join(); } else { // we need to write the bytes to the given output // we don't know if the write will be blocking, so hand it off to another thread client.consumeBytes(request, (buffers, a) -> CompletableFuture.runAsync(() -> { for (ByteBuffer byteBuffer : buffers) { try { outChannel.write(byteBuffer); } catch (IOException e1) { throw KubernetesClientException.launderThrowable(e1); } } }, serialExecutor).whenComplete((v, t) -> { if (t != null) { a.cancel(); onFailure(t); } else if (!closed.get()) { a.consume(); } else { a.cancel(); } })).whenComplete((a, e) -> { if (e != null) { onFailure(e); } if (a != null) { asyncBody.complete(a.body()); a.body().consume(); a.body().done().whenComplete((v, t) -> CompletableFuture.runAsync(() -> { if (t != null) { onFailure(t); } else { cleanUp(); } }, serialExecutor)); } }); } return this;
377
459
836
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/MetricOperationsImpl.java
MetricOperationsImpl
metrics
class MetricOperationsImpl<T, L> extends OperationSupport implements MetricOperation<T, L> { public static final String METRIC_ENDPOINT_URL = "apis/metrics.k8s.io/v1beta1/"; private final Class<L> apiTypeListClass; private final Class<T> apiTypeClass; public MetricOperationsImpl(OperationContext operationContext, Class<T> apiTypeClass, Class<L> apiTypeListClass) { super(operationContext); this.apiTypeClass = apiTypeClass; this.apiTypeListClass = apiTypeListClass; } /** * Get a list of metrics * * @return a list object for metrics */ @Override public L metrics() {<FILL_FUNCTION_BODY>} /** * Get a single metric. name needs to be provided. * * @return a single metric */ @Override public T metric() { try { return handleMetric(getMetricEndpointUrl(), apiTypeClass); } catch (IOException exception) { throw KubernetesClientException.launderThrowable(exception); } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(interruptedException); } } /** * Returns a list of metrics matching specified labels * * @param labelsMap labels as HashMap * @return list of metrics found matching provided label */ @Override public L metrics(Map<String, Object> labelsMap) { Map<String, String> labels = new HashMap<>(); labelsMap.forEach((k, v) -> labels.put(k, v.toString())); return withLabels(labels).metrics(); } protected String getMetricEndpointUrlWithPlural(String plural) { String result = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL); if (isResourceNamespaced() && namespace != null) { result += "namespaces/" + namespace + "/"; } result += plural; if (context.getName() != null) { result += "/" + context.getName(); } if (Utils.isNotNullOrEmpty(context.getLabels())) { result = getUrlWithLabels(result, context.getLabels()); } return result; } private String getMetricEndpointUrl() { return getMetricEndpointUrlWithPlural(context.getPlural()); } private String getUrlWithLabels(String baseUrl, Map<String, String> labels) { URLBuilder httpUrlBuilder = new URLBuilder(baseUrl); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : labels.entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()).append(","); } httpUrlBuilder.addQueryParameter("labelSelector", sb.substring(0, sb.toString().length() - 1)); return httpUrlBuilder.toString(); } }
try { return handleMetric(getMetricEndpointUrl(), apiTypeListClass); } catch (IOException exception) { throw KubernetesClientException.launderThrowable(exception); } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(interruptedException); }
792
93
885
<methods>public void <init>(io.fabric8.kubernetes.client.Client) ,public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public static Status createStatus(HttpResponse<?>, io.fabric8.kubernetes.client.utils.KubernetesSerialization) ,public static Status createStatus(int, java.lang.String) ,public java.lang.String getAPIGroupName() ,public java.lang.String getAPIGroupVersion() ,public io.fabric8.kubernetes.client.Config getConfig() ,public io.fabric8.kubernetes.client.utils.KubernetesSerialization getKubernetesSerialization() ,public java.lang.String getName() ,public java.lang.String getNamespace() ,public java.net.URL getNamespacedUrl(java.lang.String) throws java.net.MalformedURLException,public java.net.URL getNamespacedUrl() throws java.net.MalformedURLException,public io.fabric8.kubernetes.client.dsl.internal.OperationContext getOperationContext() ,public io.fabric8.kubernetes.client.RequestConfig getRequestConfig() ,public java.lang.String getResourceT() ,public java.net.URL getResourceURLForPatchOperation(java.net.URL, io.fabric8.kubernetes.client.dsl.base.PatchContext) throws java.net.MalformedURLException,public java.net.URL getResourceURLForWriteOperation(java.net.URL) throws java.net.MalformedURLException,public transient java.net.URL getResourceUrl(java.lang.String, java.lang.String, java.lang.String[]) throws java.net.MalformedURLException,public java.net.URL getResourceUrl(java.lang.String, java.lang.String) throws java.net.MalformedURLException,public java.net.URL getResourceUrl() throws java.net.MalformedURLException,public R1 handleRaw(Class<R1>, java.lang.String, java.lang.String, java.lang.Object) ,public boolean isResourceNamespaced() ,public static io.fabric8.kubernetes.client.KubernetesClientException requestException(io.fabric8.kubernetes.client.http.HttpRequest, java.lang.Throwable, java.lang.String) ,public static io.fabric8.kubernetes.client.KubernetesClientException requestException(io.fabric8.kubernetes.client.http.HttpRequest, java.lang.Exception) ,public static io.fabric8.kubernetes.client.KubernetesClientException requestFailure(io.fabric8.kubernetes.client.http.HttpRequest, Status) ,public static io.fabric8.kubernetes.client.KubernetesClientException requestFailure(io.fabric8.kubernetes.client.http.HttpRequest, Status, java.lang.String) ,public transient R1 restCall(Class<R1>, java.lang.String[]) <variables>private static final java.lang.String CLIENT_STATUS_FLAG,private static final java.lang.String FIELD_MANAGER_PARAM,public static final java.lang.String JSON,public static final java.lang.String JSON_MERGE_PATCH,public static final java.lang.String JSON_PATCH,private static final Logger LOG,public static final java.lang.String STRATEGIC_MERGE_JSON_PATCH,protected java.lang.String apiGroupName,protected java.lang.String apiGroupVersion,protected final non-sealed io.fabric8.kubernetes.client.Config config,protected io.fabric8.kubernetes.client.dsl.internal.OperationContext context,protected boolean dryRun,protected final non-sealed io.fabric8.kubernetes.client.http.HttpClient httpClient,protected java.lang.String name,protected java.lang.String namespace,protected final non-sealed java.lang.String resourceT,protected java.lang.String subresource
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NodeMetricOperationsImpl.java
NodeMetricOperationsImpl
isResourceNamespaced
class NodeMetricOperationsImpl extends MetricOperationsImpl<NodeMetrics, NodeMetricsList> implements NodeMetricOperation { public NodeMetricOperationsImpl(Client client) { this(HasMetadataOperationsImpl.defaultContext(client)); } public NodeMetricOperationsImpl(OperationContext context) { super(context.withPlural("nodes"), NodeMetrics.class, NodeMetricsList.class); } @Override public NodeMetrics metrics(String nodeName) { return withName(nodeName).metric(); } @Override public NodeMetricOperation withLabels(Map<String, String> labels) { return new NodeMetricOperationsImpl(context.withLabels(labels)); } @Override public NodeMetricOperation withName(String name) { return new NodeMetricOperationsImpl(context.withName(name)); } @Override public boolean isResourceNamespaced() {<FILL_FUNCTION_BODY>} }
return false; // workaround until the class metadata is fixed
253
16
269
<methods>public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext, Class<NodeMetrics>, Class<NodeMetricsList>) ,public NodeMetrics metric() ,public NodeMetricsList metrics() ,public NodeMetricsList metrics(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String METRIC_ENDPOINT_URL,private final non-sealed Class<NodeMetrics> apiTypeClass,private final non-sealed Class<NodeMetricsList> apiTypeListClass
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PatchUtils.java
PatchUtils
withoutRuntimeState
class PatchUtils { public enum Format { YAML, JSON } private PatchUtils() { } public static String withoutRuntimeState(Object object, Format format, boolean omitStatus, KubernetesSerialization serialization) { Function<Object, String> mapper = format == Format.JSON ? serialization::asJson : serialization::asYaml; return mapper.apply(withoutRuntimeState(object, omitStatus, serialization)); } static JsonNode withoutRuntimeState(Object object, boolean omitStatus, KubernetesSerialization serialization) {<FILL_FUNCTION_BODY>} private static void removeEmptyArrays(ObjectNode raw) { List<String> toRemove = new ArrayList<>(); for (Iterator<String> names = raw.fieldNames(); names.hasNext();) { String name = names.next(); JsonNode node = raw.get(name); if (node.isArray() && node.size() == 0) { toRemove.add(name); } if (node.isObject()) { removeEmptyArrays((ObjectNode) node); } } raw.remove(toRemove); } public static String jsonDiff(Object current, Object updated, boolean omitStatus, KubernetesSerialization serialization) { return serialization .asJson(JsonDiff.asJson(withoutRuntimeState(current, omitStatus, serialization), withoutRuntimeState(updated, omitStatus, serialization))); } }
ObjectNode raw = serialization.convertValue(object, ObjectNode.class); // it makes the diffs more compact to not have empty arrays removeEmptyArrays(raw); Optional.ofNullable(raw.get("metadata")).filter(ObjectNode.class::isInstance).map(ObjectNode.class::cast).ifPresent(m -> { m.remove("creationTimestamp"); m.remove("deletionTimestamp"); m.remove("generation"); m.remove("selfLink"); m.remove("uid"); }); if (omitStatus) { raw.remove("status"); } return raw;
378
163
541
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PodOperationContext.java
StreamContext
getLogParameters
class StreamContext { private OutputStream outputStream; public StreamContext(OutputStream outputStream) { this.outputStream = outputStream; } public StreamContext() { } } private String containerId; private StreamContext output; private StreamContext error; private StreamContext errorChannel; private boolean redirectingIn; private InputStream in; private boolean tty; private boolean terminatedStatus; private boolean timestamps; private String sinceTimestamp; private Integer sinceSeconds; private Integer tailingLines; private Integer readyWaitTimeout; private boolean prettyOutput; private ExecListener execListener; private Integer limitBytes; private Integer bufferSize; private String file; private String dir; private boolean terminateOnError; private boolean rolling; public PodOperationContext withContainerId(String containerId) { return this.toBuilder().containerId(containerId).build(); } public PodOperationContext withIn(InputStream in) { return this.toBuilder().in(in).build(); } public PodOperationContext withTty(boolean tty) { return this.toBuilder().tty(tty).build(); } public PodOperationContext withTerminatedStatus(boolean terminatedStatus) { return this.toBuilder().terminatedStatus(terminatedStatus).build(); } public PodOperationContext withTimestamps(boolean timestamps) { return this.toBuilder().timestamps(timestamps).build(); } public PodOperationContext withSinceTimestamp(String sinceTimestamp) { return this.toBuilder().sinceTimestamp(sinceTimestamp).build(); } public PodOperationContext withSinceSeconds(Integer sinceSeconds) { return this.toBuilder().sinceSeconds(sinceSeconds).build(); } public PodOperationContext withTailingLines(Integer tailingLines) { return this.toBuilder().tailingLines(tailingLines).build(); } public PodOperationContext withPrettyOutput(boolean prettyOutput) { return this.toBuilder().prettyOutput(prettyOutput).build(); } public PodOperationContext withExecListener(ExecListener execListener) { return this.toBuilder().execListener(execListener).build(); } public PodOperationContext withLimitBytes(Integer limitBytes) { return this.toBuilder().limitBytes(limitBytes).build(); } public PodOperationContext withBufferSize(Integer bufferSize) { return this.toBuilder().bufferSize(bufferSize).build(); } public PodOperationContext withFile(String file) { return this.toBuilder().file(file).build(); } public PodOperationContext withDir(String dir) { return this.toBuilder().dir(dir).build(); } public PodOperationContext withReadyWaitTimeout(Integer logWaitTimeout) { return this.toBuilder().readyWaitTimeout(logWaitTimeout).build(); } public String getLogParameters() {<FILL_FUNCTION_BODY>
StringBuilder sb = new StringBuilder(); sb.append("log?pretty=").append(prettyOutput); if (containerId != null && !containerId.isEmpty()) { sb.append("&container=").append(containerId); } if (terminatedStatus) { sb.append("&previous=true"); } if (sinceSeconds != null) { sb.append("&sinceSeconds=").append(sinceSeconds); } else if (sinceTimestamp != null) { sb.append("&sinceTime=").append(sinceTimestamp); } if (tailingLines != null) { sb.append("&tailLines=").append(tailingLines); } if (limitBytes != null) { sb.append("&limitBytes=").append(limitBytes); } if (timestamps) { sb.append("&timestamps=true"); } return sb.toString();
772
247
1,019
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PortForwarderWebsocket.java
PortForwarderWebsocket
forward
class PortForwarderWebsocket { private static final Logger LOG = LoggerFactory.getLogger(PortForwarderWebsocket.class); private final HttpClient client; private final Executor executor; private final long connectTimeoutMills; public PortForwarderWebsocket(HttpClient client, Executor executor, long connectTimeoutMillis) { this.client = client; this.executor = executor; this.connectTimeoutMills = connectTimeoutMillis; } public LocalPortForward forward(final URL resourceBaseUrl, final int port, final InetAddress localHost, final int localPort) {<FILL_FUNCTION_BODY>} public PortForward forward(URL resourceBaseUrl, int port, final ReadableByteChannel in, final WritableByteChannel out) { final PortForwarderWebsocketListener listener = new PortForwarderWebsocketListener(in, out, executor); CompletableFuture<WebSocket> socket = client .newWebSocketBuilder() .uri(URI.create(URLUtils.join(resourceBaseUrl.toString(), "portforward?ports=" + port))) .connectTimeout(connectTimeoutMills, TimeUnit.MILLISECONDS) .subprotocol("v4.channel.k8s.io") .buildAsync(listener); socket.whenComplete((w, t) -> { if (t != null) { listener.onError(w, t); } }); return new PortForward() { private final AtomicBoolean closed = new AtomicBoolean(); @Override public void close() { if (!closed.compareAndSet(false, true)) { return; } socket.whenComplete((w, t) -> { if (w != null) { listener.closeBothWays(w, 1001, "User closing"); } }); } @Override public boolean isAlive() { return listener.isAlive(); } @Override public boolean errorOccurred() { return listener.errorOccurred(); } @Override public Collection<Throwable> getClientThrowables() { return listener.getClientThrowables(); } @Override public Collection<Throwable> getServerThrowables() { return listener.getServerThrowables(); } }; } InetSocketAddress createNewInetSocketAddress(InetAddress localHost, int localPort) { if (localHost == null) { return new InetSocketAddress(localPort); } return new InetSocketAddress(localHost, localPort); } }
try { InetSocketAddress inetSocketAddress = createNewInetSocketAddress(localHost, localPort); final ServerSocketChannel server = ServerSocketChannel.open().bind(inetSocketAddress); final AtomicBoolean alive = new AtomicBoolean(true); final CopyOnWriteArrayList<PortForward> handles = new CopyOnWriteArrayList<>(); final ExecutorService executorService = Executors.newSingleThreadExecutor(); // Create a handle that can be used to retrieve information and stop the port-forward final LocalPortForward localPortForwardHandle = new LocalPortForward() { @Override public void close() throws IOException { alive.set(false); try { server.close(); } finally { Utils.closeQuietly(handles); executorService.shutdownNow(); } } @Override public boolean isAlive() { return alive.get(); } @Override public boolean errorOccurred() { for (PortForward handle : handles) { if (handle.errorOccurred()) { return true; } } return false; } @Override public InetAddress getLocalAddress() { try { return ((InetSocketAddress) server.getLocalAddress()).getAddress(); } catch (IOException e) { throw new IllegalStateException("Cannot determine local address", e); } } @Override public int getLocalPort() { try { return ((InetSocketAddress) server.getLocalAddress()).getPort(); } catch (IOException e) { throw new IllegalStateException("Cannot determine local address", e); } } @Override public Collection<Throwable> getClientThrowables() { Collection<Throwable> clientThrowables = new ArrayList<>(); for (PortForward handle : handles) { clientThrowables.addAll(handle.getClientThrowables()); } return clientThrowables; } @Override public Collection<Throwable> getServerThrowables() { Collection<Throwable> serverThrowables = new ArrayList<>(); for (PortForward handle : handles) { serverThrowables.addAll(handle.getServerThrowables()); } return serverThrowables; } }; // Start listening on localhost for new connections. // Every new connection will open its own stream on the remote resource. executorService.execute(() -> { // accept cycle while (alive.get()) { try { SocketChannel socket = server.accept(); handles.add(forward(resourceBaseUrl, port, socket, socket)); } catch (IOException e) { if (alive.get()) { LOG.error("Error while listening for connections", e); } Utils.closeQuietly(localPortForwardHandle); } } }); return localPortForwardHandle; } catch (IOException e) { throw new IllegalStateException("Unable to port forward", e); }
681
766
1,447
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PortForwarderWebsocketListener.java
PortForwarderWebsocketListener
onMessage
class PortForwarderWebsocketListener implements WebSocket.Listener { private static final Logger logger = LoggerFactory.getLogger(PortForwarderWebsocketListener.class); private static final String LOG_PREFIX = "FWD"; private static final String PROTOCOL_ERROR = "Protocol error"; private static final int BUFFER_SIZE = 4096; private final ExecutorService pumperService = Executors.newSingleThreadExecutor(); private final SerialExecutor serialExecutor; private final AtomicBoolean alive = new AtomicBoolean(true); final Collection<Throwable> clientThrowables = new CopyOnWriteArrayList<>(); final Collection<Throwable> serverThrowables = new CopyOnWriteArrayList<>(); private final ReadableByteChannel in; private final WritableByteChannel out; private int messagesRead = 0; public PortForwarderWebsocketListener(ReadableByteChannel in, WritableByteChannel out, Executor executor) { this.in = in; this.out = out; this.serialExecutor = new SerialExecutor(executor); } @Override public void onOpen(final WebSocket webSocket) { logger.debug("{}: onOpen", LOG_PREFIX); if (in != null) { pumperService.execute(() -> { try { pipe(in, webSocket, alive::get); } catch (IOException | InterruptedException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } logger.debug("Error while writing client data"); if (alive.get()) { clientThrowables.add(e); closeBothWays(webSocket, 1001, "Client error"); } } }); } } @Override public void onMessage(WebSocket webSocket, String text) { logger.debug("{}: onMessage(String)", LOG_PREFIX); onMessage(webSocket, ByteBuffer.wrap(text.getBytes(StandardCharsets.UTF_8))); } @Override public void onMessage(WebSocket webSocket, ByteBuffer buffer) {<FILL_FUNCTION_BODY>} @Override public void onClose(WebSocket webSocket, int code, String reason) { logger.debug("{}: onClose. Code={}, Reason={}", LOG_PREFIX, code, reason); if (alive.get()) { closeForwarder(); } } @Override public void onError(WebSocket webSocket, Throwable t) { logger.debug("{}: Throwable received from websocket", LOG_PREFIX, t); if (alive.get()) { serverThrowables.add(t); closeForwarder(); } } boolean isAlive() { return alive.get(); } boolean errorOccurred() { return !clientThrowables.isEmpty() || !serverThrowables.isEmpty(); } Collection<Throwable> getClientThrowables() { return clientThrowables; } Collection<Throwable> getServerThrowables() { return serverThrowables; } void closeBothWays(WebSocket webSocket, int code, String message) { logger.debug("{}: Closing with code {} and reason: {}", LOG_PREFIX, code, message); alive.set(false); try { webSocket.sendClose(code, message); } catch (Exception e) { serverThrowables.add(e); logger.debug("Error while closing the websocket", e); } closeForwarder(); } private void closeForwarder() { serialExecutor.execute(() -> { alive.set(false); if (in != null) { Utils.closeQuietly(in); } if (out != null && out != in) { Utils.closeQuietly(out); } pumperService.shutdownNow(); serialExecutor.shutdownNow(); }); } private static void pipe(ReadableByteChannel in, WebSocket webSocket, BooleanSupplier isAlive) throws IOException, InterruptedException { final ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); int read; do { buffer.clear(); buffer.put((byte) 0); // channel byte read = in.read(buffer); if (read > 0) { buffer.flip(); webSocket.send(buffer); } else if (read == 0) { // in is non-blocking, prevent a busy loop Thread.sleep(50); } } while (isAlive.getAsBoolean() && read >= 0); } }
messagesRead++; if (messagesRead <= 2) { // skip the first two messages, containing the ports used internally webSocket.request(); return; } if (!buffer.hasRemaining()) { KubernetesClientException e = new KubernetesClientException("Received an empty message"); serverThrowables.add(e); logger.debug("Protocol error", e); closeBothWays(webSocket, 1002, PROTOCOL_ERROR); return; } byte channel = buffer.get(); if (channel < 0 || channel > 1) { KubernetesClientException e = new KubernetesClientException( String.format("Received a wrong channel from the remote socket: %s", channel)); serverThrowables.add(e); logger.debug("Protocol error", e); closeBothWays(webSocket, 1002, PROTOCOL_ERROR); } else if (channel == 1) { // Error channel KubernetesClientException e = new KubernetesClientException( String.format("Received an error from the remote socket %s", ExecWebSocketListener.toString(buffer))); serverThrowables.add(e); logger.debug("Server error", e); closeForwarder(); } else { // Data if (out != null) { serialExecutor.execute(() -> { try { while (buffer.hasRemaining()) { int written = out.write(buffer); // channel byte already skipped if (written == 0) { // out is non-blocking, prevent a busy loop Thread.sleep(50); } } webSocket.request(); } catch (IOException | InterruptedException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } if (alive.get()) { clientThrowables.add(e); logger.debug("Error while forwarding data to the client", e); closeBothWays(webSocket, 1002, PROTOCOL_ERROR); } } }); } }
1,214
538
1,752
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/VersionUsageUtils.java
VersionUsageUtils
log
class VersionUsageUtils { private static final Logger LOG = LoggerFactory.getLogger(VersionUsageUtils.class); private static final ConcurrentHashMap<String, Boolean> UNSTABLE_TYPES = new ConcurrentHashMap<>(); private static final boolean LOG_EACH_USAGE = false; private VersionUsageUtils() { } public static void log(String type, String version) {<FILL_FUNCTION_BODY>} private static boolean isUnstable(String version) { String lowerCaseVersion = version.toLowerCase(Locale.ROOT); return lowerCaseVersion.contains("beta") || lowerCaseVersion.contains("alpha"); } private static void alert(String type, String version) { String message = "The client is using resource type '{}' with unstable version '{}'"; if (type.equals("customresourcedefinitions") && version.equals("v1beta1")) { LOG.debug(message, type, version); } else { LOG.warn(message, type, version); } } }
if (type == null || version == null) { return; } if (isUnstable(version)) { if (LOG_EACH_USAGE || UNSTABLE_TYPES.putIfAbsent(type + "-" + version, true) == null) { alert(type, version); } }
273
87
360
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchConnectionManager.java
WatchConnectionManager
start
class WatchConnectionManager<T extends HasMetadata, L extends KubernetesResourceList<T>> extends AbstractWatchManager<T> { private final long connectTimeoutMillis; protected WatcherWebSocketListener<T> listener; private volatile CompletableFuture<WebSocket> websocketFuture; volatile boolean ready; public WatchConnectionManager(final HttpClient client, final BaseOperation<T, L, ?> baseOperation, final ListOptions listOptions, final Watcher<T> watcher, final int reconnectInterval, final int reconnectLimit, long websocketTimeout) throws MalformedURLException { super(watcher, baseOperation, listOptions, reconnectLimit, reconnectInterval, client); this.connectTimeoutMillis = websocketTimeout; } @Override protected void closeCurrentRequest() { Optional.ofNullable(this.websocketFuture).ifPresent( theFuture -> theFuture.whenComplete( (w, t) -> Optional.ofNullable(w).ifPresent(ws -> ws.sendClose(1000, null)))); } public CompletableFuture<WebSocket> getWebsocketFuture() { return websocketFuture; } @Override protected void start(URL url, Map<String, String> headers, WatchRequestState state) {<FILL_FUNCTION_BODY>} }
this.listener = new WatcherWebSocketListener<>(this, state); Builder builder = client.newWebSocketBuilder(); headers.forEach(builder::header); builder.uri(URI.create(url.toString())).connectTimeout(connectTimeoutMillis, TimeUnit.MILLISECONDS); this.websocketFuture = builder.buildAsync(this.listener).handle((w, t) -> { if (t != null) { try { if (t instanceof WebSocketHandshakeException) { WebSocketHandshakeException wshe = (WebSocketHandshakeException) t; HttpResponse<?> response = wshe.getResponse(); final int code = response.code(); // We do not expect a 200 in response to the websocket connection. If it occurs, we throw // an exception and try the watch via a persistent HTTP Get. // Newer Kubernetes might also return 503 Service Unavailable in case WebSockets are not supported Status status = OperationSupport.createStatus(response, this.baseOperation.getKubernetesSerialization()); t = OperationSupport.requestFailure(client.newHttpRequestBuilder().url(url).build(), status, "Received " + code + " on websocket"); } throw KubernetesClientException.launderThrowable(t); } finally { if (ready) { // if we're ready, then invoke the reconnect logic watchEnded(t, state); } } } this.ready = true; return w; });
337
391
728
<methods>public void close() ,public synchronized void closeRequest() ,public void setWatchEndCheckMs(int) <variables>private static final int INFO_LOG_CONNECTION_ERRORS,protected BaseOperation<T,?,?> baseOperation,protected final non-sealed io.fabric8.kubernetes.client.http.HttpClient client,private final Map<Class<?>,java.lang.Integer> endErrors,final non-sealed java.util.concurrent.atomic.AtomicBoolean forceClosed,volatile io.fabric8.kubernetes.client.dsl.internal.AbstractWatchManager.WatchRequestState latestRequestState,private final non-sealed ListOptions listOptions,private static final Logger logger,private final non-sealed boolean receiveBookmarks,private Future<?> reconnectAttempt,private final non-sealed int reconnectLimit,private final non-sealed java.net.URL requestUrl,final non-sealed AtomicReference<java.lang.String> resourceVersion,private java.util.concurrent.atomic.AtomicInteger retryAfterSeconds,private final non-sealed io.fabric8.kubernetes.client.utils.ExponentialBackoffIntervalCalculator retryIntervalCalculator,private int watchEndCheckMs,final non-sealed Watcher<T> watcher
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java
WatchHTTPManager
start
class WatchHTTPManager<T extends HasMetadata, L extends KubernetesResourceList<T>> extends AbstractWatchManager<T> { private CompletableFuture<HttpResponse<AsyncBody>> call; private volatile AsyncBody body; public WatchHTTPManager(final HttpClient client, final BaseOperation<T, L, ?> baseOperation, final ListOptions listOptions, final Watcher<T> watcher, final int reconnectInterval, final int reconnectLimit) throws MalformedURLException { super(watcher, baseOperation, listOptions, reconnectLimit, reconnectInterval, client); } @Override protected synchronized void start(URL url, Map<String, String> headers, WatchRequestState state) {<FILL_FUNCTION_BODY>} @Override protected synchronized void closeCurrentRequest() { Optional.ofNullable(call).ifPresent(theFuture -> { theFuture.cancel(true); }); Optional.ofNullable(body).ifPresent(AsyncBody::cancel); } }
HttpRequest.Builder builder = client.newHttpRequestBuilder().url(url).forStreaming(); headers.forEach(builder::header); StringBuffer buffer = new StringBuffer(); call = client.consumeBytes(builder.build(), (b, a) -> { for (ByteBuffer content : b) { for (char c : StandardCharsets.UTF_8.decode(content).array()) { if (c == '\n') { onMessage(buffer.toString(), state); buffer.setLength(0); } else { buffer.append(c); } } } a.consume(); }); call.whenComplete((response, t) -> { if (t != null) { this.watchEnded(t, state); } if (response != null) { body = response.body(); if (!response.isSuccessful()) { Status status = OperationSupport.createStatus(response.code(), response.message()); if (onStatus(status, state)) { return; // terminal state } watchEnded(new KubernetesClientException(status), state); } else { resetReconnectAttempts(state); body.consume(); body.done().whenComplete((v, e) -> watchEnded(e, state)); } } });
255
344
599
<methods>public void close() ,public synchronized void closeRequest() ,public void setWatchEndCheckMs(int) <variables>private static final int INFO_LOG_CONNECTION_ERRORS,protected BaseOperation<T,?,?> baseOperation,protected final non-sealed io.fabric8.kubernetes.client.http.HttpClient client,private final Map<Class<?>,java.lang.Integer> endErrors,final non-sealed java.util.concurrent.atomic.AtomicBoolean forceClosed,volatile io.fabric8.kubernetes.client.dsl.internal.AbstractWatchManager.WatchRequestState latestRequestState,private final non-sealed ListOptions listOptions,private static final Logger logger,private final non-sealed boolean receiveBookmarks,private Future<?> reconnectAttempt,private final non-sealed int reconnectLimit,private final non-sealed java.net.URL requestUrl,final non-sealed AtomicReference<java.lang.String> resourceVersion,private java.util.concurrent.atomic.AtomicInteger retryAfterSeconds,private final non-sealed io.fabric8.kubernetes.client.utils.ExponentialBackoffIntervalCalculator retryIntervalCalculator,private int watchEndCheckMs,final non-sealed Watcher<T> watcher
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatcherWebSocketListener.java
WatcherWebSocketListener
onMessage
class WatcherWebSocketListener<T extends HasMetadata> implements WebSocket.Listener { protected static final Logger logger = LoggerFactory.getLogger(WatcherWebSocketListener.class); protected final WatchRequestState state; protected final AbstractWatchManager<T> manager; protected WatcherWebSocketListener(AbstractWatchManager<T> manager, WatchRequestState state) { this.manager = manager; this.state = state; } @Override public void onOpen(final WebSocket webSocket) { logger.debug("WebSocket successfully opened"); manager.resetReconnectAttempts(state); } @Override public void onError(WebSocket webSocket, Throwable t) { manager.watchEnded(t, state); } @Override public void onMessage(WebSocket webSocket, String text) {<FILL_FUNCTION_BODY>} @Override public void onMessage(WebSocket webSocket, ByteBuffer bytes) { onMessage(webSocket, StandardCharsets.UTF_8.decode(bytes).toString()); } @Override public void onClose(WebSocket webSocket, int code, String reason) { logger.debug("WebSocket close received. code: {}, reason: {}", code, reason); try { webSocket.sendClose(code, reason); } finally { manager.watchEnded(null, state); } } }
try { manager.onMessage(text, state); } finally { webSocket.request(); }
361
33
394
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/ReplicaSetOperationsImpl.java
ReplicaSetOperationsImpl
rollback
class ReplicaSetOperationsImpl extends RollableScalableResourceOperation<ReplicaSet, ReplicaSetList, RollableScalableResource<ReplicaSet>> implements TimeoutImageEditReplacePatchable<ReplicaSet> { public ReplicaSetOperationsImpl(Client client) { this(new PodOperationContext(), HasMetadataOperationsImpl.defaultContext(client)); } ReplicaSetOperationsImpl(PodOperationContext context, OperationContext superContext) { super(context, superContext.withApiGroupName("apps") .withApiGroupVersion("v1") .withPlural("replicasets"), ReplicaSet.class, ReplicaSetList.class); } @Override public ReplicaSetOperationsImpl newInstance(OperationContext context) { return new ReplicaSetOperationsImpl(rollingOperationContext, context); } @Override public ReplicaSetOperationsImpl newInstance(PodOperationContext context, OperationContext superContext) { return new ReplicaSetOperationsImpl(context, superContext); } @Override public RollingUpdater<ReplicaSet, ReplicaSetList> getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit) { return new ReplicaSetRollingUpdater(context.getClient(), getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), getRequestConfig().getLoggingInterval()); } @Override public Status rollback(DeploymentRollback deploymentRollback) {<FILL_FUNCTION_BODY>} @Override public String getLog(boolean isPretty) { return PodOperationUtil .getLog(new ReplicaSetOperationsImpl(rollingOperationContext.withPrettyOutput(isPretty), context).doGetLog(), isPretty); } private List<PodResource> doGetLog() { ReplicaSet replicaSet = requireFromServer(); return PodOperationUtil.getPodOperationsForController(context, rollingOperationContext, replicaSet.getMetadata().getUid(), getReplicaSetSelectorLabels(replicaSet)); } /** * Returns an unclosed Reader. It's the caller responsibility to close it. * * @return Reader */ @Override public Reader getLogReader() { return PodOperationUtil.getLogReader(doGetLog()); } /** * Returns an unclosed InputStream. It's the caller responsibility to close it. * * @return InputStream */ @Override public InputStream getLogInputStream() { return PodOperationUtil.getLogInputStream(doGetLog()); } @Override public LogWatch watchLog(OutputStream out) { return PodOperationUtil.watchLog(doGetLog(), out); } static Map<String, String> getReplicaSetSelectorLabels(ReplicaSet replicaSet) { Map<String, String> labels = new HashMap<>(); if (replicaSet != null && replicaSet.getSpec() != null && replicaSet.getSpec().getSelector() != null) { labels.putAll(replicaSet.getSpec().getSelector().getMatchLabels()); } return labels; } @Override protected List<Container> getContainers(ReplicaSet value) { return value.getSpec().getTemplate().getSpec().getContainers(); } @Override public TimeTailPrettyLoggable limitBytes(int limitBytes) { return new ReplicaSetOperationsImpl(rollingOperationContext.withLimitBytes(limitBytes), context); } @Override public TimeTailPrettyLoggable terminated() { return new ReplicaSetOperationsImpl(rollingOperationContext.withTerminatedStatus(true), context); } @Override public Loggable withPrettyOutput() { return new ReplicaSetOperationsImpl(rollingOperationContext.withPrettyOutput(true), context); } @Override public PrettyLoggable tailingLines(int lines) { return new ReplicaSetOperationsImpl(rollingOperationContext.withTailingLines(lines), context); } @Override public TailPrettyLoggable sinceTime(String timestamp) { return new ReplicaSetOperationsImpl(rollingOperationContext.withSinceTimestamp(timestamp), context); } @Override public TailPrettyLoggable sinceSeconds(int seconds) { return new ReplicaSetOperationsImpl(rollingOperationContext.withSinceSeconds(seconds), context); } @Override public BytesLimitTerminateTimeTailPrettyLoggable usingTimestamps() { return new ReplicaSetOperationsImpl(rollingOperationContext.withTimestamps(true), context); } }
throw new KubernetesClientException("rollback not supported in case of ReplicaSets");
1,194
25
1,219
<methods>public ReplicaSet edit(UnaryOperator<ReplicaSet>) ,public java.lang.String getLog() ,public io.fabric8.kubernetes.client.dsl.Loggable inContainer(java.lang.String) ,public abstract RollableScalableResourceOperation<ReplicaSet,ReplicaSetList,RollableScalableResource<ReplicaSet>> newInstance(io.fabric8.kubernetes.client.dsl.internal.PodOperationContext, io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public ReplicaSet pause() ,public ReplicaSet restart() ,public ReplicaSet resume() ,public TimeoutImageEditReplacePatchable<ReplicaSet> rolling() ,public ReplicaSet undo() ,public ReplicaSet updateImage(java.lang.String) ,public ReplicaSet updateImage(Map<java.lang.String,java.lang.String>) ,public io.fabric8.kubernetes.client.dsl.LogWatch watchLog() ,public io.fabric8.kubernetes.client.dsl.Loggable withLogWaitTimeout(java.lang.Integer) ,public io.fabric8.kubernetes.client.dsl.Loggable withReadyWaitTimeout(java.lang.Integer) ,public RollableScalableResourceOperation<ReplicaSet,ReplicaSetList,RollableScalableResource<ReplicaSet>> withTimeout(long, java.util.concurrent.TimeUnit) ,public RollableScalableResourceOperation<ReplicaSet,ReplicaSetList,RollableScalableResource<ReplicaSet>> withTimeoutInMillis(long) <variables>protected final non-sealed io.fabric8.kubernetes.client.dsl.internal.PodOperationContext rollingOperationContext
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/ReplicaSetRollingUpdater.java
ReplicaSetRollingUpdater
updateDeploymentKey
class ReplicaSetRollingUpdater extends RollingUpdater<ReplicaSet, ReplicaSetList> { ReplicaSetRollingUpdater(Client client, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { super(client, namespace, rollingTimeoutMillis, loggingIntervalMillis); } @Override protected ReplicaSet createClone(ReplicaSet obj, String newName, String newDeploymentHash) { return new ReplicaSetBuilder(obj) .editMetadata() .withResourceVersion(null) .withName(newName) .endMetadata() .editSpec() .withReplicas(0) .editSelector().addToMatchLabels(DEPLOYMENT_KEY, newDeploymentHash).endSelector() .editTemplate().editMetadata().addToLabels(DEPLOYMENT_KEY, newDeploymentHash).endMetadata().endTemplate() .endSpec() .build(); } @Override protected FilterWatchListDeletable<Pod, PodList, PodResource> selectedPodLister(ReplicaSet obj) { return selectedPodLister(obj.getSpec().getSelector()); } @Override protected ReplicaSet updateDeploymentKey(String name, String hash) {<FILL_FUNCTION_BODY>} @Override protected ReplicaSet removeDeploymentKey(String name) { return resources().inNamespace(namespace).withName(name).edit(old -> new ReplicaSetBuilder(old).editSpec() .editSelector().removeFromMatchLabels(DEPLOYMENT_KEY).endSelector() .editTemplate().editMetadata().removeFromLabels(DEPLOYMENT_KEY).endMetadata().endTemplate() .endSpec() .build()); } @Override protected int getReplicas(ReplicaSet obj) { return obj.getSpec().getReplicas(); } @Override protected ReplicaSet setReplicas(ReplicaSet obj, int replicas) { return new ReplicaSetBuilder(obj).editSpec().withReplicas(replicas).endSpec().build(); } @Override protected MixedOperation<ReplicaSet, ReplicaSetList, RollableScalableResource<ReplicaSet>> resources() { return new ReplicaSetOperationsImpl(this.client); } }
return resources().inNamespace(namespace).withName(name).edit(old -> new ReplicaSetBuilder(old).editSpec() .editSelector().addToMatchLabels(DEPLOYMENT_KEY, hash).endSelector() .editTemplate().editMetadata().addToLabels(DEPLOYMENT_KEY, hash).endMetadata().endTemplate() .endSpec() .build());
595
100
695
<methods>public static T pause(RollableScalableResourceOperation<T,?,?>) ,public static Map<java.lang.String,java.lang.Object> requestPayLoadForRolloutPause() ,public static Map<java.lang.String,java.lang.Object> requestPayLoadForRolloutRestart() ,public static Map<java.lang.String,java.lang.Object> requestPayLoadForRolloutResume() ,public static T restart(RollableScalableResourceOperation<T,?,?>) ,public static T resume(RollableScalableResourceOperation<T,?,?>) ,public ReplicaSet rollUpdate(ReplicaSet, ReplicaSet) <variables>private static final java.lang.Long DEFAULT_SERVER_GC_WAIT_TIMEOUT,public static final java.lang.String DEPLOYMENT_KEY,private static final transient Logger LOG,protected final non-sealed io.fabric8.kubernetes.client.Client client,private final non-sealed long loggingIntervalMillis,protected final non-sealed java.lang.String namespace,private final non-sealed long rollingTimeoutMillis
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/RollableScalableResourceOperation.java
RollableScalableResourceOperation
undo
class RollableScalableResourceOperation<T extends HasMetadata, L extends KubernetesResourceList<T>, R extends Resource<T>> extends HasMetadataOperation<T, L, R> implements RollableScalableResource<T>, TimeoutImageEditReplacePatchable<T> { protected final PodOperationContext rollingOperationContext; protected RollableScalableResourceOperation(PodOperationContext context, OperationContext superContext, Class<T> type, Class<L> listType) { super(superContext, type, listType); this.rollingOperationContext = context; } protected abstract RollingUpdater<T, L> getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit); @Override public T edit(UnaryOperator<T> function) { RollingUpdater<T, L> rollingUpdater = getRollingUpdater(context.getTimeout(), context.getTimeoutUnit()); if (!rollingOperationContext.isRolling() || rollingUpdater == null) { return super.edit(function); } T oldObj = getItemOrRequireFromServer(); T newObj = function.apply(getKubernetesSerialization().clone(oldObj)); return rollingUpdater.rollUpdate(oldObj, newObj); } public abstract RollableScalableResourceOperation<T, L, R> newInstance(PodOperationContext context, OperationContext superContext); @Override public Loggable withLogWaitTimeout(Integer logWaitTimeout) { return withReadyWaitTimeout(logWaitTimeout); } @Override public Loggable withReadyWaitTimeout(Integer timeout) { return newInstance(rollingOperationContext.withReadyWaitTimeout(timeout), context); } @Override public Loggable inContainer(String id) { return newInstance(rollingOperationContext.withContainerId(id), context); } @Override public TimeoutImageEditReplacePatchable<T> rolling() { return newInstance(rollingOperationContext.toBuilder().rolling(true).build(), context); } @Override public String getLog() { return getLog(rollingOperationContext.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 = getKubernetesSerialization().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); } @Override public RollableScalableResourceOperation<T, L, R> withTimeout(long timeout, TimeUnit unit) { return newInstance(rollingOperationContext, context.withTimeout(timeout, unit)); } @Override public RollableScalableResourceOperation<T, L, R> withTimeoutInMillis(long timeoutInMillis) { return withTimeout(timeoutInMillis, TimeUnit.MILLISECONDS); } @Override public T pause() { throw new KubernetesClientException(context.getPlural() + " pausing is not supported"); } @Override public T resume() { throw new KubernetesClientException(context.getPlural() + " resuming is not supported"); } @Override public T restart() { throw new KubernetesClientException(context.getPlural() + " restarting is not supported"); } @Override public T undo() {<FILL_FUNCTION_BODY>} }
throw new KubernetesClientException(context.getPlural() + " undo is not supported");
1,243
27
1,270
<methods>public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext, Class<T>, Class<L>) ,public T accept(Consumer<T>) ,public T edit(UnaryOperator<T>) ,public transient T edit(Visitor[]) ,public T editStatus(UnaryOperator<T>) ,public HasMetadataOperation<T,L,R> newInstance(io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public T patch() ,public T patch(io.fabric8.kubernetes.client.dsl.base.PatchContext) ,public T patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, T) ,public T patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, java.lang.String) ,public T patchStatus() ,public T patchStatus(T) ,public T replace() ,public T replaceStatus() ,public T scale(int) ,public T scale(int, boolean) ,public Scale scale(Scale) ,public T update() ,public T updateStatus() <variables>public static final long DEFAULT_GRACE_PERIOD_IN_SECONDS,public static final io.fabric8.kubernetes.api.model.DeletionPropagation DEFAULT_PROPAGATION_POLICY,private static final Logger LOGGER,private static final java.lang.String PATCH_OPERATION,private static final java.lang.String REPLACE_OPERATION,private static final java.lang.String UPDATE_OPERATION
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/StatefulSetOperationsImpl.java
StatefulSetOperationsImpl
undo
class StatefulSetOperationsImpl extends RollableScalableResourceOperation<StatefulSet, StatefulSetList, RollableScalableResource<StatefulSet>> implements TimeoutImageEditReplacePatchable<StatefulSet> { public StatefulSetOperationsImpl(Client client) { this(new PodOperationContext(), HasMetadataOperationsImpl.defaultContext(client)); } public StatefulSetOperationsImpl(PodOperationContext context, OperationContext superContext) { super(context, superContext.withApiGroupName("apps") .withApiGroupVersion("v1") .withPlural("statefulsets"), StatefulSet.class, StatefulSetList.class); } @Override public StatefulSetOperationsImpl newInstance(OperationContext context) { return new StatefulSetOperationsImpl(rollingOperationContext, context); } @Override public StatefulSetOperationsImpl newInstance(PodOperationContext context, OperationContext superContext) { return new StatefulSetOperationsImpl(context, superContext); } @Override public RollingUpdater<StatefulSet, StatefulSetList> getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit) { return null; } @Override public Status rollback(DeploymentRollback deploymentRollback) { throw new KubernetesClientException("rollback not supported in case of StatefulSets"); } @Override public String getLog(boolean isPretty) { return PodOperationUtil.getLog( new StatefulSetOperationsImpl(rollingOperationContext.withPrettyOutput(isPretty), context).doGetLog(), isPretty); } private List<PodResource> doGetLog() { StatefulSet statefulSet = requireFromServer(); return PodOperationUtil.getPodOperationsForController(context, rollingOperationContext, statefulSet.getMetadata().getUid(), getStatefulSetSelectorLabels(statefulSet)); } /** * Returns an unclosed Reader. It's the caller responsibility to close it. * * @return Reader */ @Override public Reader getLogReader() { return PodOperationUtil.getLogReader(doGetLog()); } /** * Returns an unclosed InputStream. It's the caller responsibility to close it. * * @return InputStream */ @Override public InputStream getLogInputStream() { return PodOperationUtil.getLogInputStream(doGetLog()); } @Override public LogWatch watchLog(OutputStream out) { return PodOperationUtil.watchLog(doGetLog(), out); } @Override public StatefulSet restart() { return RollingUpdater.restart(this); } @Override public StatefulSet undo() {<FILL_FUNCTION_BODY>} private ControllerRevisionList getControllerRevisionListForStatefulSet(StatefulSet statefulSet) { return this.context.getClient().resources(ControllerRevision.class, ControllerRevisionList.class).inNamespace(namespace) .withLabels(statefulSet.getSpec().getSelector().getMatchLabels()).list(); } static Map<String, String> getStatefulSetSelectorLabels(StatefulSet statefulSet) { Map<String, String> labels = new HashMap<>(); if (statefulSet != null && statefulSet.getSpec() != null && statefulSet.getSpec().getTemplate() != null && statefulSet.getSpec().getTemplate().getMetadata() != null) { labels.putAll(statefulSet.getSpec().getTemplate().getMetadata().getLabels()); } return labels; } @Override protected List<Container> getContainers(StatefulSet value) { return value.getSpec().getTemplate().getSpec().getContainers(); } @Override public TimeTailPrettyLoggable limitBytes(int limitBytes) { return new StatefulSetOperationsImpl(rollingOperationContext.withLimitBytes(limitBytes), context); } @Override public TimeTailPrettyLoggable terminated() { return new StatefulSetOperationsImpl(rollingOperationContext.withTerminatedStatus(true), context); } @Override public Loggable withPrettyOutput() { return new StatefulSetOperationsImpl(rollingOperationContext.withPrettyOutput(true), context); } @Override public PrettyLoggable tailingLines(int lines) { return new StatefulSetOperationsImpl(rollingOperationContext.withTailingLines(lines), context); } @Override public TailPrettyLoggable sinceTime(String timestamp) { return new StatefulSetOperationsImpl(rollingOperationContext.withSinceTimestamp(timestamp), context); } @Override public TailPrettyLoggable sinceSeconds(int seconds) { return new StatefulSetOperationsImpl(rollingOperationContext.withSinceSeconds(seconds), context); } @Override public BytesLimitTerminateTimeTailPrettyLoggable usingTimestamps() { return new StatefulSetOperationsImpl(rollingOperationContext.withTimestamps(true), context); } }
List<ControllerRevision> controllerRevisions = getControllerRevisionListForStatefulSet(get()).getItems(); if (controllerRevisions.size() < 2) { throw new IllegalStateException("No revision to rollback to!"); } // Sort list of replicaSets based on revision annotation controllerRevisions.sort((o1, o2) -> { Long revision2 = o2.getRevision(); Long revision1 = o1.getRevision(); if (revision1 != null && revision2 != null) { return revision2.intValue() - revision1.intValue(); } else if (revision1 != null) { return revision1.intValue(); } else if (revision2 != null) { return revision2.intValue(); } else { return 0; } }); ControllerRevision previousControllerRevision = controllerRevisions.get(1); return patch(PatchContext.of(PatchType.STRATEGIC_MERGE), getKubernetesSerialization().asJson(previousControllerRevision.getData()));
1,336
280
1,616
<methods>public StatefulSet edit(UnaryOperator<StatefulSet>) ,public java.lang.String getLog() ,public io.fabric8.kubernetes.client.dsl.Loggable inContainer(java.lang.String) ,public abstract RollableScalableResourceOperation<StatefulSet,StatefulSetList,RollableScalableResource<StatefulSet>> newInstance(io.fabric8.kubernetes.client.dsl.internal.PodOperationContext, io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public StatefulSet pause() ,public StatefulSet restart() ,public StatefulSet resume() ,public TimeoutImageEditReplacePatchable<StatefulSet> rolling() ,public StatefulSet undo() ,public StatefulSet updateImage(java.lang.String) ,public StatefulSet updateImage(Map<java.lang.String,java.lang.String>) ,public io.fabric8.kubernetes.client.dsl.LogWatch watchLog() ,public io.fabric8.kubernetes.client.dsl.Loggable withLogWaitTimeout(java.lang.Integer) ,public io.fabric8.kubernetes.client.dsl.Loggable withReadyWaitTimeout(java.lang.Integer) ,public RollableScalableResourceOperation<StatefulSet,StatefulSetList,RollableScalableResource<StatefulSet>> withTimeout(long, java.util.concurrent.TimeUnit) ,public RollableScalableResourceOperation<StatefulSet,StatefulSetList,RollableScalableResource<StatefulSet>> withTimeoutInMillis(long) <variables>protected final non-sealed io.fabric8.kubernetes.client.dsl.internal.PodOperationContext rollingOperationContext
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/batch/v1/JobOperationsImpl.java
JobOperationsImpl
waitUntilJobIsScaled
class JobOperationsImpl extends HasMetadataOperation<Job, JobList, ScalableResource<Job>> implements ScalableResource<Job> { static final transient Logger LOG = LoggerFactory.getLogger(JobOperationsImpl.class); private final PodOperationContext podControllerOperationContext; public JobOperationsImpl(Client client) { this(new PodOperationContext(), HasMetadataOperationsImpl.defaultContext(client)); } public JobOperationsImpl(PodOperationContext context, OperationContext superContext) { super(superContext.withApiGroupName("batch") .withApiGroupVersion("v1") .withPlural("jobs"), Job.class, JobList.class); this.podControllerOperationContext = context; } @Override public JobOperationsImpl newInstance(OperationContext context) { return new JobOperationsImpl(podControllerOperationContext, context); } @Override public Job scale(int count) { Job res = accept(b -> b.getSpec().setParallelism(count)); if (context.getTimeout() > 0) { waitUntilJobIsScaled(); res = get(); } return res; } /** * Lets wait until there are enough Ready pods of the given Job */ private void waitUntilJobIsScaled() {<FILL_FUNCTION_BODY>} @Override public String getLog() { return getLog(podControllerOperationContext.isPrettyOutput()); } @Override public String getLog(boolean isPretty) { StringBuilder stringBuilder = new StringBuilder(); List<PodResource> podOperationList = doGetLog(); for (PodResource podOperation : podOperationList) { stringBuilder.append(podOperation.getLog(isPretty)); } return stringBuilder.toString(); } private List<PodResource> doGetLog() { Job job = requireFromServer(); return PodOperationUtil.getPodOperationsForController(context, podControllerOperationContext, job.getMetadata().getUid(), getJobPodLabels(job)); } /** * Returns an unclosed Reader. It's the caller responsibility to close it. * * @return Reader */ @Override public Reader getLogReader() { return PodOperationUtil.getLogReader(doGetLog()); } /** * Returns an unclosed InputStream. It's the caller responsibility to close it. * * @return Reader */ @Override public InputStream getLogInputStream() { return PodOperationUtil.getLogInputStream(doGetLog()); } @Override public LogWatch watchLog() { return watchLog(null); } @Override public LogWatch watchLog(OutputStream out) { return PodOperationUtil.watchLog(doGetLog(), out); } @Override public Loggable withLogWaitTimeout(Integer logWaitTimeout) { return withReadyWaitTimeout(logWaitTimeout); } @Override public Loggable withReadyWaitTimeout(Integer timeout) { return new JobOperationsImpl(podControllerOperationContext.withReadyWaitTimeout(timeout), context); } @Override protected Job modifyItemForReplaceOrPatch(Supplier<Job> current, Job job) { Job jobFromServer = current.get(); if (job.getSpec().getSelector() == null) { job.getSpec().setSelector(jobFromServer.getSpec().getSelector()); } if (job.getSpec().getTemplate().getMetadata() != null) { job.getSpec().getTemplate().getMetadata().setLabels(jobFromServer.getSpec().getTemplate().getMetadata().getLabels()); } else { job.getSpec().getTemplate().setMetadata(jobFromServer.getSpec().getTemplate().getMetadata()); } return job; } static Map<String, String> getJobPodLabels(Job job) { Map<String, String> labels = new HashMap<>(); if (job != null && job.getMetadata() != null && job.getMetadata().getUid() != null) { labels.put("controller-uid", job.getMetadata().getUid()); } return labels; } @Override public Loggable inContainer(String id) { return new JobOperationsImpl(podControllerOperationContext.withContainerId(id), context); } @Override public TimeTailPrettyLoggable limitBytes(int limitBytes) { return new JobOperationsImpl(podControllerOperationContext.withLimitBytes(limitBytes), context); } @Override public TimeTailPrettyLoggable terminated() { return new JobOperationsImpl(podControllerOperationContext.withTerminatedStatus(true), context); } @Override public Loggable withPrettyOutput() { return new JobOperationsImpl(podControllerOperationContext.withPrettyOutput(true), context); } @Override public PrettyLoggable tailingLines(int lines) { return new JobOperationsImpl(podControllerOperationContext.withTailingLines(lines), context); } @Override public TailPrettyLoggable sinceTime(String timestamp) { return new JobOperationsImpl(podControllerOperationContext.withSinceTimestamp(timestamp), context); } @Override public TailPrettyLoggable sinceSeconds(int seconds) { return new JobOperationsImpl(podControllerOperationContext.withSinceSeconds(seconds), context); } @Override public BytesLimitTerminateTimeTailPrettyLoggable usingTimestamps() { return new JobOperationsImpl(podControllerOperationContext.withTimestamps(true), context); } }
final AtomicReference<Job> atomicJob = new AtomicReference<>(); waitUntilCondition(job -> { atomicJob.set(job); Integer activeJobs = job.getStatus().getActive(); if (activeJobs == null) { activeJobs = 0; } if (Objects.equals(job.getSpec().getParallelism(), activeJobs)) { return true; } LOG.debug("Only {}/{} pods scheduled for Job: {} in namespace: {} so waiting...", job.getStatus().getActive(), job.getSpec().getParallelism(), job.getMetadata().getName(), namespace); return false; }, context.getTimeout(), context.getTimeoutUnit());
1,468
182
1,650
<methods>public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext, Class<Job>, Class<JobList>) ,public Job accept(Consumer<Job>) ,public Job edit(UnaryOperator<Job>) ,public transient Job edit(Visitor[]) ,public Job editStatus(UnaryOperator<Job>) ,public HasMetadataOperation<Job,JobList,ScalableResource<Job>> newInstance(io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public Job patch() ,public Job patch(io.fabric8.kubernetes.client.dsl.base.PatchContext) ,public Job patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, Job) ,public Job patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, java.lang.String) ,public Job patchStatus() ,public Job patchStatus(Job) ,public Job replace() ,public Job replaceStatus() ,public Job scale(int) ,public Job scale(int, boolean) ,public Scale scale(Scale) ,public Job update() ,public Job updateStatus() <variables>public static final long DEFAULT_GRACE_PERIOD_IN_SECONDS,public static final io.fabric8.kubernetes.api.model.DeletionPropagation DEFAULT_PROPAGATION_POLICY,private static final Logger LOGGER,private static final java.lang.String PATCH_OPERATION,private static final java.lang.String REPLACE_OPERATION,private static final java.lang.String UPDATE_OPERATION
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ReplicationControllerOperationsImpl.java
ReplicationControllerOperationsImpl
getReplicationControllerPodLabels
class ReplicationControllerOperationsImpl extends RollableScalableResourceOperation<ReplicationController, ReplicationControllerList, RollableScalableResource<ReplicationController>> implements TimeoutImageEditReplacePatchable<ReplicationController> { public ReplicationControllerOperationsImpl(Client client) { this(new PodOperationContext(), HasMetadataOperationsImpl.defaultContext(client)); } public ReplicationControllerOperationsImpl(PodOperationContext context, OperationContext superContext) { super(context, superContext.withPlural("replicationcontrollers"), ReplicationController.class, ReplicationControllerList.class); } @Override public ReplicationControllerOperationsImpl newInstance(OperationContext context) { return new ReplicationControllerOperationsImpl(rollingOperationContext, context); } @Override public ReplicationControllerOperationsImpl newInstance(PodOperationContext context, OperationContext superContext) { return new ReplicationControllerOperationsImpl(context, superContext); } @Override public RollingUpdater<ReplicationController, ReplicationControllerList> getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit) { return new ReplicationControllerRollingUpdater(context.getClient(), namespace, rollingTimeUnit.toMillis(rollingTimeout), getRequestConfig().getLoggingInterval()); } @Override public Status rollback(DeploymentRollback deploymentRollback) { throw new KubernetesClientException("rollback not supported in case of ReplicationControllers"); } @Override public String getLog(boolean isPretty) { return PodOperationUtil.getLog( new ReplicationControllerOperationsImpl(rollingOperationContext.withPrettyOutput(isPretty), context).doGetLog(), isPretty); } private List<PodResource> doGetLog() { ReplicationController rc = requireFromServer(); return PodOperationUtil.getPodOperationsForController(context, rollingOperationContext, rc.getMetadata().getUid(), getReplicationControllerPodLabels(rc)); } /** * Returns an unclosed Reader. It's the caller responsibility to close it. * * @return Reader */ @Override public Reader getLogReader() { return PodOperationUtil.getLogReader(doGetLog()); } /** * Returns an unclosed InputStream. It's the caller responsibility to close it. * * @return InputStream */ @Override public InputStream getLogInputStream() { return PodOperationUtil.getLogInputStream(doGetLog()); } @Override public LogWatch watchLog(OutputStream out) { return PodOperationUtil.watchLog(doGetLog(), out); } static Map<String, String> getReplicationControllerPodLabels(ReplicationController replicationController) {<FILL_FUNCTION_BODY>} @Override protected List<Container> getContainers(ReplicationController value) { return value.getSpec().getTemplate().getSpec().getContainers(); } @Override public TimeTailPrettyLoggable limitBytes(int limitBytes) { return new ReplicationControllerOperationsImpl(rollingOperationContext.withLimitBytes(limitBytes), context); } @Override public TimeTailPrettyLoggable terminated() { return new ReplicationControllerOperationsImpl(rollingOperationContext.withTerminatedStatus(true), context); } @Override public Loggable withPrettyOutput() { return new ReplicationControllerOperationsImpl(rollingOperationContext.withPrettyOutput(true), context); } @Override public PrettyLoggable tailingLines(int lines) { return new ReplicationControllerOperationsImpl(rollingOperationContext.withTailingLines(lines), context); } @Override public TailPrettyLoggable sinceTime(String timestamp) { return new ReplicationControllerOperationsImpl(rollingOperationContext.withSinceTimestamp(timestamp), context); } @Override public TailPrettyLoggable sinceSeconds(int seconds) { return new ReplicationControllerOperationsImpl(rollingOperationContext.withSinceSeconds(seconds), context); } @Override public BytesLimitTerminateTimeTailPrettyLoggable usingTimestamps() { return new ReplicationControllerOperationsImpl(rollingOperationContext.withTimestamps(true), context); } }
Map<String, String> labels = new HashMap<>(); if (replicationController != null && replicationController.getSpec() != null && replicationController.getSpec().getSelector() != null) { labels.putAll(replicationController.getSpec().getSelector()); } return labels;
1,120
80
1,200
<methods>public ReplicationController edit(UnaryOperator<ReplicationController>) ,public java.lang.String getLog() ,public io.fabric8.kubernetes.client.dsl.Loggable inContainer(java.lang.String) ,public abstract RollableScalableResourceOperation<ReplicationController,ReplicationControllerList,RollableScalableResource<ReplicationController>> newInstance(io.fabric8.kubernetes.client.dsl.internal.PodOperationContext, io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public ReplicationController pause() ,public ReplicationController restart() ,public ReplicationController resume() ,public TimeoutImageEditReplacePatchable<ReplicationController> rolling() ,public ReplicationController undo() ,public ReplicationController updateImage(java.lang.String) ,public ReplicationController updateImage(Map<java.lang.String,java.lang.String>) ,public io.fabric8.kubernetes.client.dsl.LogWatch watchLog() ,public io.fabric8.kubernetes.client.dsl.Loggable withLogWaitTimeout(java.lang.Integer) ,public io.fabric8.kubernetes.client.dsl.Loggable withReadyWaitTimeout(java.lang.Integer) ,public RollableScalableResourceOperation<ReplicationController,ReplicationControllerList,RollableScalableResource<ReplicationController>> withTimeout(long, java.util.concurrent.TimeUnit) ,public RollableScalableResourceOperation<ReplicationController,ReplicationControllerList,RollableScalableResource<ReplicationController>> withTimeoutInMillis(long) <variables>protected final non-sealed io.fabric8.kubernetes.client.dsl.internal.PodOperationContext rollingOperationContext
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ReplicationControllerRollingUpdater.java
ReplicationControllerRollingUpdater
createClone
class ReplicationControllerRollingUpdater extends RollingUpdater<ReplicationController, ReplicationControllerList> { ReplicationControllerRollingUpdater(Client client, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { super(client, namespace, rollingTimeoutMillis, loggingIntervalMillis); } @Override protected ReplicationController createClone(ReplicationController obj, String newName, String newDeploymentHash) {<FILL_FUNCTION_BODY>} @Override protected FilterWatchListDeletable<Pod, PodList, PodResource> selectedPodLister(ReplicationController obj) { return pods().inNamespace(namespace).withLabels(obj.getSpec().getSelector()); } @Override protected ReplicationController updateDeploymentKey(String name, String hash) { ReplicationController old = resources().inNamespace(namespace).withName(name).get(); ReplicationController updated = new ReplicationControllerBuilder(old).editSpec() .addToSelector(DEPLOYMENT_KEY, hash) .editTemplate().editMetadata().addToLabels(DEPLOYMENT_KEY, hash).endMetadata().endTemplate() .endSpec() .build(); return resources().inNamespace(namespace).withName(name).replace(updated); } @Override protected ReplicationController removeDeploymentKey(String name) { ReplicationController old = resources().inNamespace(namespace).withName(name).get(); ReplicationController updated = new ReplicationControllerBuilder(old).editSpec() .removeFromSelector(DEPLOYMENT_KEY) .editTemplate().editMetadata().removeFromLabels(DEPLOYMENT_KEY).endMetadata().endTemplate() .endSpec() .build(); return resources().inNamespace(namespace).withName(name).replace(updated); } @Override protected int getReplicas(ReplicationController obj) { return obj.getSpec().getReplicas(); } @Override protected ReplicationController setReplicas(ReplicationController obj, int replicas) { return new ReplicationControllerBuilder(obj).editSpec().withReplicas(replicas).endSpec().build(); } @Override protected MixedOperation<ReplicationController, ReplicationControllerList, RollableScalableResource<ReplicationController>> resources() { return new ReplicationControllerOperationsImpl(this.client); } }
return new ReplicationControllerBuilder(obj) .editMetadata() .withResourceVersion(null) .withName(newName) .endMetadata() .editSpec() .withReplicas(0).addToSelector(DEPLOYMENT_KEY, newDeploymentHash) .editTemplate().editMetadata().addToLabels(DEPLOYMENT_KEY, newDeploymentHash).endMetadata().endTemplate() .endSpec() .build();
608
121
729
<methods>public static T pause(RollableScalableResourceOperation<T,?,?>) ,public static Map<java.lang.String,java.lang.Object> requestPayLoadForRolloutPause() ,public static Map<java.lang.String,java.lang.Object> requestPayLoadForRolloutRestart() ,public static Map<java.lang.String,java.lang.Object> requestPayLoadForRolloutResume() ,public static T restart(RollableScalableResourceOperation<T,?,?>) ,public static T resume(RollableScalableResourceOperation<T,?,?>) ,public ReplicationController rollUpdate(ReplicationController, ReplicationController) <variables>private static final java.lang.Long DEFAULT_SERVER_GC_WAIT_TIMEOUT,public static final java.lang.String DEPLOYMENT_KEY,private static final transient Logger LOG,protected final non-sealed io.fabric8.kubernetes.client.Client client,private final non-sealed long loggingIntervalMillis,protected final non-sealed java.lang.String namespace,private final non-sealed long rollingTimeoutMillis
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ServiceAccountOperationsImpl.java
ServiceAccountOperationsImpl
handleTokenRequest
class ServiceAccountOperationsImpl extends HasMetadataOperation<ServiceAccount, ServiceAccountList, ServiceAccountResource> implements ServiceAccountResource { public ServiceAccountOperationsImpl(Client client) { this(HasMetadataOperationsImpl.defaultContext(client)); } private ServiceAccountOperationsImpl(OperationContext context) { super(context.withPlural("serviceaccounts"), ServiceAccount.class, ServiceAccountList.class); } @Override public ServiceAccountOperationsImpl newInstance(OperationContext context) { return new ServiceAccountOperationsImpl(context); } @Override public TokenRequest tokenRequest(TokenRequest tokenRequest) { return handleTokenRequest(tokenRequest); } private TokenRequest handleTokenRequest(TokenRequest tokenRequest) {<FILL_FUNCTION_BODY>} }
try { URL requestUrl = new URL(URLUtils.join(getResourceUrl().toString(), "token")); HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() .post(JSON, getKubernetesSerialization().asJson(tokenRequest)).url(requestUrl); return handleResponse(requestBuilder, TokenRequest.class); } catch (IOException exception) { throw KubernetesClientException.launderThrowable(forOperationType("token request"), exception); }
204
123
327
<methods>public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext, Class<ServiceAccount>, Class<ServiceAccountList>) ,public ServiceAccount accept(Consumer<ServiceAccount>) ,public ServiceAccount edit(UnaryOperator<ServiceAccount>) ,public transient ServiceAccount edit(Visitor[]) ,public ServiceAccount editStatus(UnaryOperator<ServiceAccount>) ,public HasMetadataOperation<ServiceAccount,ServiceAccountList,io.fabric8.kubernetes.client.dsl.ServiceAccountResource> newInstance(io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public ServiceAccount patch() ,public ServiceAccount patch(io.fabric8.kubernetes.client.dsl.base.PatchContext) ,public ServiceAccount patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, ServiceAccount) ,public ServiceAccount patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, java.lang.String) ,public ServiceAccount patchStatus() ,public ServiceAccount patchStatus(ServiceAccount) ,public ServiceAccount replace() ,public ServiceAccount replaceStatus() ,public ServiceAccount scale(int) ,public ServiceAccount scale(int, boolean) ,public Scale scale(Scale) ,public ServiceAccount update() ,public ServiceAccount updateStatus() <variables>public static final long DEFAULT_GRACE_PERIOD_IN_SECONDS,public static final io.fabric8.kubernetes.api.model.DeletionPropagation DEFAULT_PROPAGATION_POLICY,private static final Logger LOGGER,private static final java.lang.String PATCH_OPERATION,private static final java.lang.String REPLACE_OPERATION,private static final java.lang.String UPDATE_OPERATION
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ServiceOperationsImpl.java
ServiceOperationsImpl
getUrlHelper
class ServiceOperationsImpl extends HasMetadataOperation<Service, ServiceList, ServiceResource<Service>> implements ServiceResource<Service> { public static final String EXTERNAL_NAME = "ExternalName"; public ServiceOperationsImpl(Client client) { this(HasMetadataOperationsImpl.defaultContext(client)); } private ServiceOperationsImpl(OperationContext context) { super(context.withPlural("services"), Service.class, ServiceList.class); } @Override public ServiceOperationsImpl newInstance(OperationContext context) { return new ServiceOperationsImpl(context); } @Override public Service waitUntilReady(long amount, TimeUnit timeUnit) { long started = System.nanoTime(); super.waitUntilReady(amount, timeUnit); long alreadySpent = System.nanoTime() - started; // if awaiting existence took very long, let's give at least 10 seconds to awaiting readiness long remaining = Math.max(10_000, timeUnit.toNanos(amount) - alreadySpent); Resource<Endpoints> endpointsOperation = this.context.getClient().resources(Endpoints.class, EndpointsList.class) .inNamespace(this.context.getNamespace()).withName(this.context.getName()); endpointsOperation.waitUntilReady(remaining, TimeUnit.MILLISECONDS); return get(); } @Override public String getURL(String portName) { String clusterIP = getItemOrRequireFromServer().getSpec().getClusterIP(); if ("None".equals(clusterIP)) { throw new IllegalStateException("Service: " + getItemOrRequireFromServer().getMetadata().getName() + " in namespace " + namespace + " is head-less. Search for endpoints instead"); } return getUrlHelper(portName); } private String getUrlHelper(String portName) {<FILL_FUNCTION_BODY>} private static List<ServiceToURLProvider> getServiceToURLProviders(ClassLoader loader) { Iterator<ServiceToURLProvider> iterator = ServiceLoader.load(ServiceToURLProvider.class, loader).iterator(); List<ServiceToURLProvider> servicesList = new ArrayList<>(); while (iterator.hasNext()) { servicesList.add(iterator.next()); } return servicesList; } private Pod matchingPod() { Service item = requireFromServer(); Map<String, String> labels = item.getSpec().getSelector(); PodList list = new PodOperationsImpl(context.getClient()).inNamespace(item.getMetadata().getNamespace()).withLabels(labels) .list(); return list.getItems().stream().findFirst() .orElseThrow(() -> new IllegalStateException("Could not find matching pod for service:" + item + ".")); } @Override public PortForward portForward(int port, ReadableByteChannel in, WritableByteChannel out) { Pod m = matchingPod(); return new PodOperationsImpl(context.getClient()) .inNamespace(m.getMetadata().getNamespace()) .withName(m.getMetadata().getName()) .portForward(port, in, out); } @Override public LocalPortForward portForward(int port, int localPort) { Pod m = matchingPod(); return new PodOperationsImpl(context.getClient()) .inNamespace(m.getMetadata().getNamespace()) .withName(m.getMetadata().getName()) .portForward(port, localPort); } @Override public LocalPortForward portForward(int port, InetAddress localInetAddress, int localPort) { Pod m = matchingPod(); return new PodOperationsImpl(context.getClient()) .inNamespace(m.getMetadata().getNamespace()) .withName(m.getMetadata().getName()) .portForward(port, localInetAddress, localPort); } @Override public LocalPortForward portForward(int port) { Pod m = matchingPod(); return new PodOperationsImpl(context.getClient()) .inNamespace(m.getMetadata().getNamespace()) .withName(m.getMetadata().getName()) .portForward(port); } public class ServiceToUrlSortComparator implements Comparator<ServiceToURLProvider> { @Override public int compare(ServiceToURLProvider first, ServiceToURLProvider second) { return first.getPriority() - second.getPriority(); } } @Override protected Service modifyItemForReplaceOrPatch(Supplier<Service> currentSupplier, Service item) { if (!isExternalNameService(item)) { Service old = currentSupplier.get(); return new ServiceBuilder(item) .editSpec() .withClusterIP(old.getSpec().getClusterIP()) .endSpec() .build(); } return item; } private boolean isExternalNameService(Service item) { if (item.getSpec() != null && item.getSpec().getType() != null) { return item.getSpec().getType().equals(EXTERNAL_NAME); } return false; } }
List<ServiceToURLProvider> servicesList = getServiceToURLProviders(Thread.currentThread().getContextClassLoader()); if (servicesList.isEmpty()) { servicesList = getServiceToURLProviders(getClass().getClassLoader()); } // Sort all loaded implementations according to priority Collections.sort(servicesList, new ServiceToUrlSortComparator()); for (ServiceToURLProvider serviceToURLProvider : servicesList) { String url = serviceToURLProvider.getURL(getItemOrRequireFromServer(), portName, namespace, context.getClient().adapt(KubernetesClient.class)); if (url != null && URLUtils.isValidURL(url)) { return url; } } return null;
1,326
189
1,515
<methods>public void <init>(io.fabric8.kubernetes.client.dsl.internal.OperationContext, Class<Service>, Class<ServiceList>) ,public Service accept(Consumer<Service>) ,public Service edit(UnaryOperator<Service>) ,public transient Service edit(Visitor[]) ,public Service editStatus(UnaryOperator<Service>) ,public HasMetadataOperation<Service,ServiceList,ServiceResource<Service>> newInstance(io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public Service patch() ,public Service patch(io.fabric8.kubernetes.client.dsl.base.PatchContext) ,public Service patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, Service) ,public Service patch(io.fabric8.kubernetes.client.dsl.base.PatchContext, java.lang.String) ,public Service patchStatus() ,public Service patchStatus(Service) ,public Service replace() ,public Service replaceStatus() ,public Service scale(int) ,public Service scale(int, boolean) ,public Scale scale(Scale) ,public Service update() ,public Service updateStatus() <variables>public static final long DEFAULT_GRACE_PERIOD_IN_SECONDS,public static final io.fabric8.kubernetes.api.model.DeletionPropagation DEFAULT_PROPAGATION_POLICY,private static final Logger LOGGER,private static final java.lang.String PATCH_OPERATION,private static final java.lang.String REPLACE_OPERATION,private static final java.lang.String UPDATE_OPERATION
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/LegacyRollableScalableResourceOperation.java
LegacyRollableScalableResourceOperation
scale
class LegacyRollableScalableResourceOperation<T extends HasMetadata, L extends KubernetesResourceList<T>, R extends Resource<T>> extends RollableScalableResourceOperation<T, L, R> { protected LegacyRollableScalableResourceOperation(PodOperationContext context, OperationContext superContext, Class<T> type, Class<L> listType) { super(context, superContext, type, listType); } @Override public Scale scale(Scale scaleParam) { return scale(scaleParam, this); } public static Scale scale(Scale scaleParam, HasMetadataOperation<?, ?, ?> operation) {<FILL_FUNCTION_BODY>} }
// handles the conversion back in forth between v1beta1.scale and v1.scale // the sticking point is mostly the conversion of the selector from a map to a single string GenericKubernetesResource scale = operation.handleScale( Optional.ofNullable(scaleParam) .map(s -> operation.getKubernetesSerialization().unmarshal(operation.getKubernetesSerialization().asYaml(s), GenericKubernetesResource.class)) .map(g -> { g.getAdditionalProperties().put("status", null); // could explicitly set the apiVersion, but that doesn't seem to be required return g; }).orElse(null), GenericKubernetesResource.class); return Optional.ofNullable(scale).map(s -> { Optional.ofNullable((Map) s.getAdditionalProperties().get("status")) .ifPresent(status -> Optional.ofNullable((Map<String, Object>) status.get("selector")) .ifPresent(selector -> status.put("selector", selector.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining(";"))))); return s; }).map(s -> operation.getKubernetesSerialization().unmarshal(operation.getKubernetesSerialization().asYaml(s), Scale.class)) .orElse(null);
178
357
535
<methods>public T edit(UnaryOperator<T>) ,public java.lang.String getLog() ,public io.fabric8.kubernetes.client.dsl.Loggable inContainer(java.lang.String) ,public abstract RollableScalableResourceOperation<T,L,R> newInstance(io.fabric8.kubernetes.client.dsl.internal.PodOperationContext, io.fabric8.kubernetes.client.dsl.internal.OperationContext) ,public T pause() ,public T restart() ,public T resume() ,public TimeoutImageEditReplacePatchable<T> rolling() ,public T undo() ,public T updateImage(java.lang.String) ,public T updateImage(Map<java.lang.String,java.lang.String>) ,public io.fabric8.kubernetes.client.dsl.LogWatch watchLog() ,public io.fabric8.kubernetes.client.dsl.Loggable withLogWaitTimeout(java.lang.Integer) ,public io.fabric8.kubernetes.client.dsl.Loggable withReadyWaitTimeout(java.lang.Integer) ,public RollableScalableResourceOperation<T,L,R> withTimeout(long, java.util.concurrent.TimeUnit) ,public RollableScalableResourceOperation<T,L,R> withTimeoutInMillis(long) <variables>protected final non-sealed io.fabric8.kubernetes.client.dsl.internal.PodOperationContext rollingOperationContext
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/ReplicaSetOperationsImpl.java
ReplicaSetOperationsImpl
rollback
class ReplicaSetOperationsImpl extends LegacyRollableScalableResourceOperation<ReplicaSet, ReplicaSetList, RollableScalableResource<ReplicaSet>> implements TimeoutImageEditReplacePatchable<ReplicaSet> { public ReplicaSetOperationsImpl(Client client) { this(new PodOperationContext(), HasMetadataOperationsImpl.defaultContext(client)); } ReplicaSetOperationsImpl(PodOperationContext context, OperationContext superContext) { super(context, superContext.withApiGroupName("extensions") .withApiGroupVersion("v1beta1") .withPlural("replicasets"), ReplicaSet.class, ReplicaSetList.class); } @Override public ReplicaSetOperationsImpl newInstance(OperationContext context) { return new ReplicaSetOperationsImpl(rollingOperationContext, context); } @Override public ReplicaSetOperationsImpl newInstance(PodOperationContext context, OperationContext superContext) { return new ReplicaSetOperationsImpl(context, superContext); } @Override public RollingUpdater<ReplicaSet, ReplicaSetList> getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit) { return new ReplicaSetRollingUpdater(context.getClient(), getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), getRequestConfig().getLoggingInterval()); } @Override public Status rollback(DeploymentRollback deploymentRollback) {<FILL_FUNCTION_BODY>} @Override public String getLog(boolean isPretty) { StringBuilder stringBuilder = new StringBuilder(); List<PodResource> podOperationList = new ReplicaSetOperationsImpl(rollingOperationContext.withPrettyOutput(isPretty), context).doGetLog(); for (PodResource podOperation : podOperationList) { stringBuilder.append(podOperation.getLog(isPretty)); } return stringBuilder.toString(); } private List<PodResource> doGetLog() { ReplicaSet replicaSet = requireFromServer(); return PodOperationUtil.getPodOperationsForController(context, rollingOperationContext, replicaSet.getMetadata().getUid(), getReplicaSetSelectorLabels(replicaSet)); } /** * Returns an unclosed Reader. It's the caller responsibility to close it. * * @return Reader */ @Override public Reader getLogReader() { return PodOperationUtil.getLogReader(doGetLog()); } /** * Returns an unclosed InputStream. It's the caller responsibility to close it. * * @return InputStream */ @Override public InputStream getLogInputStream() { return PodOperationUtil.getLogInputStream(doGetLog()); } @Override public LogWatch watchLog(OutputStream out) { return PodOperationUtil.watchLog(doGetLog(), out); } static Map<String, String> getReplicaSetSelectorLabels(ReplicaSet replicaSet) { Map<String, String> labels = new HashMap<>(); if (replicaSet != null && replicaSet.getSpec() != null && replicaSet.getSpec().getSelector() != null) { labels.putAll(replicaSet.getSpec().getSelector().getMatchLabels()); } return labels; } @Override protected List<Container> getContainers(ReplicaSet value) { return value.getSpec().getTemplate().getSpec().getContainers(); } @Override public TimeTailPrettyLoggable limitBytes(int limitBytes) { return new ReplicaSetOperationsImpl(rollingOperationContext.withLimitBytes(limitBytes), context); } @Override public TimeTailPrettyLoggable terminated() { return new ReplicaSetOperationsImpl(rollingOperationContext.withTerminatedStatus(true), context); } @Override public Loggable withPrettyOutput() { return new ReplicaSetOperationsImpl(rollingOperationContext.withPrettyOutput(true), context); } @Override public PrettyLoggable tailingLines(int lines) { return new ReplicaSetOperationsImpl(rollingOperationContext.withTailingLines(lines), context); } @Override public TailPrettyLoggable sinceTime(String timestamp) { return new ReplicaSetOperationsImpl(rollingOperationContext.withSinceTimestamp(timestamp), context); } @Override public TailPrettyLoggable sinceSeconds(int seconds) { return new ReplicaSetOperationsImpl(rollingOperationContext.withSinceSeconds(seconds), context); } @Override public BytesLimitTerminateTimeTailPrettyLoggable usingTimestamps() { return new ReplicaSetOperationsImpl(rollingOperationContext.withTimestamps(true), context); } }
throw new KubernetesClientException("rollback not supported in case of ReplicaSets");
1,249
25
1,274
<methods>public Scale scale(Scale) ,public static Scale scale(Scale, HasMetadataOperation<?,?,?>) <variables>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/ReplicaSetRollingUpdater.java
ReplicaSetRollingUpdater
createClone
class ReplicaSetRollingUpdater extends RollingUpdater<ReplicaSet, ReplicaSetList> { ReplicaSetRollingUpdater(Client client, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { super(client, namespace, rollingTimeoutMillis, loggingIntervalMillis); } @Override protected ReplicaSet createClone(ReplicaSet obj, String newName, String newDeploymentHash) {<FILL_FUNCTION_BODY>} @Override protected FilterWatchListDeletable<Pod, PodList, PodResource> selectedPodLister(ReplicaSet obj) { return selectedPodLister(obj.getSpec().getSelector()); } @Override protected ReplicaSet updateDeploymentKey(String name, String hash) { return resources().inNamespace(namespace).withName(name).edit(r -> new ReplicaSetBuilder(r) .editSpec() .editSelector().addToMatchLabels(DEPLOYMENT_KEY, hash).endSelector() .editTemplate().editMetadata().addToLabels(DEPLOYMENT_KEY, hash).endMetadata().endTemplate() .endSpec() .build()); } @Override protected ReplicaSet removeDeploymentKey(String name) { return resources().inNamespace(namespace).withName(name).edit(r -> new ReplicaSetBuilder(r) .editSpec() .editSelector().removeFromMatchLabels(DEPLOYMENT_KEY).endSelector() .editTemplate().editMetadata().removeFromLabels(DEPLOYMENT_KEY).endMetadata().endTemplate() .endSpec() .build()); } @Override protected int getReplicas(ReplicaSet obj) { return obj.getSpec().getReplicas(); } @Override protected ReplicaSet setReplicas(ReplicaSet obj, int replicas) { return new ReplicaSetBuilder(obj).editSpec().withReplicas(replicas).endSpec().build(); } @Override protected MixedOperation<ReplicaSet, ReplicaSetList, RollableScalableResource<ReplicaSet>> resources() { return new ReplicaSetOperationsImpl(client); } }
return new ReplicaSetBuilder(obj) .editMetadata() .withResourceVersion(null) .withName(newName) .endMetadata() .editSpec() .withReplicas(0) .editSelector().addToMatchLabels(DEPLOYMENT_KEY, newDeploymentHash).endSelector() .editTemplate().editMetadata().addToLabels(DEPLOYMENT_KEY, newDeploymentHash).endMetadata().endTemplate() .endSpec() .build();
567
132
699
<methods>public static T pause(RollableScalableResourceOperation<T,?,?>) ,public static Map<java.lang.String,java.lang.Object> requestPayLoadForRolloutPause() ,public static Map<java.lang.String,java.lang.Object> requestPayLoadForRolloutRestart() ,public static Map<java.lang.String,java.lang.Object> requestPayLoadForRolloutResume() ,public static T restart(RollableScalableResourceOperation<T,?,?>) ,public static T resume(RollableScalableResourceOperation<T,?,?>) ,public ReplicaSet rollUpdate(ReplicaSet, ReplicaSet) <variables>private static final java.lang.Long DEFAULT_SERVER_GC_WAIT_TIMEOUT,public static final java.lang.String DEPLOYMENT_KEY,private static final transient Logger LOG,protected final non-sealed io.fabric8.kubernetes.client.Client client,private final non-sealed long loggingIntervalMillis,protected final non-sealed java.lang.String namespace,private final non-sealed long rollingTimeoutMillis
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUpload.java
PodUpload
upload
class PodUpload { private static final Logger LOG = LoggerFactory.getLogger(PodUpload.class); private static final String TAR_PATH_DELIMITER = "/"; private PodUpload() { } public static boolean upload(PodOperationsImpl operation, Path pathToUpload) throws IOException { final File toUpload = pathToUpload.toFile(); if (Utils.isNotNullOrEmpty(operation.getContext().getFile()) && toUpload.isFile()) { return uploadTar(operation, getDirectoryFromFile(operation.getContext().getFile()), tar -> addFileToTar(new File(operation.getContext().getFile()).getName(), toUpload, tar)); } else if (Utils.isNotNullOrEmpty(operation.getContext().getDir()) && toUpload.isDirectory()) { return uploadTar(operation, ensureEndsWithSlash(operation.getContext().getDir()), tar -> { for (File file : Objects.requireNonNull(toUpload.listFiles())) { addFileToTar(file.getName(), file, tar); } }); } throw new IllegalArgumentException("Provided arguments are not valid (file, directory, path)"); } private static String getDirectoryFromFile(String file) { String directoryTrimmedFromFilePath = file.substring(0, file.lastIndexOf('/')); return ensureEndsWithSlash(directoryTrimmedFromFilePath.isEmpty() ? "/" : directoryTrimmedFromFilePath); } private static boolean upload(PodOperationsImpl operation, String file, UploadProcessor<OutputStream> processor) throws IOException {<FILL_FUNCTION_BODY>} public static boolean uploadFileData(PodOperationsImpl operation, InputStream inputStream) throws IOException { return upload(operation, operation.getContext().getFile(), os -> InputStreamPumper.transferTo(inputStream, os::write)); } private static boolean uploadTar(PodOperationsImpl operation, String directory, UploadProcessor<TarArchiveOutputStream> processor) throws IOException { String fileName = String.format("%sfabric8-%s.tar", directory, generateId()); boolean uploaded = upload(operation, fileName, os -> { try (final TarArchiveOutputStream tar = new TarArchiveOutputStream(os)) { tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); tar.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX); processor.process(tar); } }); if (!uploaded) { // best effort delete of the failed upload try (ExecWatch rm = operation.writingOutput(new ByteArrayOutputStream()).exec("sh", "-c", String.format("rm %s", fileName))) { if (!Utils.waitUntilReady(rm.exitCode(), operation.getRequestConfig().getUploadRequestTimeout(), TimeUnit.MILLISECONDS) || !Integer.valueOf(0).equals(rm.exitCode().getNow(null))) { LOG.warn("delete of temporary tar file {} may not have completed", fileName); } } return false; } final String command = extractTarCommand(directory, fileName); try (ExecWatch execWatch = operation.redirectingInput().exec("sh", "-c", command)) { CompletableFuture<Integer> countExitFuture = execWatch.exitCode(); // TODO: this enforcement duplicates the timeout return Utils.waitUntilReady(countExitFuture, operation.getRequestConfig().getUploadRequestTimeout(), TimeUnit.MILLISECONDS) && Integer.valueOf(0).equals(countExitFuture.getNow(null)); } } static String extractTarCommand(String directory, String tar) { return String.format("mkdir -p %1$s; tar -C %1$s -xmf %2$s; e=$?; rm %2$s; exit $e", shellQuote(directory), tar); } private static void addFileToTar(String fileName, File file, TarArchiveOutputStream tar) throws IOException { tar.putArchiveEntry(new TarArchiveEntry(file, fileName)); if (file.isFile()) { Files.copy(file.toPath(), tar); tar.closeArchiveEntry(); } else if (file.isDirectory()) { tar.closeArchiveEntry(); for (File fileInDirectory : Objects.requireNonNull(file.listFiles())) { addFileToTar(fileName + TAR_PATH_DELIMITER + fileInDirectory.getName(), fileInDirectory, tar); } } } static String createExecCommandForUpload(String file) { return String.format( "mkdir -p %s && cat - > %s", shellQuote(getDirectoryFromFile(file)), shellQuote(file)); } private static String ensureEndsWithSlash(String path) { return path.endsWith("/") ? path : (path + "/"); } }
String command = createExecCommandForUpload(file); CompletableFuture<Integer> exitFuture; int uploadRequestTimeout = operation.getRequestConfig().getUploadRequestTimeout(); long uploadRequestTimeoutEnd = uploadRequestTimeout < 0 ? Long.MAX_VALUE : uploadRequestTimeout + System.currentTimeMillis(); long expected = 0; try (ExecWatch execWatch = operation.redirectingInput().terminateOnError().exec("sh", "-c", command)) { OutputStream out = execWatch.getInput(); CountingOutputStream countingStream = new CountingOutputStream(out); processor.process(countingStream); out.close(); // also flushes expected = countingStream.getBytesWritten(); exitFuture = execWatch.exitCode(); } // enforce the timeout after we've written everything - generally this won't fail, but // we may have already exceeded the timeout because of how long it took to write if (!Utils.waitUntilReady(exitFuture, Math.max(0, uploadRequestTimeoutEnd - System.currentTimeMillis()), TimeUnit.MILLISECONDS)) { LOG.debug("failed to complete upload before timeout expired"); return false; } final Integer exitCode = exitFuture.getNow(null); if (exitCode != null && exitCode != 0) { LOG.debug("upload process failed with exit code {}", exitCode); return false; } ByteArrayOutputStream byteCount = new ByteArrayOutputStream(); try (ExecWatch countWatch = operation.writingOutput(byteCount).exec("sh", "-c", String.format("wc -c < %s", shellQuote(file)))) { CompletableFuture<Integer> countExitFuture = countWatch.exitCode(); if (!Utils.waitUntilReady(countExitFuture, Math.max(0, uploadRequestTimeoutEnd - System.currentTimeMillis()), TimeUnit.MILLISECONDS) || !Integer.valueOf(0).equals(countExitFuture.getNow(null))) { LOG.debug("failed to validate the upload size, exit code {}", countExitFuture.getNow(null)); return false; } String remoteSize = new String(byteCount.toByteArray(), StandardCharsets.UTF_8); if (!String.valueOf(expected).equals(remoteSize.trim())) { LOG.debug("upload file size validation failed, expected {}, but was {}", expected, remoteSize); return false; } } return true;
1,264
614
1,878
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/impl/Adapters.java
Adapters
registerClient
class Adapters { private final Set<ClassLoader> classLoaders = Collections.newSetFromMap(new ConcurrentHashMap<>()); private final Map<Class<?>, ExtensionAdapter<?>> extensionAdapters = new ConcurrentHashMap<>(); private final Handlers handlers; public Adapters(Handlers handlers) { this.handlers = handlers; discoverServices(Adapters.class.getClassLoader()); discoverServices(Thread.currentThread().getContextClassLoader()); } public <T extends Client, C extends ClientAdapter<C>> void registerClient(Class<T> type, ClientAdapter<C> target) {<FILL_FUNCTION_BODY>} public <C extends Client> void register(ExtensionAdapter<C> adapter) { if (extensionAdapters.putIfAbsent(adapter.getExtensionType(), adapter) == null) { adapter.registerResources(this::registerResource); adapter.registerClients(this::registerClient); if (adapter instanceof InternalExtensionAdapter) { ((InternalExtensionAdapter) adapter).registerHandlers(handlers); } } } public <C extends Client> void unregister(ExtensionAdapter<C> adapter) { extensionAdapters.remove(adapter.getExtensionType()); // TODO: remove handlers and other state } public <C extends Client> ExtensionAdapter<C> get(Class<C> type) { discoverServices(type.getClassLoader()); return (ExtensionAdapter<C>) extensionAdapters.get(type); } private void discoverServices(ClassLoader classLoader) { if (classLoader != null && classLoaders.add(classLoader)) { for (ExtensionAdapter<?> adapter : ServiceLoader.load(ExtensionAdapter.class, classLoader)) { register(adapter); } } } public <T extends HasMetadata, R extends ExtensibleResourceAdapter<T>> void registerResource( Class<T> type, R target) { ResourceDefinitionContext definitionContest = ResourceDefinitionContext.fromResourceType(type); Class<? extends KubernetesResourceList> listType = KubernetesResourceUtil.inferListType(type); handlers.register(type, c -> new ResourcedHasMetadataOperation<>(HasMetadataOperationsImpl.defaultContext(c), definitionContest, type, listType, target)); } }
if (!type.isAssignableFrom(target.getClass())) { throw new IllegalArgumentException("The adapter should implement the type"); } if (target.getClient() != null) { throw new IllegalArgumentException("The client adapter should already be initialized"); } ExtensionAdapter<C> adapter = new ExtensionAdapter<C>() { @Override public Class getExtensionType() { return type; } @Override public C adapt(Client client) { C result = target.newInstance(); result.init(client); return result; } }; extensionAdapters.put(type, adapter); // some of the old extension adapters were inconsistent - and // specified the client class, rather than the dsl/interface // alternatively - we could just leave the type blank and scan the class hierarchy extensionAdapters.put(target.getClass(), adapter);
605
231
836
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/impl/Handlers.java
Handlers
get
class Handlers { private final Map<Class<?>, ResourceHandler<?, ?>> resourceHandlers = new ConcurrentHashMap<>(); private final Map<List<String>, ResourceDefinitionContext> genericDefinitions = new ConcurrentHashMap<>(); public <T extends HasMetadata, L extends KubernetesResourceList<T>, R extends Resource<T>> void register(Class<T> type, Function<Client, HasMetadataOperation<T, L, R>> operationConstructor) { if (resourceHandlers.put(type, new ResourceHandlerImpl(type, operationConstructor)) != null) { throw new AssertionError(String.format("%s already registered", type.getName())); } } public <T extends HasMetadata> void unregister(Class<T> type) { resourceHandlers.remove(type); } /** * Returns a {@link ResourceHandler} for the given item. The client is optional, if it is supplied, then the server can be * consulted for resource metadata if a generic item is passed in. * * @return the handler * @throws KubernetesClientException if a handler cannot be found */ public <T extends HasMetadata, V extends VisitableBuilder<T, V>> ResourceHandler<T, V> get(T meta, Client client) { Class<T> type = (Class<T>) meta.getClass(); if (type.equals(GenericKubernetesResource.class)) { GenericKubernetesResource gkr = (GenericKubernetesResource) meta; ResourceDefinitionContext rdc = getResourceDefinitionContext(gkr.getApiVersion(), gkr.getKind(), client); if (rdc != null) { return new ResourceHandlerImpl(GenericKubernetesResource.class, GenericKubernetesResourceList.class, rdc); } } ResourceHandler<T, V> result = get(type); if (result == null) { throw new KubernetesClientException("Could not find a registered handler for item: [" + meta + "]."); } return result; } public ResourceDefinitionContext getResourceDefinitionContext(String apiVersion, String kind, Client client) { // check if it's built-in Class<? extends KubernetesResource> clazz = client.adapt(BaseClient.class).getKubernetesSerialization() .getRegisteredKubernetesResource(apiVersion, kind); ResourceDefinitionContext rdc = null; if (clazz != null) { rdc = ResourceDefinitionContext.fromResourceType(clazz); } else { // if a client has been supplied, we can try to look this up from the server if (kind == null || apiVersion == null) { return null; } String api = ApiVersionUtil.trimGroupOrNull(apiVersion); if (api == null) { return null; } String version = ApiVersionUtil.trimVersion(apiVersion); // assume that resource metadata won't change for the lifetime of the client rdc = genericDefinitions.computeIfAbsent(Arrays.asList(kind, apiVersion), k -> { APIResourceList resourceList = client.getApiResources(apiVersion); if (resourceList == null) { return null; } return resourceList.getResources() .stream() .filter(r -> kind.equals(r.getKind())) .findFirst() .map(resource -> new ResourceDefinitionContext.Builder().withGroup(api) .withKind(kind) .withNamespaced(Boolean.TRUE.equals(resource.getNamespaced())) .withPlural(resource.getName()) .withVersion(version) .build()) .orElse(null); }); } return rdc; } private <T extends HasMetadata, V extends VisitableBuilder<T, V>> ResourceHandler<T, V> get(Class<T> type) {<FILL_FUNCTION_BODY>} public <T extends HasMetadata, L extends KubernetesResourceList<T>, R extends Resource<T>> HasMetadataOperation<T, L, R> getOperation( Class<T> type, Class<L> listType, Client client) { ResourceHandler<T, ?> resourceHandler = get(type); if (resourceHandler == null) { throw new IllegalStateException(); } return (HasMetadataOperation<T, L, R>) resourceHandler.operation(client, listType); } public <T extends HasMetadata> HasMetadataOperation<T, ?, Resource<T>> getNonListingOperation(Class<T> type, Client client) { return getOperation(type, KubernetesResourceUtil.inferListType(type), client); } public <T extends HasMetadata> NamespacedInOutCreateable<T, T> getNamespacedHasMetadataCreateOnlyOperation(Class<T> type, Client client) { HasMetadataOperation<T, ?, Resource<T>> operation = getNonListingOperation(type, client); return operation::inNamespace; } }
if (type.equals(GenericKubernetesResource.class)) { return null; } return (ResourceHandler<T, V>) resourceHandlers.computeIfAbsent(type, k -> new ResourceHandlerImpl<>(type, null));
1,269
64
1,333
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/impl/ResourceHandlerImpl.java
ResourceHandlerImpl
edit
class ResourceHandlerImpl<T extends HasMetadata, V extends VisitableBuilder<T, V>> implements ResourceHandler<T, V> { private final ResourceDefinitionContext context; private final Class<T> type; private final Class<V> builderClass; private final Class<? extends KubernetesResourceList<T>> defaultListClass; private final Function<Client, HasMetadataOperation<T, ?, Resource<T>>> operationConstructor; ResourceHandlerImpl(Class<T> type, Function<Client, HasMetadataOperation<T, ?, Resource<T>>> operationConstructor) { this.type = type; this.context = ResourceDefinitionContext.fromResourceType(type); this.builderClass = KubernetesResourceUtil.inferBuilderType(type); this.defaultListClass = (Class<? extends KubernetesResourceList<T>>) KubernetesResourceUtil.inferListType(type); this.operationConstructor = operationConstructor; } ResourceHandlerImpl(Class<T> type, Class<? extends KubernetesResourceList<T>> listClass, ResourceDefinitionContext context) { this.type = type; this.context = context; this.defaultListClass = listClass; this.builderClass = KubernetesResourceUtil.inferBuilderType(type); this.operationConstructor = null; } @Override public V edit(T item) {<FILL_FUNCTION_BODY>} @Override public <L extends KubernetesResourceList<T>> HasMetadataOperation<T, L, Resource<T>> operation(Client client, Class<L> listType) { if (operationConstructor != null) { if (listType != null && !listType.isAssignableFrom(defaultListClass)) { throw new IllegalArgumentException(String.format("Handler type %s with list %s not compatible with %s", type, defaultListClass.getName(), listType.getName())); } return (HasMetadataOperation<T, L, Resource<T>>) operationConstructor.apply(client); } return new HasMetadataOperationsImpl<>(client, context, type, (Class) Utils.getNonNullOrElse(listType, defaultListClass)); } @Override public boolean hasOperation() { return operationConstructor != null; } }
if (this.builderClass == null) { throw new KubernetesClientException(String.format("Cannot edit %s with visitors, no builder was found", type.getName())); } try { return this.builderClass.getDeclaredConstructor(item.getClass()).newInstance(item); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw KubernetesClientException.launderThrowable(e); }
569
127
696
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/impl/URLFromClusterIPImpl.java
URLFromClusterIPImpl
getURL
class URLFromClusterIPImpl implements ServiceToURLProvider { @Override public int getPriority() { return ServiceToUrlImplPriority.FIFTH.getValue(); } @Override public String getURL(Service service, String portName, String namespace, KubernetesClient client) {<FILL_FUNCTION_BODY>} }
ServicePort port = URLFromServiceUtil.getServicePortByName(service, portName); if (port != null && service.getSpec().getType().equals("ClusterIP")) { return port.getProtocol().toLowerCase() + "://" + service.getSpec().getClusterIP() + ":" + port.getPort(); } return null;
86
91
177
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/impl/URLFromEnvVarsImpl.java
URLFromEnvVarsImpl
getURL
class URLFromEnvVarsImpl implements ServiceToURLProvider { public static final Logger logger = LoggerFactory.getLogger(URLFromEnvVarsImpl.class); public static final String ANNOTATION_EXPOSE_URL = "fabric8.io/exposeUrl"; @Override public String getURL(Service service, String portName, String namespace, KubernetesClient client) {<FILL_FUNCTION_BODY>} @Override public int getPriority() { return ServiceToUrlImplPriority.THIRD.getValue(); } }
String serviceHost = URLFromServiceUtil.resolveHostFromEnvVarOrSystemProperty(service.getMetadata().getName()); String servicePort = URLFromServiceUtil.resolvePortFromEnvVarOrSystemProperty(service.getMetadata().getName(), ""); String serviceProtocol = URLFromServiceUtil .resolveProtocolFromEnvVarOrSystemProperty(service.getSpec().getPorts().iterator().next().getProtocol(), ""); if (!serviceHost.isEmpty() && !servicePort.isEmpty() && !serviceProtocol.isEmpty()) { return serviceProtocol + "://" + serviceHost + ":" + servicePort; } else { String answer = getOrCreateAnnotations(service).get(ANNOTATION_EXPOSE_URL); if (answer != null && !answer.isEmpty()) { return answer; } } return null;
142
204
346
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/impl/URLFromIngressImpl.java
URLFromIngressImpl
getURL
class URLFromIngressImpl implements ServiceToURLProvider { @Override public String getURL(Service service, String portName, String namespace, KubernetesClient client) {<FILL_FUNCTION_BODY>} @Override public int getPriority() { return ServiceToUrlImplPriority.FIRST.getValue(); } }
ServicePort port = URLFromServiceUtil.getServicePortByName(service, portName); String serviceName = service.getMetadata().getName(); if (port == null) { throw new RuntimeException("Couldn't find port: " + portName + " for service " + service.getMetadata().getName()); } if (client.supports(io.fabric8.kubernetes.api.model.extensions.Ingress.class)) { io.fabric8.kubernetes.api.model.extensions.IngressList ingresses = client.extensions().ingresses().inNamespace(namespace) .list(); if (ingresses != null && !ingresses.getItems().isEmpty()) { return URLFromServiceUtil.getURLFromExtensionsV1beta1IngressList(ingresses.getItems(), namespace, serviceName, port); } } else if (client.supports(io.fabric8.kubernetes.api.model.networking.v1.Ingress.class)) { io.fabric8.kubernetes.api.model.networking.v1.IngressList ingresses = client.network().v1().ingresses() .inNamespace(namespace).list(); if (ingresses != null && !ingresses.getItems().isEmpty()) { return URLFromServiceUtil.getURLFromNetworkingV1IngressList(ingresses.getItems(), namespace, serviceName, port); } } return null;
86
353
439
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/impl/URLFromNodePortImpl.java
URLFromNodePortImpl
getURL
class URLFromNodePortImpl implements ServiceToURLProvider { public static final Logger logger = LoggerFactory.getLogger(URLFromNodePortImpl.class); public String getURL(Service service, String portName, String namespace, KubernetesClient client) {<FILL_FUNCTION_BODY>} private NodePortUrlComponents getUrlComponentsFromNodeList(NodeStatus nodeStatus, Integer nodePort) { if (nodeStatus != null) { List<NodeAddress> addresses = nodeStatus.getAddresses(); for (NodeAddress address : addresses) { String ip = address.getAddress(); if (!ip.isEmpty()) { return new NodePortUrlComponents(ip, nodePort); } } } return null; } private class NodePortUrlComponents { public String getClusterIP() { return clusterIP; } private String clusterIP; public Integer getPortNumber() { return portNumber; } private Integer portNumber; public NodePortUrlComponents(String clusterIP, Integer portNumber) { this.clusterIP = clusterIP; this.portNumber = portNumber; } } @Override public int getPriority() { return ServiceToUrlImplPriority.SECOND.getValue(); } }
ServicePort port = URLFromServiceUtil.getServicePortByName(service, portName); String serviceProto = port.getProtocol(); NodePortUrlComponents urlComponents = null; Integer nodePort = port.getNodePort(); if (nodePort != null) { try { NodeList nodeList = client.nodes().list(); if (nodeList != null && nodeList.getItems() != null) { for (Node item : nodeList.getItems()) { urlComponents = getUrlComponentsFromNodeList(item.getStatus(), nodePort); if (urlComponents != null) { break; } } } } catch (KubernetesClientException exception) { logger.warn("Could not find a node!", exception); } } return urlComponents != null ? (serviceProto + "://" + urlComponents.getClusterIP() + ":" + urlComponents.getPortNumber()).toLowerCase(Locale.ROOT) : null;
333
261
594
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/impl/V1CertificatesAPIGroupClient.java
V1CertificatesAPIGroupClient
certificateSigningRequests
class V1CertificatesAPIGroupClient extends ClientAdapter<V1CertificatesAPIGroupClient> implements V1CertificatesAPIGroupDSL { @Override public NonNamespaceOperation<CertificateSigningRequest, CertificateSigningRequestList, CertificateSigningRequestResource<CertificateSigningRequest>> certificateSigningRequests() {<FILL_FUNCTION_BODY>} @Override public V1CertificatesAPIGroupClient newInstance() { return new V1CertificatesAPIGroupClient(); } }
// we need the cast to satisfy java 8 return (NonNamespaceOperation<CertificateSigningRequest, CertificateSigningRequestList, CertificateSigningRequestResource<CertificateSigningRequest>>) resources( CertificateSigningRequest.class, CertificateSigningRequestList.class, CertificateSigningRequestResource.class);
132
82
214
<methods>public non-sealed void <init>() ,public A adapt(Class<A>) ,public void close() ,public APIGroup getApiGroup(java.lang.String) ,public APIGroupList getApiGroups() ,public APIResourceList getApiResources(java.lang.String) ,public java.lang.String getApiVersion() ,public io.fabric8.kubernetes.client.Client getClient() ,public io.fabric8.kubernetes.client.Config getConfiguration() ,public io.fabric8.kubernetes.client.http.HttpClient getHttpClient() ,public java.net.URL getMasterUrl() ,public java.lang.String getNamespace() ,public boolean hasApiGroup(java.lang.String, boolean) ,public io.fabric8.kubernetes.client.impl.V1CertificatesAPIGroupClient inAnyNamespace() ,public io.fabric8.kubernetes.client.impl.V1CertificatesAPIGroupClient inNamespace(java.lang.String) ,public void init(io.fabric8.kubernetes.client.Client) ,public java.lang.Boolean isAdaptable(Class<A>) ,public io.fabric8.kubernetes.client.Client newClient(io.fabric8.kubernetes.client.RequestConfig) ,public abstract io.fabric8.kubernetes.client.impl.V1CertificatesAPIGroupClient newInstance() ,public java.lang.String raw(java.lang.String, java.lang.String, java.lang.Object) ,public MixedOperation<T,L,R> resources(Class<T>, Class<L>, Class<R>) ,public RootPaths rootPaths() ,public boolean supports(Class<T>) ,public boolean supports(java.lang.String, java.lang.String) ,public boolean supportsApiPath(java.lang.String) <variables>private io.fabric8.kubernetes.client.Client client
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/impl/SharedInformerFactoryImpl.java
SharedInformerFactoryImpl
sharedIndexInformerFor
class SharedInformerFactoryImpl implements SharedInformerFactory { private static final Logger log = LoggerFactory.getLogger(SharedInformerFactoryImpl.class); private final List<SharedIndexInformer<?>> informers = new ArrayList<>(); private final ConcurrentLinkedQueue<SharedInformerEventListener> eventListeners = new ConcurrentLinkedQueue<>(); private String name; private String namespace; private final KubernetesClient client; public SharedInformerFactoryImpl(KubernetesClient client) { this.client = client; } @Override public SharedInformerFactory inNamespace(String namespace) { this.namespace = namespace; return this; } @Override public SharedInformerFactory withName(String name) { this.name = name; return this; } @Override public synchronized <T extends HasMetadata> SharedIndexInformer<T> sharedIndexInformerFor(Class<T> apiTypeClass, long resyncPeriodInMillis) {<FILL_FUNCTION_BODY>} @Override public synchronized <T> SharedIndexInformer<T> getExistingSharedIndexInformer(Class<T> apiTypeClass) { for (SharedIndexInformer<?> informer : this.informers) { if (informer.getApiTypeClass().equals(apiTypeClass)) { return (SharedIndexInformer<T>) informer; } } return null; } @Override public synchronized Future<Void> startAllRegisteredInformers() { List<CompletableFuture<Void>> startInformerTasks = new ArrayList<>(); if (!informers.isEmpty()) { for (SharedIndexInformer<?> informer : informers) { CompletableFuture<Void> future = informer.start().toCompletableFuture(); startInformerTasks.add(future); future.whenComplete((v, t) -> { if (t != null) { if (this.eventListeners.isEmpty()) { log.warn("Failed to start informer {}", informer, t); } else { this.eventListeners .forEach(listener -> listener.onException(informer, KubernetesClientException.launderThrowable(t))); } } }); } } return CompletableFuture.allOf(startInformerTasks.toArray(new CompletableFuture[] {})); } @Override public synchronized void stopAllRegisteredInformers() { informers.forEach(SharedIndexInformer::stop); } @Override public void addSharedInformerEventListener(SharedInformerEventListener event) { this.eventListeners.add(event); } }
MixedOperation<T, KubernetesResourceList<T>, Resource<T>> resources = client.resources(apiTypeClass); Informable<T> informable = null; if (namespace != null) { NonNamespaceOperation<T, KubernetesResourceList<T>, Resource<T>> nonNamespaceOp = resources.inNamespace(namespace); informable = nonNamespaceOp; if (name != null) { informable = nonNamespaceOp.withName(name); } } else if (name != null) { informable = resources.withName(name); } else { informable = resources.inAnyNamespace(); } SharedIndexInformer<T> informer = informable.runnableInformer(resyncPeriodInMillis); this.informers.add(informer); return informer;
703
217
920
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/impl/cache/ProcessorStore.java
ProcessorStore
update
class ProcessorStore<T extends HasMetadata> implements SyncableStore<T> { private CacheImpl<T> cache; private SharedProcessor<T> processor; private AtomicBoolean synced = new AtomicBoolean(); private List<String> deferredAdd = new ArrayList<>(); public ProcessorStore(CacheImpl<T> cache, SharedProcessor<T> processor) { this.cache = cache; this.processor = processor; } @Override public void add(T obj) { update(obj); } @Override public void update(List<T> items) { items.stream().map(this::updateInternal).filter(Objects::nonNull).forEach(n -> this.processor.distribute(n, false)); } private Notification<T> updateInternal(T obj) { T oldObj = this.cache.put(obj); Notification<T> notification = null; if (oldObj != null) { if (!Objects.equals(oldObj.getMetadata().getResourceVersion(), obj.getMetadata().getResourceVersion())) { notification = new ProcessorListener.UpdateNotification<>(oldObj, obj); } } else if (synced.get() || !cache.isFullState()) { notification = new ProcessorListener.AddNotification<>(obj); } else { deferredAdd.add(getKey(obj)); } return notification; } @Override public void update(T obj) {<FILL_FUNCTION_BODY>} @Override public void delete(T obj) { Object oldObj = this.cache.remove(obj); if (oldObj != null) { this.processor.distribute(new ProcessorListener.DeleteNotification<>(obj, false), false); } } @Override public List<T> list() { return cache.list(); } @Override public List<String> listKeys() { return cache.listKeys(); } @Override public T get(T object) { return cache.get(object); } @Override public T getByKey(String key) { return cache.getByKey(key); } @Override public void retainAll(Set<String> nextKeys) { if (synced.compareAndSet(false, true)) { deferredAdd.stream().map(cache::getByKey).filter(Objects::nonNull) .forEach(v -> this.processor.distribute(new ProcessorListener.AddNotification<>(v), false)); deferredAdd.clear(); } List<T> current = cache.list(); if (nextKeys.isEmpty() && current.isEmpty()) { this.processor.distribute(l -> l.getHandler().onNothing(), false); return; } current.forEach(v -> { String key = cache.getKey(v); if (!nextKeys.contains(key)) { cache.remove(v); this.processor.distribute(new ProcessorListener.DeleteNotification<>(v, true), false); } }); } @Override public String getKey(T obj) { return cache.getKey(obj); } @Override public void resync() { // lock to ensure the ordering wrt other events synchronized (cache.getLockObject()) { this.cache.list() .forEach(i -> this.processor.distribute(new ProcessorListener.UpdateNotification<>(i, i), true)); } } }
Notification<T> notification = updateInternal(obj); if (notification != null) { this.processor.distribute(notification, false); }
909
45
954
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/impl/cache/SharedProcessor.java
SharedProcessor
shouldResync
class SharedProcessor<T> { private static final Logger log = LoggerFactory.getLogger(SharedProcessor.class); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final List<ProcessorListener<T>> listeners = new ArrayList<>(); private final List<ProcessorListener<T>> syncingListeners = new ArrayList<>(); private final SerialExecutor executor; private final String informerDescription; public SharedProcessor() { this(Runnable::run, "informer"); } public SharedProcessor(Executor executor, String informerDescription) { // serialexecutors are by default unbounded, we expect this behavior here // because resync may flood the executor with events for large caches // if we ever need to limit the queue size, we have to revisit the // resync locking behavior this.executor = new SerialExecutor(executor); this.informerDescription = informerDescription; } /** * Adds the specific processorListener * * @param processorListener specific processor listener */ public void addListener(final ProcessorListener<T> processorListener) { lock.writeLock().lock(); try { this.listeners.add(processorListener); if (processorListener.isReSync()) { this.syncingListeners.add(processorListener); } } finally { lock.writeLock().unlock(); } } /** * Distribute the object amount listeners. * * @param obj specific obj * @param isSync whether in sync or not */ public void distribute(ProcessorListener.Notification<T> obj, boolean isSync) { distribute(l -> l.add(obj), isSync); } /** * Distribute the operation to the respective listeners */ public void distribute(Consumer<ProcessorListener<T>> operation, boolean isSync) { // obtain the list to call outside before submitting lock.readLock().lock(); List<ProcessorListener<T>> toCall; try { if (isSync) { toCall = new ArrayList<>(syncingListeners); } else { toCall = new ArrayList<>(listeners); } } finally { lock.readLock().unlock(); } try { executor.execute(() -> { for (ProcessorListener<T> listener : toCall) { try { operation.accept(listener); } catch (Exception ex) { log.error("{} failed invoking {} event handler: {}", informerDescription, listener.getHandler(), ex.getMessage(), ex); } } }); } catch (RejectedExecutionException e) { // do nothing } } public boolean shouldResync() {<FILL_FUNCTION_BODY>} public void stop() { executor.shutdownNow(); lock.writeLock().lock(); try { syncingListeners.clear(); listeners.clear(); } finally { lock.writeLock().unlock(); } } /** * Adds a new listener. When running this will pause event distribution until * the new listener has received an initial set of add events */ public ProcessorListener<T> addProcessorListener(ResourceEventHandler<? super T> handler, long resyncPeriodMillis, Supplier<Collection<T>> initialItems) { lock.writeLock().lock(); try { ProcessorListener<T> listener = new ProcessorListener<>(handler, resyncPeriodMillis); for (T item : initialItems.get()) { listener.add(new ProcessorListener.AddNotification<>(item)); } addListener(listener); return listener; } finally { lock.writeLock().unlock(); } } }
lock.writeLock().lock(); boolean resyncNeeded = false; try { this.syncingListeners.clear(); ZonedDateTime now = ZonedDateTime.now(); for (ProcessorListener<T> listener : this.listeners) { if (listener.shouldResync(now)) { resyncNeeded = true; this.syncingListeners.add(listener); listener.determineNextResync(now); } } } finally { lock.writeLock().unlock(); } return resyncNeeded;
963
148
1,111
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/internal/CreateOrReplaceHelper.java
CreateOrReplaceHelper
createOrReplace
class CreateOrReplaceHelper<T extends HasMetadata> { public static final int CREATE_OR_REPLACE_RETRIES = 3; private final UnaryOperator<T> createTask; private final UnaryOperator<T> replaceTask; private final UnaryOperator<T> waitTask; private final UnaryOperator<T> reloadTask; private final KubernetesSerialization serialization; public CreateOrReplaceHelper(UnaryOperator<T> createTask, UnaryOperator<T> replaceTask, UnaryOperator<T> waitTask, UnaryOperator<T> reloadTask, KubernetesSerialization serialization) { this.createTask = createTask; this.replaceTask = replaceTask; this.waitTask = waitTask; this.reloadTask = reloadTask; this.serialization = serialization; } public T createOrReplace(T item) {<FILL_FUNCTION_BODY>} private T replace(T item, String resourceVersion) { KubernetesResourceUtil.setResourceVersion(item, resourceVersion); return replaceTask.apply(item); } private boolean shouldRetry(int responseCode) { return responseCode > 499; } }
String resourceVersion = KubernetesResourceUtil.getResourceVersion(item); final CompletableFuture<T> future = new CompletableFuture<>(); int nTries = 0; item = serialization.clone(item); while (!future.isDone() && nTries < CREATE_OR_REPLACE_RETRIES) { try { // Create KubernetesResourceUtil.setResourceVersion(item, null); return createTask.apply(item); } catch (KubernetesClientException exception) { if (shouldRetry(exception.getCode())) { T itemFromServer = reloadTask.apply(item); if (itemFromServer == null) { waitTask.apply(item); nTries++; continue; } } else if (exception.getCode() != HttpURLConnection.HTTP_CONFLICT) { throw exception; } future.complete(replace(item, resourceVersion)); } } return future.join();
310
256
566
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/internal/OptionalDependencyWrapper.java
OptionalDependencyWrapper
wrapRunWithOptionalDependency
class OptionalDependencyWrapper { private OptionalDependencyWrapper() { } /** * Runs the provided {@link Supplier} implementation and catches any {@link NoClassDefFoundError} * * @param supplier implementation to safely run * @param message to display for caught exceptions (e.g. "Base64InputStream class is provided by * commons-codec" * @param <R> type of supplier * @return run object */ public static <R> R wrapRunWithOptionalDependency(Supplier<R> supplier, String message) {<FILL_FUNCTION_BODY>} }
try { return supplier.get(); } catch (NoClassDefFoundError ex) { throw new KubernetesClientException(String.format( "%s, an optional dependency. To use this functionality you must explicitly add this dependency to the classpath.", message), ex); }
154
75
229
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/internal/PodOperationUtil.java
PodOperationUtil
waitUntilReadyOrTerminal
class PodOperationUtil { private static final Logger LOG = LoggerFactory.getLogger(PodOperationUtil.class); private PodOperationUtil() { } /** * Gets PodOperations for Pods specific to a controller * * @param podOperations {@link PodOperationsImpl} generic PodOperations class without any pod configured * @param controllerPodList List of pods based on a label that are related to a Controller * @param controllerUid UID of Controller * @return returns list of PodOperations with pods whose owner's UID is of the provided controller */ public static List<PodResource> getFilteredPodsForLogs(PodOperationsImpl podOperations, PodList controllerPodList, String controllerUid) { List<PodResource> pods = new ArrayList<>(); for (Pod pod : controllerPodList.getItems()) { OwnerReference ownerReference = KubernetesResourceUtil.getControllerUid(pod); if (ownerReference != null && ownerReference.getUid().equals(controllerUid)) { pods.add(podOperations.withName(pod.getMetadata().getName())); } } return pods; } public static PodOperationsImpl getGenericPodOperations(OperationContext context, PodOperationContext podOperationContext) { return new PodOperationsImpl( podOperationContext, context.withName(null).withApiGroupName(null).withApiGroupVersion("v1")); } public static List<PodResource> getPodOperationsForController(OperationContext context, PodOperationContext podOperationContext, String controllerUid, Map<String, String> selectorLabels) { return getPodOperationsForController( PodOperationUtil.getGenericPodOperations(context, podOperationContext), controllerUid, selectorLabels); } public static LogWatch watchLog(List<PodResource> podResources, OutputStream out) { return findFirstPodResource(podResources).map(it -> it.watchLog(out)).orElse(null); } public static Reader getLogReader(List<PodResource> podResources) { return findFirstPodResource(podResources).map(Loggable::getLogReader).orElse(null); } public static InputStream getLogInputStream(List<PodResource> podResources) { return findFirstPodResource(podResources).map(Loggable::getLogInputStream).orElse(null); } private static Optional<PodResource> findFirstPodResource(List<PodResource> podResources) { if (!podResources.isEmpty()) { if (podResources.size() > 1) { LOG.debug("Found {} pods, Using first one to get log", podResources.size()); } return Optional.ofNullable(podResources.get(0)); } return Optional.empty(); } public static String getLog(List<PodResource> podOperationList, Boolean isPretty) { StringBuilder stringBuilder = new StringBuilder(); for (PodResource podOperation : podOperationList) { stringBuilder.append(podOperation.getLog(isPretty)); } return stringBuilder.toString(); } public static List<PodResource> getPodOperationsForController(PodOperationsImpl podOperations, String controllerUid, Map<String, String> selectorLabels) { PodList controllerPodList = podOperations.withLabels(selectorLabels).list(); return PodOperationUtil.getFilteredPodsForLogs(podOperations, controllerPodList, controllerUid); } public static Pod waitUntilReadyOrTerminal(PodResource podOperation, int logWaitTimeoutMs) {<FILL_FUNCTION_BODY>} static boolean isReadyOrTerminal(Pod p) { // we'll treat missing as an exit condition - there's no expectation that we should wait for a pod that doesn't exist return p == null || Readiness.isPodReady(p) || Optional.ofNullable(p.getStatus()).map(PodStatus::getPhase) .filter(phase -> !Arrays.asList("Pending", "Unknown").contains(phase)).isPresent(); } }
AtomicReference<Pod> podRef = new AtomicReference<>(); try { // Wait for Pod to become ready or succeeded podOperation.waitUntilCondition(p -> { podRef.set(p); return isReadyOrTerminal(p); }, logWaitTimeoutMs, TimeUnit.MILLISECONDS); } catch (KubernetesClientTimeoutException timeout) { LOG.debug("Timed out waiting for Pod to become Ready: {}, will still proceed", timeout.getMessage()); } catch (Exception otherException) { LOG.warn("Error while waiting for Pod to become Ready", otherException); } return podRef.get();
1,035
169
1,204
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/internal/SerialExecutor.java
SerialExecutor
execute
class SerialExecutor implements Executor { final Queue<Runnable> tasks = new LinkedBlockingDeque<>(); final Executor executor; Runnable active; private volatile boolean shutdown; private Thread thread; private final Object threadLock = new Object(); public SerialExecutor(Executor executor) { this.executor = executor; } @Override public synchronized void execute(final Runnable r) {<FILL_FUNCTION_BODY>} protected synchronized void scheduleNext() { if ((active = tasks.poll()) != null) { executor.execute(active); } } /** * Shutdown the executor without executing any more tasks. * <p> * The the current task will be interrupting if it is not the thread that initiated the shutdown. */ public void shutdownNow() { this.shutdown = true; tasks.clear(); synchronized (threadLock) { if (thread != null && thread != Thread.currentThread()) { thread.interrupt(); } } } public boolean isShutdown() { return shutdown; } }
if (shutdown) { throw new RejectedExecutionException(); } tasks.offer(() -> { try { if (shutdown) { return; } synchronized (threadLock) { thread = Thread.currentThread(); } r.run(); } catch (Throwable t) { thread.getUncaughtExceptionHandler().uncaughtException(thread, t); } finally { synchronized (threadLock) { thread = null; } Thread.interrupted(); scheduleNext(); } }); if (active == null) { scheduleNext(); }
304
167
471
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/AttachExample.java
AttachExample
main
class AttachExample { public static void main(String[] args) throws IOException {<FILL_FUNCTION_BODY>} private static ExecWatch attach(KubernetesClient client, String namespace, String podName, CompletableFuture<Void> sessionFuture) { return client.pods().inNamespace(namespace).withName(podName) .redirectingInput() .writingOutput(System.out) .writingError(System.err) .withTTY() .usingListener(new ExecListener() { @Override public void onFailure(Throwable t, Response failureResponse) { sessionFuture.complete(null); } @Override public void onClose(int code, String reason) { sessionFuture.complete(null); } }) .attach(); } }
if (args.length < 1) { System.out.println("Usage: podName [namespace]"); return; } String podName = args[0]; String namespace = "default"; if (args.length > 1) { namespace = args[1]; } CompletableFuture<Void> sessionFuture = new CompletableFuture<>(); try ( KubernetesClient client = new KubernetesClientBuilder().build(); ExecWatch watch = attach(client, namespace, podName, sessionFuture)) { System.out.println("Type 'exit' to detach"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String input = reader.readLine(); if (input.equals("exit")) { return; } watch.getInput().write((input + "\n").getBytes(StandardCharsets.UTF_8)); watch.getInput().flush(); if (sessionFuture.isDone()) { System.out.println("Session closed"); return; } } }
210
279
489
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/BindingExample.java
BindingExample
main
class BindingExample { @SuppressWarnings("java:S106") public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
final String podName = "binding-example-" + generateId(); try (final KubernetesClient client = new KubernetesClientBuilder().build()) { final String namespace; if (client.getConfiguration().getNamespace() != null) { namespace = client.getConfiguration().getNamespace(); } else if (client.getNamespace() != null) { namespace = client.getNamespace(); } else { namespace = client.namespaces().list().getItems().stream().findFirst() .orElseThrow(() -> new IllegalStateException("No namespace available")).getMetadata().getName(); } client.pods().inNamespace(namespace).resource(new PodBuilder() .withMetadata(new ObjectMetaBuilder() .withName(podName) .build()) .withSpec(new PodSpecBuilder() .withSchedulerName("random-scheduler-name-which-does-not-exist") .addNewContainer() .withName(podName) .withImage("nginx:latest") .endContainer() .build()) .build()).create(); final Node firstNode = client.nodes().list().getItems().stream().findFirst() .orElseThrow(() -> new IllegalStateException("No nodes available")); client.bindings().inNamespace(namespace).resource(new BindingBuilder() .withNewMetadata().withName(podName).endMetadata() .withNewTarget() .withKind(firstNode.getKind()) .withApiVersion(firstNode.getApiVersion()) .withName(firstNode.getMetadata().getName()).endTarget() .build()).create(); System.out.printf("Successfully bound Pod %s to Node %s%n", podName, firstNode.getMetadata().getName()); }
49
444
493
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/CRDExample.java
CRDExample
main
class CRDExample { private static final Logger logger = LoggerFactory.getLogger(CRDExample.class); private static final boolean LOG_ROOT_PATHS = false; /** * Example of Cluster and Namespaced scoped K8S Custom Resources. * To test Cluster scoped resource use "--cluster" as first argument. * To test Namespaced resource provide namespace as first argument (namespace must exists in K8S). * * @param args Either "--cluster" or namespace name. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
boolean resourceNamespaced = true; String namespace = null; if (args.length > 0) { if ("--cluster".equals(args[0])) { resourceNamespaced = false; } else { namespace = args[0]; } } try (final KubernetesClient client = new KubernetesClientBuilder().build()) { if (resourceNamespaced) { if (namespace == null) { namespace = client.getNamespace(); } if (namespace == null) { System.err.println("No namespace specified and no default defined!"); return; } System.out.println("Using namespace: " + namespace); } else { System.out.println("Creating cluster scoped resource"); } if (LOG_ROOT_PATHS) { RootPaths rootPaths = client.rootPaths(); if (rootPaths != null) { List<String> paths = rootPaths.getPaths(); if (paths != null) { System.out.println("Supported API Paths:"); for (String path : paths) { System.out.println(" " + path); } System.out.println(); } } } CustomResourceDefinitionList crds = client.apiextensions().v1().customResourceDefinitions().list(); List<CustomResourceDefinition> crdsItems = crds.getItems(); System.out.println("Found " + crdsItems.size() + " CRD(s)"); CustomResourceDefinition dummyCRD = null; final String dummyCRDName = CustomResource.getCRDName(Dummy.class); for (CustomResourceDefinition crd : crdsItems) { ObjectMeta metadata = crd.getMetadata(); if (metadata != null) { String name = metadata.getName(); System.out.println(" " + name + " => " + metadata.getSelfLink()); if (dummyCRDName.equals(name)) { dummyCRD = crd; } } } if (dummyCRD != null) { System.out.println("Found CRD: " + dummyCRD.getMetadata().getSelfLink()); } else { dummyCRD = CustomResourceDefinitionContext.v1CRDFromCustomResourceType(Dummy.class) .editSpec() .editVersion(0) .withNewSchema() .withNewOpenAPIV3Schema() .withTitle("dummy") .withType("object") .addToRequired("spec") .addToProperties("spec", new JSONSchemaPropsBuilder() .withType("object") .addToProperties("foo", new JSONSchemaPropsBuilder().withType("string").build()) .addToProperties("bar", new JSONSchemaPropsBuilder().withType("string").build()) .build()) .endOpenAPIV3Schema() .endSchema() .endVersion() .endSpec() .build(); client.apiextensions().v1().customResourceDefinitions().resource(dummyCRD).create(); System.out.println("Created CRD " + dummyCRD.getMetadata().getName()); } // wait a beat for the endpoints to be ready Thread.sleep(5000); // lets create a client for the CRD NonNamespaceOperation<Dummy, DummyList, Resource<Dummy>> dummyClient = client.resources(Dummy.class, DummyList.class); if (resourceNamespaced) { dummyClient = ((MixedOperation<Dummy, DummyList, Resource<Dummy>>) dummyClient).inNamespace(namespace); } DummyList dummyList = dummyClient.list(); List<Dummy> items = dummyList.getItems(); System.out.println(" found " + items.size() + " dummies"); for (Dummy item : items) { System.out.println(" " + item); } Dummy dummy = new Dummy(); ObjectMeta metadata = new ObjectMeta(); metadata.setName("foo"); dummy.setMetadata(metadata); DummySpec dummySpec = new DummySpec(); Date now = new Date(); dummySpec.setBar("beer: " + now); dummySpec.setFoo("cheese: " + now); dummy.setSpec(dummySpec); Dummy created = dummyClient.resource(dummy).createOrReplace(); System.out.println("Upserted " + dummy); created.getSpec().setBar("otherBar"); dummyClient.resource(created).createOrReplace(); System.out.println("Watching for changes to Dummies"); Watch watch = dummyClient.withResourceVersion(created.getMetadata().getResourceVersion()).watch(new Watcher<Dummy>() { @Override public void eventReceived(Action action, Dummy resource) { System.out.println("==> " + action + " for " + resource); if (resource.getSpec() == null) { logger.error("No Spec for resource {}", resource); } } @Override public void onClose(WatcherException cause) { } }); System.in.read(); watch.close(); } catch (KubernetesClientException e) { logger.error(e.getMessage(), e); } catch (Exception e) { logger.error(e.getMessage(), e); }
159
1,407
1,566
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/CRDLoadExample.java
CRDLoadExample
main
class CRDLoadExample { private static final Logger logger = LoggerFactory.getLogger(CRDLoadExample.class); public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
try (final KubernetesClient client = new KubernetesClientBuilder().build()) { // List all Custom resources. logger.info("Listing all current Custom Resource Definitions :"); CustomResourceDefinitionList crdList = client.apiextensions().v1().customResourceDefinitions().list(); crdList.getItems().forEach(crd -> logger.info(crd.getMetadata().getName())); // Creating a custom resource from yaml CustomResourceDefinition aCustomResourceDefinition = client.apiextensions().v1().customResourceDefinitions() .load(CRDLoadExample.class.getResourceAsStream("/crd.yml")).item(); logger.info("Creating CRD..."); client.apiextensions().v1().customResourceDefinitions().resource(aCustomResourceDefinition).create(); logger.info("Updated Custom Resource Definitions: "); client.apiextensions().v1().customResourceDefinitions().list().getItems() .forEach(crd -> logger.info(crd.getMetadata().getName())); }
58
270
328
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ConfigMapExample.java
ConfigMapExample
main
class ConfigMapExample { private static final Logger logger = LoggerFactory.getLogger(ConfigMapExample.class); public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
Config config = new ConfigBuilder().build(); try (KubernetesClient client = new KubernetesClientBuilder().withConfig(config).build()) { String namespace = null; if (args.length > 0) { namespace = args[0]; } if (namespace == null) { namespace = client.getNamespace(); } if (namespace == null) { namespace = "default"; } String name = "cheese"; Resource<ConfigMap> configMapResource = client.configMaps().inNamespace(namespace) .resource(new ConfigMapBuilder().withNewMetadata().withName(name) .endMetadata().addToData("foo", "" + new Date()).addToData("bar", "beer") .build()); ConfigMap configMap = configMapResource.createOrReplace(); logger.info("Upserted ConfigMap at {} data {}", configMap.getMetadata().getSelfLink(), configMap.getData()); }
55
246
301
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/CreatePod.java
CreatePod
main
class CreatePod { private static final Logger logger = LoggerFactory.getLogger(CreatePod.class); public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
if (args.length == 0) { logger.warn("Usage: podJsonFileName <token> <namespace>"); return; } String fileName = args[0]; String namespace = null; if (args.length > 2) { namespace = args[2]; } File file = new File(fileName); if (!file.exists() || !file.isFile()) { logger.warn("File does not exist: {}", fileName); return; } ConfigBuilder builder = new ConfigBuilder(); if (args.length > 1) { builder.withOauthToken(args[1]); } Config config = builder.build(); try (final KubernetesClient client = new KubernetesClientBuilder().withConfig(config).build()) { if (namespace == null) { namespace = client.getNamespace(); } List<HasMetadata> resources = client.load(new FileInputStream(fileName)).items(); if (resources.isEmpty()) { logger.error("No resources loaded from file: {}", fileName); return; } HasMetadata resource = resources.get(0); if (resource instanceof Pod) { Pod pod = (Pod) resource; logger.info("Creating pod in namespace {}", namespace); NonNamespaceOperation<Pod, PodList, PodResource> pods = client.pods().inNamespace(namespace); Pod result = pods.resource(pod).create(); logger.info("Created pod {}", result.getMetadata().getName()); } else { logger.error("Loaded resource is not a Pod! {}", resource); } } catch (Exception e) { logger.error(e.getMessage(), e); }
55
432
487
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/CredentialsExample.java
CredentialsExample
main
class CredentialsExample { private static final Logger logger = LoggerFactory.getLogger(CredentialsExample.class); public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
final ConfigBuilder configBuilder = new ConfigBuilder(); if (args.length > 0) { configBuilder.withMasterUrl(args[0]); } Config config = configBuilder .withTrustCerts(true) .withUsername("developer") .withPassword("developer") .withNamespace("myproject") .build(); try (final KubernetesClient client = new KubernetesClientBuilder().withConfig(config).build()) { logger.info("Received pods {}", client.pods().list()); } catch (Exception e) { logger.error(e.getMessage(), e); Throwable[] suppressed = e.getSuppressed(); if (suppressed != null) { for (Throwable t : suppressed) { logger.error(t.getMessage(), t); } } }
57
219
276
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/CronJobExample.java
CronJobExample
main
class CronJobExample { private static final Logger logger = LoggerFactory.getLogger(CronJobExample.class); public static void main(String[] args) {<FILL_FUNCTION_BODY>} private static void log(String action, Object obj) { logger.info("{}: {}", action, obj); } private static void log(String action) { logger.info(action); } }
String master = "https://localhost:8443/"; if (args.length == 1) { master = args[0]; } log("Using master with url ", master); Config config = new ConfigBuilder().withMasterUrl(master).build(); try (final KubernetesClient client = new KubernetesClientBuilder().withConfig(config).build()) { final String namespace = client.getNamespace(); CronJob cronJob1 = new CronJobBuilder() .withApiVersion("batch/v1beta1") .withNewMetadata() .withName("hello") .withLabels(Collections.singletonMap("foo", "bar")) .endMetadata() .withNewSpec() .withSchedule("*/1 * * * *") .withNewJobTemplate() .withNewSpec() .withNewTemplate() .withNewSpec() .addNewContainer() .withName("hello") .withImage("busybox") .withArgs("/bin/sh", "-c", "date; echo Hello from Kubernetes") .endContainer() .withRestartPolicy("OnFailure") .endSpec() .endTemplate() .endSpec() .endJobTemplate() .endSpec() .build(); log("Creating cron job from object"); cronJob1 = client.batch().v1().cronjobs().inNamespace(namespace).resource(cronJob1).create(); log("Successfully created cronjob with name ", cronJob1.getMetadata().getName()); log("Watching over pod which would be created during cronjob execution..."); final CountDownLatch watchLatch = new CountDownLatch(1); try (Watch ignored = client.pods().inNamespace(namespace).withLabel("job-name").watch(new Watcher<Pod>() { @Override public void eventReceived(Action action, Pod aPod) { log(aPod.getMetadata().getName(), aPod.getStatus().getPhase()); if (aPod.getStatus().getPhase().equals("Succeeded")) { log("Logs -> ", client.pods().inNamespace(namespace).withName(aPod.getMetadata().getName()).getLog()); watchLatch.countDown(); } } @Override public void onClose(WatcherException e) { // Ignore } })) { watchLatch.await(2, TimeUnit.MINUTES); } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); log("Could not watch pod", interruptedException); } catch (KubernetesClientException kubernetesClientException) { log("Could not watch pod", kubernetesClientException); } } catch (KubernetesClientException exception) { log("An error occured while processing cronjobs:", exception.getMessage()); }
112
731
843
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/CustomResourceInformerExample.java
CustomResourceInformerExample
main
class CustomResourceInformerExample { private static final Logger logger = LoggerFactory.getLogger(CustomResourceInformerExample.class); public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
try (KubernetesClient client = new KubernetesClientBuilder().build()) { SharedInformerFactory sharedInformerFactory = client.informers(); SharedIndexInformer<Dummy> podInformer = sharedInformerFactory.sharedIndexInformerFor(Dummy.class, 60 * 1000L); logger.info("Informer factory initialized."); podInformer.addEventHandler( new ResourceEventHandler<Dummy>() { @Override public void onAdd(Dummy pod) { logger.info("{} dummy added", pod.getMetadata().getName()); } @Override public void onUpdate(Dummy oldPod, Dummy newPod) { logger.info("{} dummy updated", oldPod.getMetadata().getName()); } @Override public void onDelete(Dummy pod, boolean deletedFinalStateUnknown) { logger.info("{} dummy deleted", pod.getMetadata().getName()); } }); podInformer.stopped().whenComplete((v, t) -> { if (t != null) { logger.error("Exception occurred, caught: {}", t.getMessage()); } }); logger.info("Starting all registered informers"); sharedInformerFactory.startAllRegisteredInformers(); Executors.newSingleThreadExecutor().submit(() -> { Thread.currentThread().setName("HAS_SYNCED_THREAD"); try { for (;;) { logger.info("podInformer.hasSynced() : {}", podInformer.hasSynced()); Thread.sleep(10 * 1000L); } } catch (InterruptedException inEx) { Thread.currentThread().interrupt(); logger.warn("HAS_SYNCED_THREAD interrupted: {}", inEx.getMessage()); } }); final Dummy toCreate = new Dummy(); toCreate.getMetadata().setName("dummy"); if (client.getConfiguration().getNamespace() != null) { toCreate.getMetadata().setNamespace(client.getConfiguration().getNamespace()); } else if (client.getNamespace() != null) { toCreate.getMetadata().setNamespace(client.getNamespace()); } else { toCreate.getMetadata().setNamespace(client.namespaces().list().getItems().stream().findFirst() .map(HasMetadata::getMetadata).map(ObjectMeta::getNamespace).orElse("default")); } client.resources(Dummy.class).resource(toCreate).createOrReplace(); // Wait for some time now TimeUnit.MINUTES.sleep(5); podInformer.close(); } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); logger.warn("interrupted: {}", interruptedException.getMessage()); }
59
714
773
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/CustomResourceV1Example.java
CustomResourceV1Example
main
class CustomResourceV1Example { @SuppressWarnings("java:S106") public static void main(String... args) {<FILL_FUNCTION_BODY>} @Group("example.com") @Version("v1") public static final class Show extends CustomResource<ShowSpec, Void> implements Namespaced { @SuppressWarnings("unused") public Show() { super(); } public Show(String metaName, ShowSpec spec) { setMetadata(new ObjectMetaBuilder().withName(metaName).build()); setSpec(spec); } } public static final class ShowList extends DefaultKubernetesResourceList<Show> { } @SuppressWarnings("unused") public static final class ShowSpec implements Serializable { private static final long serialVersionUID = -1548881019086449848L; private String name; private Number score; public ShowSpec() { super(); } public ShowSpec(String name, int score) { this.name = name; this.score = score; } public String getName() { return name; } public Number getScore() { return score; } public void setName(String name) { this.name = name; } public void setScore(Number score) { this.score = score; } } }
try (KubernetesClient kc = new KubernetesClientBuilder().build()) { // @formatter:off final CustomResourceDefinition crd = CustomResourceDefinitionContext.v1CRDFromCustomResourceType(Show.class) .editSpec().editVersion(0) .withNewSchema().withNewOpenAPIV3Schema() .withTitle("Shows") .withType("object") .addToRequired("spec") .addToProperties("spec", new JSONSchemaPropsBuilder() .withType("object") .addToProperties("name", new JSONSchemaPropsBuilder().withType("string").build()) .addToProperties("score", new JSONSchemaPropsBuilder().withType("number").build()) .build()) .endOpenAPIV3Schema().endSchema() .endVersion().endSpec().build(); // @formatter:on kc.apiextensions().v1().customResourceDefinitions().resource(crd).createOrReplace(); System.out.println("Created custom shows.example.com Kubernetes API"); final NonNamespaceOperation<Show, ShowList, Resource<Show>> shows = kc.resources(Show.class, ShowList.class) .inNamespace("default"); shows.list(); shows.resource(new Show("breaking-bad", new ShowSpec("Breaking Bad", 10))).createOrReplace(); shows.resource(new Show("better-call-saul", new ShowSpec("Better call Saul", 8))).createOrReplace(); shows.resource(new Show("the-wire", new ShowSpec("The Wire", 10))).createOrReplace(); System.out.println("Added three shows"); shows.list().getItems() .forEach(s -> System.out.printf(" - %s%n", s.getSpec().name)); final Show theWire = shows.withName("the-wire").get(); System.out.printf("The Wire Score is: %s%n", theWire.getSpec().score); }
389
502
891
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/DeleteExamples.java
DeleteExamples
main
class DeleteExamples { private static final Logger logger = LoggerFactory.getLogger(DeleteExamples.class); private static final String NAMESPACE = "this-is-a-test"; public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
try (KubernetesClient client = new KubernetesClientBuilder().build()) { try { logger.info("Create namespace: {}", client.namespaces() .resource(new NamespaceBuilder().withNewMetadata().withName(NAMESPACE).endMetadata().build()) .create()); logger.info("Deleted namespace: {}", client.namespaces().withName(NAMESPACE).delete()); logger.info("Deleted testPod: {}", client.pods().inNamespace(NAMESPACE).withName("test-pod").delete()); logger.info("Deleted pod by label: {}", client.pods().withLabel("this", "works").delete()); } catch (KubernetesClientException e) { logger.error(e.getMessage(), e); } finally { client.namespaces().withName(NAMESPACE).delete(); } }
78
219
297
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/DeploymentExamples.java
DeploymentExamples
main
class DeploymentExamples { private static final Logger logger = LoggerFactory.getLogger(DeploymentExamples.class); private static final String NAMESPACE = "this-is-a-test"; public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
try (KubernetesClient client = new KubernetesClientBuilder().build()) { // Create a namespace for all our stuff Namespace ns = new NamespaceBuilder().withNewMetadata().withName(NAMESPACE).addToLabels("this", "rocks").endMetadata() .build(); logger.info("Created namespace: {}", client.namespaces().resource(ns).createOrReplace()); ServiceAccount fabric8 = new ServiceAccountBuilder().withNewMetadata().withName("fabric8").endMetadata().build(); client.serviceAccounts().inNamespace(NAMESPACE).resource(fabric8).createOrReplace(); try { Deployment deployment = new DeploymentBuilder() .withNewMetadata() .withName("nginx") .endMetadata() .withNewSpec() .withReplicas(1) .withNewTemplate() .withNewMetadata() .addToLabels("app", "nginx") .endMetadata() .withNewSpec() .addNewContainer() .withName("nginx") .withImage("nginx") .addNewPort() .withContainerPort(80) .endPort() .endContainer() .endSpec() .endTemplate() .withNewSelector() .addToMatchLabels("app", "nginx") .endSelector() .endSpec() .build(); deployment = client.apps().deployments().inNamespace(NAMESPACE).resource(deployment).create(); logger.info("Created deployment: {}", deployment); logger.info("Scaling up: {}", deployment.getMetadata().getName()); client.apps().deployments().inNamespace(NAMESPACE).withName("nginx").scale(2, true); logger.info("Created replica sets: {}", client.apps().replicaSets().inNamespace(NAMESPACE).list().getItems()); logger.info("Deleting: {}", deployment.getMetadata().getName()); client.resource(deployment).delete(); } finally { client.namespaces().withName(NAMESPACE).delete(); } logger.info("Done."); }
79
546
625
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/DynamicSharedIndexInformerExample.java
DynamicSharedIndexInformerExample
main
class DynamicSharedIndexInformerExample { private static final Logger logger = LoggerFactory.getLogger(DynamicSharedIndexInformerExample.class.getSimpleName()); public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
ResourceDefinitionContext context = new ResourceDefinitionContext.Builder() .withGroup("demo.fabric8.io") .withVersion("v1") .withPlural("dummies") .withKind("Dummy") .withNamespaced(true) .build(); try (KubernetesClient client = new KubernetesClientBuilder().build(); SharedIndexInformer<GenericKubernetesResource> informer = client.genericKubernetesResources(context).inAnyNamespace() .runnableInformer(60 * 1000L);) { informer.addEventHandler(new ResourceEventHandler<GenericKubernetesResource>() { @Override public void onAdd(GenericKubernetesResource genericKubernetesResource) { logger.info("ADD {}/{}", genericKubernetesResource.getMetadata().getNamespace(), genericKubernetesResource.getMetadata().getName()); } @Override public void onUpdate(GenericKubernetesResource genericKubernetesResource, GenericKubernetesResource t1) { logger.info("UPDATE {}/{}", genericKubernetesResource.getMetadata().getNamespace(), genericKubernetesResource.getMetadata().getName()); } @Override public void onDelete(GenericKubernetesResource genericKubernetesResource, boolean b) { logger.info("DELETE {}/{}", genericKubernetesResource.getMetadata().getNamespace(), genericKubernetesResource.getMetadata().getName()); } }); TimeUnit.MINUTES.sleep(10); } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); logger.error("interrupted: {}", interruptedException.getMessage()); }
66
430
496
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/EndpointsExample.java
EndpointsExample
main
class EndpointsExample { private static final Logger logger = LoggerFactory.getLogger(EndpointsExample.class); private static final String NAMESPACE = "endpoints-example"; public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
try (KubernetesClient client = new KubernetesClientBuilder().build()) { Namespace ns = new NamespaceBuilder().withNewMetadata().withName(NAMESPACE).addToLabels("this", "rocks").endMetadata() .build(); logger.info("Created namespace: {}", client.namespaces().resource(ns).createOrReplace()); try { logger.info("Namespace: {}", ns); Deployment deployment = client.apps().deployments().inNamespace(NAMESPACE) .load(EndpointsExample.class.getResourceAsStream("/endpoints-deployment.yml")).item(); logger.info("Deployment created"); client.apps().deployments().inNamespace(NAMESPACE).resource(deployment).create(); Service service = client.services().inNamespace(NAMESPACE) .load(EndpointsExample.class.getResourceAsStream("/endpoints-service.yml")).item(); logger.info("Service created"); client.services().inNamespace(NAMESPACE).resource(service).create(); Endpoints endpoints = new EndpointsBuilder() .withNewMetadata().withName("external-web").withNamespace(NAMESPACE).endMetadata() .withSubsets().addNewSubset().addNewAddress().withIp("10.10.50.53").endAddress() .addNewPort().withPort(80).withName("apache").endPort() .endSubset() .build(); logger.info("Endpoint created"); client.endpoints().inNamespace(NAMESPACE).resource(endpoints).create(); logger.info("Endpoint url"); endpoints = client.endpoints().inNamespace(NAMESPACE).withName("external-web").get(); logger.info("Endpoint Port {}", endpoints.getSubsets().get(0).getPorts().get(0).getName()); } catch (Exception e) { logger.error("Exception occurred: {}", e.getMessage(), e); } finally { client.namespaces().withName(NAMESPACE).delete(); } }
75
522
597
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecExample.java
ExecExample
newExecWatch
class ExecExample { public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: podName [namespace]"); return; } String podName = args[0]; String namespace = "default"; if (args.length > 1) { namespace = args[1]; } try ( KubernetesClient client = new KubernetesClientBuilder().build(); ExecWatch watch = newExecWatch(client, namespace, podName)) { watch.exitCode().join(); } } private static ExecWatch newExecWatch(KubernetesClient client, String namespace, String podName) {<FILL_FUNCTION_BODY>} private static class SimpleListener implements ExecListener { @Override public void onOpen() { System.out.println("The shell will remain open for 10 seconds."); } @Override public void onFailure(Throwable t, Response failureResponse) { System.err.println("shell barfed"); } @Override public void onClose(int code, String reason) { System.out.println("The shell will now close."); } } }
return client.pods().inNamespace(namespace).withName(podName) .writingOutput(System.out) .writingError(System.err) .withTTY() .usingListener(new SimpleListener()) .exec("sh", "-c", "echo 'Hello world!'");
312
76
388
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecExampleWithTerminalSize.java
ExecExampleWithTerminalSize
main
class ExecExampleWithTerminalSize { public static void main(String[] args) throws InterruptedException {<FILL_FUNCTION_BODY>} private static ExecWatch newExecWatch(KubernetesClient client, String namespace, String podName, String columns, String lines) { return client.pods().inNamespace(namespace).withName(podName) .writingOutput(System.out) .writingError(System.err) .withTTY() .usingListener(new SimpleListener()) .exec("env", "TERM=xterm", "COLUMNS=" + columns, "LINES=" + lines, "sh", "-c", "ls -la"); } private static class SimpleListener implements ExecListener { @Override public void onOpen() { System.out.println("The shell will remain open for 10 seconds."); } @Override public void onFailure(Throwable t, Response failureResponse) { System.err.println("shell barfed"); } @Override public void onClose(int code, String reason) { System.out.println("The shell will now close."); } } }
if (args.length < 1) { System.out.println("Usage: podName [namespace] [columns] [lines]\n" + "Use env variable COLUMNS & LINES to initialize terminal size."); return; } String podName = args[0]; String namespace = "default"; String columns = "80"; String lines = "24"; if (args.length > 1) { namespace = args[1]; } if (args.length > 2) { columns = args[2]; } if (args.length > 3) { lines = args[3]; } try ( KubernetesClient client = new KubernetesClientBuilder().build(); ExecWatch exec = newExecWatch(client, namespace, podName, columns, lines);) { exec.exitCode().join(); }
298
224
522
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecLoopExample.java
FutureChecker
run
class FutureChecker implements Runnable { private final String name; private final Future<?> future; private FutureChecker(String name, Future<?> future) { this.name = name; this.future = future; } @Override public void run() {<FILL_FUNCTION_BODY>} }
if (!future.isDone()) { System.out.println("Future:[" + name + "] is not done yet"); }
91
37
128
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecStdInExample.java
ExecStdInExample
main
class ExecStdInExample { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
String master = "https://localhost:8443/"; String podName = null; if (args.length == 2) { master = args[0]; podName = args[1]; } if (args.length == 1) { podName = args[0]; } Config config = new ConfigBuilder().withMasterUrl(master).build(); try ( KubernetesClient client = new KubernetesClientBuilder().withConfig(config).build(); ExecWatch watch = client.pods().withName(podName) .redirectingInput() .writingOutput(System.out) .terminateOnError() .exec("cat");) { // send hello OutputStream input = watch.getInput(); input.write("hello".getBytes()); input.flush(); // close is needed when we're reading from stdin to terminate watch.close(); // wait for the process to exit watch.exitCode().join(); } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); }
35
283
318
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecuteCommandOnPodExample.java
SimpleListener
onClose
class SimpleListener implements ExecListener { private CompletableFuture<String> data; private ByteArrayOutputStream baos; public SimpleListener(CompletableFuture<String> data, ByteArrayOutputStream baos) { this.data = data; this.baos = baos; } @Override public void onOpen() { System.out.println("Reading data... "); } @Override public void onFailure(Throwable t, Response failureResponse) { System.err.println(t.getMessage()); data.completeExceptionally(t); } @Override public void onClose(int code, String reason) {<FILL_FUNCTION_BODY>} }
System.out.println("Exit with: " + code + " and with reason: " + reason); data.complete(baos.toString());
180
38
218
<no_super_class>
fabric8io_kubernetes-client
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/GenericKubernetesResourceExample.java
GenericKubernetesResourceExample
main
class GenericKubernetesResourceExample { private static final Logger logger = LoggerFactory.getLogger(GenericKubernetesResourceExample.class); public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
final ConfigBuilder configBuilder = new ConfigBuilder(); configBuilder.withWatchReconnectInterval(500); configBuilder.withWatchReconnectLimit(5); try (KubernetesClient client = new KubernetesClientBuilder().withConfig(configBuilder.build()).build()) { String namespace = "default"; CustomResourceDefinition prometheousRuleCrd = client.apiextensions().v1beta1().customResourceDefinitions() .load(GenericKubernetesResourceExample.class.getResourceAsStream("/prometheous-rule-crd.yml")).item(); client.apiextensions().v1beta1().customResourceDefinitions().resource(prometheousRuleCrd).createOrReplace(); logger.info("Successfully created Prometheous custom resource definition"); // Creating Custom Resources Now: ResourceDefinitionContext crdContext = CustomResourceDefinitionContext.fromCrd(prometheousRuleCrd); client.load(GenericKubernetesResourceExample.class.getResourceAsStream("/prometheous-rule-cr.yml")) .inNamespace(namespace) .createOrReplace(); logger.info("Created Custom Resource successfully too"); // Listing all custom resources in given namespace: NonNamespaceOperation<GenericKubernetesResource, GenericKubernetesResourceList, Resource<GenericKubernetesResource>> resourcesInNamespace = client .genericKubernetesResources(crdContext).inNamespace(namespace); GenericKubernetesResourceList list = resourcesInNamespace.list(); List<GenericKubernetesResource> items = list.getItems(); logger.info("Custom Resources :- "); for (GenericKubernetesResource customResource : items) { ObjectMeta metadata = customResource.getMetadata(); final String name = metadata.getName(); logger.info(name); } // Watching custom resources now logger.info("Watching custom resources now"); final CountDownLatch closeLatch = new CountDownLatch(1); Watch watch = resourcesInNamespace.watch(new Watcher<GenericKubernetesResource>() { @Override public void eventReceived(Action action, GenericKubernetesResource resource) { logger.info("{}: {}", action, resource); } @Override public void onClose(WatcherException e) { logger.debug("Watcher onClose"); closeLatch.countDown(); if (e != null) { logger.error(e.getMessage(), e); } } }); closeLatch.await(10, TimeUnit.MINUTES); watch.close(); // Cleanup logger.info("Deleting custom resources..."); resourcesInNamespace.withName("prometheus-example-rules").delete(); client.apiextensions().v1beta1().customResourceDefinitions() .withName(prometheousRuleCrd.getMetadata().getName()).delete(); } catch (KubernetesClientException e) { logger.error("Could not create resource: {}", e.getMessage(), e); }
65
758
823
<no_super_class>