index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/registry/DefaultDockerRegistryClientMain.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.connector.registry; import java.time.Duration; import java.util.List; import java.util.concurrent.TimeUnit; import com.google.common.base.Stopwatch; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.Evaluators; import reactor.core.publisher.Flux; import reactor.core.publisher.SignalType; public class DefaultDockerRegistryClientMain { static { // Uncomment to enable logging for troubleshooting // ConsoleAppender consoleAppender = new ConsoleAppender(); // consoleAppender.setName("console"); // consoleAppender.setThreshold(Level.DEBUG); // consoleAppender.setLayout(new PatternLayout("%d %-5p %X{requestId} %C:%L [%t] [%M] %m%n")); // consoleAppender.setWriter(new OutputStreamWriter(System.out)); // // LogManager.getRootLogger().addAppender(consoleAppender); } private static final int CONCURRENCY = 100; private static final long INTERVAL_MS = 70_000; public static void main(String[] args) { if (args.length != 3) { System.err.println("Usage: DefaultDockerRegistryClientMain <registry_uri> <image_name> <image_tag>"); System.exit(-1); } String registryUri = args[0]; String imageName = args[1]; String imageTag = args[2]; DefaultDockerRegistryClient client = newClient(registryUri); while (true) { resolve(imageName, imageTag, client); try { Thread.sleep(INTERVAL_MS); } catch (InterruptedException ignore) { } } } private static void resolve(String imageName, String imageTag, DefaultDockerRegistryClient client) { Stopwatch stopwatch = Stopwatch.createStarted(); try { List<String> results = Flux.merge(Evaluators.evaluateTimes(CONCURRENCY, n -> newResolveAction(imageName, imageTag, client))) .collectList() .block(Duration.ofSeconds(30)); System.out.println(String.format("Next round completed in %sms:", stopwatch.elapsed(TimeUnit.MILLISECONDS))); results.forEach(r -> System.out.println(" " + r)); } catch (Exception e) { e.printStackTrace(); } } private static Flux<String> newResolveAction(String imageName, String imageTag, DefaultDockerRegistryClient client) { return client.getImageDigest(imageName, imageTag) .materialize() .map(signal -> signal.getType() == SignalType.ON_NEXT ? "Result=" + signal.get() : "Error=" + signal.getThrowable().getCause().getMessage()) .flux(); } private static DefaultDockerRegistryClient newClient(String registryUri) { return new DefaultDockerRegistryClient( new TitusRegistryClientConfiguration() { @Override public String getRegistryUri() { return registryUri; } @Override public boolean isSecure() { return true; } @Override public int getRegistryTimeoutMs() { return 30_000; } @Override public int getRegistryRetryCount() { return 3; } @Override public int getRegistryRetryDelayMs() { return 5_000; } }, TitusRuntimes.internal() ); } }
400
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/registry/RegistryClient.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.connector.registry; import reactor.core.publisher.Mono; /** * Interface for a container image registry client. */ public interface RegistryClient { Mono<String> getImageDigest(String repository, String reference); }
401
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/registry/DefaultDockerRegistryClient.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.connector.registry; import java.time.Duration; import java.util.AbstractMap; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.common.network.client.TitusWebClientAddOns; import com.netflix.titus.common.network.client.WebClientExt; import com.netflix.titus.common.network.client.internal.WebClientMetric; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.guice.ProxyType; import com.netflix.titus.common.util.guice.annotation.ProxyConfiguration; import io.netty.handler.codec.http.HttpResponseStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; /** * This {@link DefaultDockerRegistryClient} implementation of {@link RegistryClient} connects to a * Docker V2 REST API compatible registry endpoint. */ @Singleton @ProxyConfiguration(types = {ProxyType.Logging, ProxyType.Spectator}) public class DefaultDockerRegistryClient implements RegistryClient { private static final Logger logger = LoggerFactory.getLogger(DefaultDockerRegistryClient.class); private static final String acceptHeader = "Accept"; private static final String dockerManifestType = "application/vnd.docker.distribution.manifest.v2+json"; private static final String dockerDigestHeaderKey = "Docker-Content-Digest"; private static final Map<String, String> headers = Collections.unmodifiableMap( Stream.of(new AbstractMap.SimpleEntry<>(acceptHeader, dockerManifestType)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) ); private final TitusRuntime titusRuntime; private final TitusRegistryClientConfiguration titusRegistryClientConfiguration; private final WebClient restClient; private final WebClientMetric webClientMetrics; @Inject DefaultDockerRegistryClient(TitusRegistryClientConfiguration configuration, TitusRuntime titusRuntime) { this.titusRuntime = titusRuntime; this.titusRegistryClientConfiguration = configuration; this.webClientMetrics = new WebClientMetric(DefaultDockerRegistryClient.class.getSimpleName(), titusRuntime.getRegistry()); this.restClient = WebClient.builder() .baseUrl(configuration.getRegistryUri()) .apply(b -> TitusWebClientAddOns.addTitusDefaults(b, titusRegistryClientConfiguration.isSecure(), webClientMetrics)) .build(); } /** * Gets the Docker Version 2 Schema 2 Content Digest for the provided repository and reference. The * reference may be an image tag or digest value. If the image does not exist or another error is * encountered, an onError value is emitted. */ public Mono<String> getImageDigest(String repository, String reference) { return restClient.get().uri(buildRegistryUri(repository, reference)) .headers(consumer -> headers.forEach(consumer::add)) .exchange() .flatMap(response -> response.toEntity(String.class)) .flatMap(response -> { if (response.getStatusCode().value() == HttpResponseStatus.NOT_FOUND.code()) { return Mono.error( TitusRegistryException.imageNotFound(repository, reference) ); } if (!response.getStatusCode().is2xxSuccessful()) { return Mono.error( TitusRegistryException.internalError(repository, reference, response.getStatusCode()) ); } HttpHeaders responseHeaders = response.getHeaders(); List<String> dockerDigestHeaderValue = responseHeaders.getOrDefault(dockerDigestHeaderKey, Collections.emptyList()); if (dockerDigestHeaderValue.isEmpty()) { return Mono.error( TitusRegistryException.headerMissing(repository, reference, dockerDigestHeaderKey) ); } return Mono.just(dockerDigestHeaderValue.get(0)); }) .timeout(Duration.ofMillis(titusRegistryClientConfiguration.getRegistryTimeoutMs())) .transformDeferred(WebClientExt.latencyMonoOperator(titusRuntime.getClock(), webClientMetrics, HttpMethod.GET)) .retryWhen(TitusWebClientAddOns.retryer( Duration.ofMillis(titusRegistryClientConfiguration.getRegistryRetryDelayMs()), titusRegistryClientConfiguration.getRegistryRetryCount(), error -> !(error instanceof TitusRegistryException), logger )); } private String buildRegistryUri(String repository, String reference) { return "/v2/" + repository + "/manifests/" + reference; } }
402
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/registry/TitusRegistryException.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.connector.registry; import org.springframework.http.HttpStatus; /** * A custom {@link RuntimeException} implementation that indicates errors communicating with a container image registry. */ public class TitusRegistryException extends RuntimeException { public enum ErrorCode { INTERNAL, MISSING_HEADER, IMAGE_NOT_FOUND, } private final ErrorCode errorCode; private final String repository; private final String reference; public TitusRegistryException(ErrorCode errorCode, String repository, String reference, String message) { this(errorCode, repository, reference, message, new RuntimeException(message)); } private TitusRegistryException(ErrorCode errorCode, String repository, String reference, String message, Throwable cause) { super(message, cause); this.errorCode = errorCode; this.repository = repository; this.reference = reference; } public ErrorCode getErrorCode() { return errorCode; } public String getRepository() { return repository; } public String getReference() { return reference; } public static TitusRegistryException imageNotFound(String repository, String reference) { return new TitusRegistryException( TitusRegistryException.ErrorCode.IMAGE_NOT_FOUND, repository, reference, String.format("Image %s:%s does not exist in registry", repository, reference) ); } public static TitusRegistryException internalError(String repository, String reference, HttpStatus statusCode) { return new TitusRegistryException(TitusRegistryException.ErrorCode.INTERNAL, repository, reference, String.format("Cannot fetch image %s:%s metadata: statusCode=%s", repository, reference, statusCode)); } public static TitusRegistryException headerMissing(String repository, String reference, String missingHeader) { return new TitusRegistryException(TitusRegistryException.ErrorCode.MISSING_HEADER, repository, reference, "Missing required header " + missingHeader); } }
403
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/registry/TitusContainerRegistryModule.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.connector.registry; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.titus.runtime.endpoint.admission.JobImageSanitizerConfiguration; import com.netflix.titus.runtime.endpoint.admission.ServiceMeshImageSanitizerConfiguration; public class TitusContainerRegistryModule extends AbstractModule { @Override protected void configure() { bind(RegistryClient.class).to(DefaultDockerRegistryClient.class); } @Provides @Singleton public TitusRegistryClientConfiguration getTitusRegistryConfiguration(ConfigProxyFactory factory) { return factory.newProxy(TitusRegistryClientConfiguration.class); } @Provides @Singleton public JobImageSanitizerConfiguration getJobImageSanitizerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(JobImageSanitizerConfiguration.class); } @Provides @Singleton public ServiceMeshImageSanitizerConfiguration getServiceMeshImageSanitizerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(ServiceMeshImageSanitizerConfiguration.class); } }
404
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/registry/TitusRegistryClientConfiguration.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.connector.registry; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titus.registryClient") public interface TitusRegistryClientConfiguration { @DefaultValue("http://localhost") String getRegistryUri(); @DefaultValue("true") boolean isSecure(); @DefaultValue("2200") int getRegistryTimeoutMs(); @DefaultValue("2") int getRegistryRetryCount(); @DefaultValue("5") int getRegistryRetryDelayMs(); }
405
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/supervisor/SupervisorClient.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.connector.supervisor; import com.netflix.titus.grpc.protogen.MasterInstance; import com.netflix.titus.grpc.protogen.MasterInstances; import com.netflix.titus.grpc.protogen.SupervisorEvent; import rx.Completable; import rx.Observable; public interface SupervisorClient { Observable<MasterInstances> getMasterInstances(); Observable<MasterInstance> getMasterInstance(String instanceId); Observable<SupervisorEvent> observeEvents(); Completable stopBeingLeader(); }
406
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/supervisor/SupervisorConnectorComponent.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.connector.supervisor; import javax.inject.Named; import com.netflix.titus.grpc.protogen.SupervisorServiceGrpc; import io.grpc.Channel; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class SupervisorConnectorComponent { public static final String SUPERVISOR_CHANNEL = "supervisorChannel"; @Bean public SupervisorServiceGrpc.SupervisorServiceStub getSupervisorClientGrpcStub(final @Named(SUPERVISOR_CHANNEL) Channel channel) { return SupervisorServiceGrpc.newStub(channel); } }
407
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/supervisor
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/supervisor/client/GrpcSupervisorClient.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.connector.supervisor.client; import com.google.protobuf.Empty; import com.netflix.titus.grpc.protogen.MasterInstance; import com.netflix.titus.grpc.protogen.MasterInstanceId; import com.netflix.titus.grpc.protogen.MasterInstances; import com.netflix.titus.grpc.protogen.SupervisorEvent; import com.netflix.titus.grpc.protogen.SupervisorServiceGrpc.SupervisorServiceStub; import com.netflix.titus.runtime.connector.GrpcClientConfiguration; import com.netflix.titus.runtime.connector.supervisor.SupervisorClient; import com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil; import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver; import io.grpc.stub.StreamObserver; import rx.Completable; import rx.Observable; import javax.inject.Inject; import javax.inject.Singleton; import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.*; @Singleton public class GrpcSupervisorClient implements SupervisorClient { private final GrpcClientConfiguration configuration; private final SupervisorServiceStub client; private final CallMetadataResolver callMetadataResolver; @Inject public GrpcSupervisorClient(GrpcClientConfiguration configuration, SupervisorServiceStub client, CallMetadataResolver callMetadataResolver) { this.configuration = configuration; this.client = client; this.callMetadataResolver = callMetadataResolver; } @Override public Observable<MasterInstances> getMasterInstances() { return createRequestObservable(emitter -> { StreamObserver<MasterInstances> streamObserver = createSimpleClientResponseObserver(emitter); createWrappedStubWithResolver(client, callMetadataResolver, configuration.getRequestTimeout()).getMasterInstances(Empty.getDefaultInstance(), streamObserver); }, configuration.getRequestTimeout()); } @Override public Observable<MasterInstance> getMasterInstance(String instanceId) { return createRequestObservable(emitter -> { StreamObserver<MasterInstance> streamObserver = createSimpleClientResponseObserver(emitter); createWrappedStubWithResolver(client, callMetadataResolver, configuration.getRequestTimeout()) .getMasterInstance(MasterInstanceId.newBuilder().setInstanceId(instanceId).build(), streamObserver); }, configuration.getRequestTimeout()); } @Override public Observable<SupervisorEvent> observeEvents() { return createRequestObservable(emitter -> { StreamObserver<SupervisorEvent> streamObserver = createSimpleClientResponseObserver(emitter); createWrappedStubWithResolver(client, callMetadataResolver).observeEvents(Empty.getDefaultInstance(), streamObserver); }); } @Override public Completable stopBeingLeader() { return createRequestCompletable(emitter -> { StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientResponseObserver(emitter); createWrappedStubWithResolver(client, callMetadataResolver, configuration.getRequestTimeout()).stopBeingLeader(Empty.getDefaultInstance(), streamObserver); }, configuration.getRequestTimeout()); } }
408
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/service/TitusAgentSecurityGroupClient.java
package com.netflix.titus.runtime.service; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.TitusVpcApi.ResetSecurityGroupRequest; import com.netflix.titus.TitusVpcApi.ResetSecurityGroupResponse; import reactor.core.publisher.Mono; public interface TitusAgentSecurityGroupClient { Mono<ResetSecurityGroupResponse> resetSecurityGroup(ResetSecurityGroupRequest request, CallMetadata callMetadata); }
409
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/service/LoadBalancerService.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.service; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.grpc.protogen.AddLoadBalancerRequest; import com.netflix.titus.grpc.protogen.GetAllLoadBalancersRequest; import com.netflix.titus.grpc.protogen.GetAllLoadBalancersResult; import com.netflix.titus.grpc.protogen.GetJobLoadBalancersResult; import com.netflix.titus.grpc.protogen.JobId; import com.netflix.titus.grpc.protogen.RemoveLoadBalancerRequest; import rx.Completable; import rx.Observable; public interface LoadBalancerService { Observable<GetJobLoadBalancersResult> getLoadBalancers(JobId jobId, CallMetadata callMetadata); Observable<GetAllLoadBalancersResult> getAllLoadBalancers(GetAllLoadBalancersRequest request, CallMetadata callMetadata); Completable addLoadBalancer(AddLoadBalancerRequest request, CallMetadata callMetadata); Completable removeLoadBalancer(RemoveLoadBalancerRequest removeLoadBalancerRequest, CallMetadata callMetadata); }
410
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/service/JobActivityHistoryService.java
package com.netflix.titus.runtime.service; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.grpc.protogen.ActivityQueryResult; import com.netflix.titus.grpc.protogen.JobId; import rx.Observable; public interface JobActivityHistoryService { Observable<ActivityQueryResult> viewScalingActivities(JobId jobId, CallMetadata callMetadata); }
411
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/service/AutoScalingService.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.service; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.grpc.protogen.DeletePolicyRequest; import com.netflix.titus.grpc.protogen.GetPolicyResult; import com.netflix.titus.grpc.protogen.JobId; import com.netflix.titus.grpc.protogen.PutPolicyRequest; import com.netflix.titus.grpc.protogen.ScalingPolicyID; import com.netflix.titus.grpc.protogen.UpdatePolicyRequest; import rx.Completable; import rx.Observable; public interface AutoScalingService { Observable<GetPolicyResult> getJobScalingPolicies(JobId jobId, CallMetadata callMetadata); Observable<ScalingPolicyID> setAutoScalingPolicy(PutPolicyRequest request, CallMetadata callMetadata); Observable<GetPolicyResult> getScalingPolicy(ScalingPolicyID request, CallMetadata callMetadata); Observable<GetPolicyResult> getAllScalingPolicies(CallMetadata callMetadata); Completable deleteAutoScalingPolicy(DeletePolicyRequest request, CallMetadata callMetadata); Completable updateAutoScalingPolicy(UpdatePolicyRequest request, CallMetadata callMetadata); }
412
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/service/HealthService.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.service; import com.netflix.titus.grpc.protogen.HealthCheckRequest; import com.netflix.titus.grpc.protogen.HealthCheckResponse; import rx.Observable; public interface HealthService { Observable<HealthCheckResponse> check(HealthCheckRequest request); }
413
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/kubernetes/KubeConstants.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.kubernetes; /** * Miscellaneous Kube constants. */ public final class KubeConstants { private KubeConstants() { } /** * Taint effect constants. */ public static String TAINT_EFFECT_NO_EXECUTE = "NoExecute"; /* * Standard node labels. */ public static final String NODE_LABEL_REGION = "failure-domain.beta.kubernetes.io/region"; public static final String NODE_LABEL_ZONE = "failure-domain.beta.kubernetes.io/zone"; public static final String NODE_LABEL_INSTANCE_TYPE = "beta.kubernetes.io/instance-type"; /** * Common prefix for Titus node annotations/labels and taints. */ public static final String TITUS_DOMAIN = "titus.netflix.com/"; public static final String TITUS_NODE_DOMAIN = "node.titus.netflix.com/"; private static final String TITUS_POD_DOMAIN = "pod.titus.netflix.com/"; public static final String TITUS_SCALER_DOMAIN = "scaler.titus.netflix.com/"; /** * Common prefix for Titus V3 job API specific annotations/labels. */ public static final String TITUS_V3_JOB_DOMAIN = "v3.job.titus.netflix.com/"; /* * Common Titus labels and annotations. */ public static final String LABEL_CAPACITY_GROUP = TITUS_DOMAIN + "capacity-group"; /* * Titus pod labels and annotations. */ public static final String POD_LABEL_ACCOUNT_ID = TITUS_POD_DOMAIN + "accountId"; public static final String POD_LABEL_SUBNETS = TITUS_POD_DOMAIN + "subnets"; public static final String POD_LABEL_RELOCATION_BINPACK = TITUS_POD_DOMAIN + "relocation-binpack"; public static final String POD_LABEL_JOB_ID = TITUS_V3_JOB_DOMAIN + "job-id"; public static final String POD_LABEL_TASK_ID = TITUS_V3_JOB_DOMAIN + "task-id"; /* * Titus node labels. */ public static final String NODE_LABEL_MACHINE_ID = TITUS_NODE_DOMAIN + "id"; public static final String NODE_LABEL_MACHINE_GROUP = TITUS_NODE_DOMAIN + "asg"; public static final String NODE_LABEL_ACCOUNT_ID = TITUS_NODE_DOMAIN + "accountId"; public static final String NODE_LABEL_KUBE_BACKEND = TITUS_NODE_DOMAIN + "backend"; public static final String NODE_LABEL_CPU_MODEL = TITUS_NODE_DOMAIN + "cpu-model-name"; public static final String NODE_LABEL_RESOURCE_POOL = TITUS_SCALER_DOMAIN + "resource-pool"; /* * Titus taints. */ public static final String TAINT_NODE_UNINITIALIZED = TITUS_NODE_DOMAIN + "uninitialized"; /** * Machines with this taint and value 'titus' can be used for pod placement. */ public static final String TAINT_VIRTUAL_KUBLET = "virtual-kubelet.io/provider"; /** * Set value to 'fenzo' to assign a machine to Fenzo scheduler. By default all machines belong to the Kube scheduler. */ public static final String TAINT_SCHEDULER = TITUS_NODE_DOMAIN + "scheduler"; public static final String TAINT_SCHEDULER_VALUE_KUBE = "kubeScheduler"; /** * Machine in a farzone have the farzone taint set with its name as a value. */ public static final String TAINT_FARZONE = TITUS_NODE_DOMAIN + "farzone"; /** * Machines with the taint value 'flex' belong to the flex tier. Machines with the taint 'critical' belong to * the critical tiers. */ public static final String TAINT_TIER = TITUS_NODE_DOMAIN + "tier"; /** * Taint added to each GPU instance. */ public static final String TAINT_GPU_INSTANCE = TITUS_NODE_DOMAIN + "gpu"; /** * Taint added to nodes with experimental backends or backends which should not be a default scheduling targets, * unless explicitly requested. */ public static final String TAINT_KUBE_BACKEND = TITUS_NODE_DOMAIN + "backend"; /** * Nodes with this taint are in the process of being decommissioned. Effects have different meaning: * - <code>PreferNoSchedule</code>: nodes being drained, and capacity is preserved if needed * - <code>NoSchedule</code>: used to avoid placing tasks with the {@link com.netflix.titus.api.jobmanager.JobConstraints#ACTIVE_HOST} onto nodes being decommissioned * - <code>NoExecute</code>: nodes being actively evacuated by task relocation */ public static final String TAINT_NODE_DECOMMISSIONING = TITUS_NODE_DOMAIN + "decommissioning"; /** * Predicted runtime for a Job in a format compatible with Go's <tt>time.Duration</tt>, e.g. <tt>10s</tt>. * <p> * See <a href="https://godoc.org/time#ParseDuration"><tt>time.ParseDuration</tt></a> for more details on the format. */ public static final String JOB_RUNTIME_PREDICTION = "predictions.scheduler.titus.netflix.com/runtime"; /* * Pod environment variable name constants. */ public static final String POD_ENV_TITUS_JOB_ID = "TITUS_JOB_ID"; public static final String POD_ENV_TITUS_TASK_ID = "TITUS_TASK_ID"; public static final String POD_ENV_NETFLIX_EXECUTOR = "NETFLIX_EXECUTOR"; public static final String POD_ENV_NETFLIX_INSTANCE_ID = "NETFLIX_INSTANCE_ID"; public static final String POD_ENV_TITUS_TASK_INSTANCE_ID = "TITUS_TASK_INSTANCE_ID"; public static final String POD_ENV_TITUS_TASK_ORIGINAL_ID = "TITUS_TASK_ORIGINAL_ID"; public static final String POD_ENV_TITUS_TASK_INDEX = "TITUS_TASK_INDEX"; /* * Label selector operators. See https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity */ public static final String SELECTOR_OPERATOR_IN = "In"; public static final String SELECTOR_OPERATOR_NOT_IN = "NotIn"; public static final String SELECTOR_OPERATOR_EXISTS = "Exists"; public static final String SELECTOR_OPERATOR_DOES_NOT_EXIST = "DoesNotExist"; public static final String SELECTOR_OPERATOR_GT = "Gt"; public static final String SELECTOR_OPERATOR_LT = "Lt"; /* * API Constants */ public static final String DEFAULT_NAMESPACE = "default"; public static final String NOT_FOUND = "Not Found"; public static final String READY = "Ready"; public static final String PENDING = "Pending"; public static final String RUNNING = "Running"; public static final String SUCCEEDED = "Succeeded"; public static final String FAILED = "Failed"; public static final String BACKGROUND = "Background"; /** * Reconciler Event Constants */ public static final String NODE_LOST = "NodeLost"; /** * ANNOTATION_KEY_IMAGE_TAG_PREFIX Stores the original tag for the image. * This is because on the v1 pod image field, there is only room for the digest and no room for the tag it came from */ public static final String ANNOTATION_KEY_IMAGE_TAG_PREFIX = "pod.titus.netflix.com/image-tag-"; }
414
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/store/v3
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/store/v3/memory/InMemoryPolicyStore.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.store.v3.memory; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import com.netflix.titus.api.appscale.model.AutoScalingPolicy; import com.netflix.titus.api.appscale.model.PolicyStatus; import com.netflix.titus.api.appscale.store.AppScalePolicyStore; import com.netflix.titus.common.util.rx.ObservableExt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; import rx.Observable; public class InMemoryPolicyStore implements AppScalePolicyStore { private static Logger log = LoggerFactory.getLogger(InMemoryPolicyStore.class); private final Map<String, AutoScalingPolicy> policyMap = new ConcurrentHashMap<>(); @Override public Completable init() { return Completable.complete(); } @Override public Observable<AutoScalingPolicy> retrievePolicies(boolean includeArchived) { return Observable.from( policyMap.values().stream() .filter(autoScalingPolicy -> autoScalingPolicy.getStatus() == PolicyStatus.Pending || autoScalingPolicy.getStatus() == PolicyStatus.Applied || autoScalingPolicy.getStatus() == PolicyStatus.Error || autoScalingPolicy.getStatus() == PolicyStatus.Deleting || (includeArchived && autoScalingPolicy.getStatus() == PolicyStatus.Deleted)) .collect(Collectors.toList())); } @Override public Observable<String> storePolicy(AutoScalingPolicy autoScalingPolicy) { return Observable.fromCallable(() -> { String policyRefId = UUID.randomUUID().toString(); AutoScalingPolicy policySaved = AutoScalingPolicy.newBuilder() .withAutoScalingPolicy(autoScalingPolicy) .withRefId(policyRefId) .withStatus(PolicyStatus.Pending) .build(); policyMap.putIfAbsent(policyRefId, policySaved); return policyRefId; }); } @Override public Completable updatePolicyId(String policyRefId, String policyId) { return Completable.fromCallable(() -> { AutoScalingPolicy autoScalingPolicy = policyMap.get(policyRefId); AutoScalingPolicy policySaved = AutoScalingPolicy.newBuilder().withAutoScalingPolicy(autoScalingPolicy).withPolicyId(policyId).build(); return policyMap.put(policyRefId, policySaved); }); } @Override public Completable updateAlarmId(String policyRefId, String alarmId) { return Completable.fromCallable(() -> { AutoScalingPolicy autoScalingPolicy = policyMap.get(policyRefId); AutoScalingPolicy policySaved = AutoScalingPolicy.newBuilder().withAutoScalingPolicy(autoScalingPolicy).withAlarmId(alarmId).build(); return policyMap.put(policyRefId, policySaved); }); } @Override public Completable updatePolicyStatus(String policyRefId, PolicyStatus policyStatus) { return Completable.fromCallable(() -> { log.info("Updating policy status for refID {} -> {}", policyRefId, policyStatus); AutoScalingPolicy autoScalingPolicy = policyMap.get(policyRefId); AutoScalingPolicy policySaved = AutoScalingPolicy.newBuilder().withAutoScalingPolicy(autoScalingPolicy).withStatus(policyStatus).build(); return policyMap.put(policyRefId, policySaved); }); } @Override public Completable updateStatusMessage(String policyRefId, String statusMessage) { return Completable.fromCallable(() -> { AutoScalingPolicy autoScalingPolicy = policyMap.get(policyRefId); AutoScalingPolicy policySaved = AutoScalingPolicy.newBuilder().withAutoScalingPolicy(autoScalingPolicy) .withStatusMessage(statusMessage).build(); return policyMap.put(policyRefId, policySaved); }); } @Override public Observable<AutoScalingPolicy> retrievePoliciesForJob(String jobId) { return ObservableExt.fromCollection(() -> policyMap.values().stream() .filter(autoScalingPolicy -> matches(jobId, autoScalingPolicy)) .collect(Collectors.toList()) ); } @Override public Completable updatePolicyConfiguration(AutoScalingPolicy autoScalingPolicy) { return Completable.fromCallable(() -> { log.info("Updating policy configuration for refID {}", autoScalingPolicy.getRefId()); AutoScalingPolicy existingPolicy = policyMap.get(autoScalingPolicy.getRefId()); AutoScalingPolicy policySaved = AutoScalingPolicy.newBuilder().withAutoScalingPolicy(existingPolicy) .withPolicyConfiguration(autoScalingPolicy.getPolicyConfiguration()).build(); return policyMap.put(policySaved.getRefId(), policySaved); }); } @Override public Observable<AutoScalingPolicy> retrievePolicyForRefId(String policyRefId) { if (policyMap.containsKey(policyRefId)) { log.info("Retrieving policy by refID {} with configuration {}", policyRefId, policyMap.get(policyRefId).getPolicyConfiguration()); return Observable.just(policyMap.get(policyRefId)); } return Observable.empty(); } @Override public Completable removePolicy(String policyRefId) { return updatePolicyStatus(policyRefId, PolicyStatus.Deleting); } private boolean matches(String jobId, AutoScalingPolicy autoScalingPolicy) { return autoScalingPolicy.getJobId().equals(jobId) && (autoScalingPolicy.getStatus() == PolicyStatus.Pending || autoScalingPolicy.getStatus() == PolicyStatus.Deleting || autoScalingPolicy.getStatus() == PolicyStatus.Error || autoScalingPolicy.getStatus() == PolicyStatus.Applied); } }
415
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/store/v3
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/store/v3/memory/InMemoryLoadBalancerStore.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.store.v3.memory; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancerState; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTarget; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTarget.State; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTargetState; import com.netflix.titus.api.loadbalancer.store.LoadBalancerStore; import com.netflix.titus.runtime.loadbalancer.LoadBalancerCursors; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import rx.Completable; import rx.Observable; /** * Operations are not being indexed yet for simplicity. */ public class InMemoryLoadBalancerStore implements LoadBalancerStore { private final ConcurrentMap<JobLoadBalancer, JobLoadBalancer.State> associations = new ConcurrentHashMap<>(); private final ConcurrentMap<LoadBalancerTarget, State> targets = new ConcurrentHashMap<>(); @Override public Observable<JobLoadBalancer> getAssociatedLoadBalancersForJob(String jobId) { return Observable.defer(() -> Observable.from(getAssociatedLoadBalancersSetForJob(jobId))); } // Note: This implementation is not optimized for constant time lookup and should only // be used for non-performance critical scenarios, like testing. @Override public Set<JobLoadBalancer> getAssociatedLoadBalancersSetForJob(String jobId) { return associations.entrySet().stream() .filter(pair -> pair.getKey().getJobId().equals(jobId) && (pair.getValue() == JobLoadBalancer.State.ASSOCIATED)) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } @Override public Completable addOrUpdateLoadBalancer(JobLoadBalancer jobLoadBalancer, JobLoadBalancer.State state) { return Completable.fromAction(() -> associations.put(jobLoadBalancer, state)); } @Override public Completable removeLoadBalancer(JobLoadBalancer jobLoadBalancer) { return Completable.fromAction(() -> associations.remove(jobLoadBalancer)); } @Override public int getNumLoadBalancersForJob(String jobId) { int loadBalancerCount = 0; for (Map.Entry<JobLoadBalancer, JobLoadBalancer.State> entry : associations.entrySet()) { if (entry.getKey().getJobId().equals(jobId)) { loadBalancerCount++; } } return loadBalancerCount; } @Override public List<JobLoadBalancerState> getAssociations() { return associations.entrySet().stream() .map(JobLoadBalancerState::from) .collect(Collectors.toList()); } @Override public List<JobLoadBalancer> getAssociationsPage(int offset, int limit) { return associations.keySet().stream() .sorted(LoadBalancerCursors.loadBalancerComparator()) .skip(offset) .limit(limit) .collect(Collectors.toList()); } @Override public Mono<Void> addOrUpdateTargets(Collection<LoadBalancerTargetState> toAdd) { return Mono.fromRunnable(() -> toAdd.forEach(t -> targets.put(t.getLoadBalancerTarget(), t.getState()))); } @Override public Mono<Void> removeDeregisteredTargets(Collection<LoadBalancerTarget> toRemove) { return Mono.fromRunnable(() -> toRemove.forEach(target -> targets.remove(target, State.DEREGISTERED))); } @Override public Flux<LoadBalancerTargetState> getLoadBalancerTargets(String loadBalancerId) { return Flux.fromStream( targets.entrySet().stream() .filter(entry -> entry.getKey().getLoadBalancerId().equals(loadBalancerId)) .map(LoadBalancerTargetState::from) ); } }
416
0
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/store/v3
Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/store/v3/memory/InMemoryJobStore.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.store.v3.memory; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.inject.Singleton; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.store.JobStore; import com.netflix.titus.api.jobmanager.store.JobStoreException; import com.netflix.titus.common.util.tuple.Pair; import rx.Completable; import rx.Observable; @Singleton public class InMemoryJobStore implements JobStore { private static final int MAX_CACHE_SIZE = 100_000; private final Cache<String, Job<?>> jobs = CacheBuilder.newBuilder() .maximumSize(MAX_CACHE_SIZE) .build(); private final Cache<String, Task> tasks = CacheBuilder.newBuilder() .maximumSize(MAX_CACHE_SIZE) .build(); private final Cache<String, Job<?>> archivedJobs = CacheBuilder.newBuilder() .maximumSize(MAX_CACHE_SIZE) .build(); private final Cache<String, Task> archivedTasks = CacheBuilder.newBuilder() .maximumSize(MAX_CACHE_SIZE) .build(); @Override public Completable init() { return Completable.complete(); } @Override public Observable<Pair<List<Job<?>>, Integer>> retrieveJobs() { return Observable.just(Pair.of(new ArrayList<>(jobs.asMap().values()), 0)); } @Override public Observable<Job<?>> retrieveJob(String jobId) { return Observable.fromCallable(() -> { Job job = jobs.getIfPresent(jobId); if (job == null) { throw JobStoreException.jobDoesNotExist(jobId); } return job; }); } @Override public Completable storeJob(Job job) { return Completable.fromAction(() -> jobs.put(job.getId(), job)); } @Override public Completable updateJob(Job job) { return storeJob(job); } @Override public Completable deleteJob(Job job) { return Completable.fromAction(() -> { tasks.asMap().values().stream().filter(task -> task.getJobId().equals(job.getId())).forEach(task -> { tasks.invalidate(task.getId()); archivedTasks.put(task.getId(), task); }); jobs.invalidate(job.getId()); archivedJobs.put(job.getId(), job); }); } @Override public Observable<Pair<List<Task>, Integer>> retrieveTasksForJob(String jobId) { List<Task> jobTask = tasks.asMap().values().stream() .filter(task -> task.getJobId().equals(jobId)) .collect(Collectors.toList()); return Observable.just(Pair.of(jobTask, 0)); } @Override public Observable<Task> retrieveTask(String taskId) { return Observable.fromCallable(() -> { Task task = tasks.getIfPresent(taskId); if (task == null) { throw JobStoreException.taskDoesNotExist(taskId); } return task; }); } @Override public Completable storeTask(Task task) { return Completable.fromAction(() -> tasks.put(task.getId(), task)); } @Override public Completable updateTask(Task task) { return storeTask(task); } @Override public Completable replaceTask(Task oldTask, Task newTask) { return Completable.fromAction(() -> { tasks.invalidate(oldTask.getId()); archivedTasks.put(oldTask.getId(), oldTask); tasks.put(newTask.getId(), newTask); }); } @Override public Completable moveTask(Job jobFrom, Job jobTo, Task taskAfter) { return Completable.fromAction(() -> { jobs.put(jobFrom.getId(), jobFrom); jobs.put(jobTo.getId(), jobTo); tasks.put(taskAfter.getId(), taskAfter); }); } @Override public Completable deleteTask(Task task) { return Completable.fromAction(() -> { tasks.invalidate(task.getId()); archivedTasks.put(task.getId(), task); }); } @Override public Observable<Job<?>> retrieveArchivedJob(String jobId) { return Observable.fromCallable(() -> { Job job = archivedJobs.getIfPresent(jobId); if (job == null) { throw JobStoreException.jobDoesNotExist(jobId); } return job; }); } @Override public Observable<Task> retrieveArchivedTasksForJob(String jobId) { return Observable.from(archivedTasks.asMap().values()).filter(task -> task.getJobId().equals(jobId)); } @Override public Observable<Task> retrieveArchivedTask(String taskId) { return Observable.fromCallable(() -> { Task task = archivedTasks.getIfPresent(taskId); if (task == null) { throw JobStoreException.taskDoesNotExist(taskId); } return task; }); } @Override public Observable<Long> retrieveArchivedTaskCountForJob(String jobId) { return Observable.from(archivedTasks.asMap().values()) .filter(task -> task.getJobId().equals(jobId)) .countLong(); } @Override public Completable deleteArchivedTask(String jobId, String taskId) { return Completable.fromAction(() -> { archivedTasks.invalidate(taskId); }); } }
417
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/test/java/com/netflix/titus/ext/jooq
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/test/java/com/netflix/titus/ext/jooq/profile/DatabaseProfileLoaderTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq.profile; import java.io.File; import java.net.URL; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class DatabaseProfileLoaderTest { @Test public void testLoadFromFile() { URL fileURL = DatabaseProfileLoaderTest.class.getClassLoader().getResource("titus-jooq.yaml"); assertThat(fileURL).isNotNull(); String file = fileURL.getPath(); DatabaseProfiles p = DatabaseProfileLoader.loadFromFile(new File(file)); assertThat(p.getProfiles()).containsEntry( "relocation", new DatabaseProfile("relocation", "jdbc:postgresql://localhost:5432/postgres", "titus", "123") ); } }
418
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/ProductionJooqContext.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq; import javax.inject.Inject; import javax.inject.Singleton; import javax.sql.DataSource; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.ExecutorsExt; import com.netflix.titus.ext.jooq.spectator.SpectatorHikariMetricsTrackerFactory; import com.netflix.titus.ext.jooq.spectator.SpectatorJooqExecuteListener; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.jooq.Configuration; import org.jooq.impl.DefaultConfiguration; import org.jooq.impl.DefaultDSLContext; import org.postgresql.PGProperty; @Singleton public class ProductionJooqContext implements JooqContext { private final DataSource dataSource; private final DefaultDSLContext dslContext; @Inject public ProductionJooqContext(JooqConfiguration jooqConfiguration, TitusRuntime titusRuntime) { HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setAutoCommit(true); hikariConfig.setMetricsTrackerFactory(new SpectatorHikariMetricsTrackerFactory( titusRuntime.getRegistry().createId("titus.jooq.hikari"), titusRuntime )); // Connection management hikariConfig.setConnectionTimeout(10000); hikariConfig.setMaximumPoolSize(10); hikariConfig.setLeakDetectionThreshold(3000); hikariConfig.addDataSourceProperty(PGProperty.SSL.getName(), "true"); hikariConfig.addDataSourceProperty(PGProperty.SSL_MODE.getName(), "verify-ca"); hikariConfig.addDataSourceProperty(PGProperty.SSL_FACTORY.getName(), RDSSSLSocketFactory.class.getName()); hikariConfig.setJdbcUrl(jooqConfiguration.getDatabaseUrl()); this.dataSource = new HikariDataSource(hikariConfig); Configuration config = new DefaultConfiguration() .derive(dataSource) .derive(DEFAULT_DIALECT) .derive(new SpectatorJooqExecuteListener( titusRuntime.getRegistry().createId("titus.jooq.executorListener"), titusRuntime )); if (jooqConfiguration.isOwnExecutorPool()) { config = config.derive(ExecutorsExt.instrumentedFixedSizeThreadPool(titusRuntime.getRegistry(), "jooq", jooqConfiguration.getExecutorPoolSize())); } this.dslContext = new DefaultDSLContext(config); } public DataSource getDataSource() { return dataSource; } public DefaultDSLContext getDslContext() { return dslContext; } }
419
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/JooqContext.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq; import javax.sql.DataSource; import org.jooq.SQLDialect; import org.jooq.impl.DefaultDSLContext; public interface JooqContext { SQLDialect DEFAULT_DIALECT = SQLDialect.POSTGRES; DataSource getDataSource(); DefaultDSLContext getDslContext(); default void close() { } }
420
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/RDSSSLSocketFactory.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq; import org.postgresql.ssl.WrappedFactory; public class RDSSSLSocketFactory extends WrappedFactory { public RDSSSLSocketFactory() { factory = RdsUtils.createRdsSSLSocketFactory(); } }
421
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/JooqConfiguration.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq; import com.netflix.archaius.api.annotations.DefaultValue; public interface JooqConfiguration { @DefaultValue("jdbc://localhost") String getDatabaseUrl(); @DefaultValue("false") boolean isInMemoryDb(); @DefaultValue("true") boolean isCreateSchemaIfNotExist(); /** * Set to true, to enable Jooq own thread executor pool. If set to false, it uses the default shared ForkJoin pool. */ @DefaultValue("true") boolean isOwnExecutorPool(); @DefaultValue("100") int getExecutorPoolSize(); }
422
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/RdsUtils.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq; import java.io.InputStream; import java.security.KeyStore; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; public final class RdsUtils { /** * Setting as a constant as it is not critical. */ private static final String TRUST_STORE_PASSWORD = "titus123"; public static SSLSocketFactory createRdsSSLSocketFactory() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream inputStream = RdsUtils.class.getClassLoader().getResourceAsStream("RDS-2019.truststore")) { trustStore.load(inputStream, TRUST_STORE_PASSWORD.toCharArray()); } TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); return sslContext.getSocketFactory(); } catch (Exception e) { throw new IllegalStateException("Cannot initialize RDS socket factory", e); } } }
423
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/JooqUtils.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.function.Supplier; import org.jooq.DSLContext; import reactor.core.publisher.Mono; public class JooqUtils { // Returns a CompletableStage that asynchronously runs the supplier on the DSL's executor public static <T> CompletionStage<T> executeAsync(Supplier<T> supplier, DSLContext dslContext) { return CompletableFuture.supplyAsync(supplier, dslContext.configuration().executorProvider().provide()); } // Returns a Mono that asynchronously runs the supplier on the DSL's executor public static <T> Mono<T> executeAsyncMono(Supplier<T> supplier, DSLContext dslContext) { return Mono.fromCompletionStage(executeAsync(supplier, dslContext)); } }
424
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/profile/DatabaseProfile.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq.profile; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Database configuration. */ public class DatabaseProfile { private final String name; private final String databaseUrl; private final String user; private final String password; @JsonCreator public DatabaseProfile(@JsonProperty("name") String name, @JsonProperty("databaseUrl") String databaseUrl, @JsonProperty("user") String user, @JsonProperty("password") String password) { this.name = name; this.databaseUrl = databaseUrl; this.user = user; this.password = password; } public String getName() { return name; } public String getDatabaseUrl() { return databaseUrl; } public String getUser() { return user; } public String getPassword() { return password; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DatabaseProfile that = (DatabaseProfile) o; return Objects.equals(name, that.name) && Objects.equals(databaseUrl, that.databaseUrl) && Objects.equals(user, that.user) && Objects.equals(password, that.password); } @Override public int hashCode() { return Objects.hash(name, databaseUrl, user, password); } @Override public String toString() { return "DatabaseProfile{" + "name='" + name + '\'' + ", databaseUrl='" + databaseUrl + '\'' + ", user='" + user + '\'' + ", password='" + password + '\'' + '}'; } }
425
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/profile/DatabaseProfileLoader.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq.profile; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; public final class DatabaseProfileLoader { public static final String LOCAL_CONFIGURATION_FILE = ".titus-jooq.yaml"; /** * Load {@link DatabaseProfile}s from the home folder. */ public static DatabaseProfiles loadLocal() { File file = new File(System.getenv("HOME"), LOCAL_CONFIGURATION_FILE); if (!file.exists()) { return DatabaseProfiles.empty(); } return loadFromFile(file); } public static DatabaseProfiles loadFromFile(File file) { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); try { return mapper.readValue(file, DatabaseProfiles.class); } catch (IOException e) { throw new IllegalArgumentException("Cannot load local database setup from " + file, e); } } }
426
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/profile/DatabaseProfiles.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq.profile; import java.util.Collections; import java.util.Map; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class DatabaseProfiles { private static final DatabaseProfiles EMPTY = new DatabaseProfiles(Collections.emptyMap()); private final Map<String, DatabaseProfile> profiles; @JsonCreator public DatabaseProfiles(@JsonProperty("profiles") Map<String, DatabaseProfile> profiles) { this.profiles = profiles; } public Map<String, DatabaseProfile> getProfiles() { return profiles; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DatabaseProfiles that = (DatabaseProfiles) o; return Objects.equals(profiles, that.profiles); } @Override public int hashCode() { return Objects.hash(profiles); } @Override public String toString() { return "DatabaseProfiles{" + "profiles=" + profiles + '}'; } public static DatabaseProfiles empty() { return EMPTY; } }
427
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/spectator/SpectatorJooqExecuteListener.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq.spectator; import com.netflix.spectator.api.Id; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.spectator.MetricSelector; import com.netflix.titus.common.util.spectator.SpectatorExt; import com.netflix.titus.common.util.spectator.ValueRangeCounter; import com.netflix.titus.common.util.time.Clock; import org.jooq.ExecuteContext; import org.jooq.ExecuteListener; public class SpectatorJooqExecuteListener implements ExecuteListener { private final MetricSelector<ValueRangeCounter> latencies; private final Clock clock; private final ThreadLocal<Long> startTimestamp = new ThreadLocal<>(); private final ThreadLocal<Long> executeTimestamp = new ThreadLocal<>(); public SpectatorJooqExecuteListener(Id root, TitusRuntime titusRuntime) { this.clock = titusRuntime.getClock(); this.latencies = SpectatorExt.newValueRangeCounterSortable( titusRuntime.getRegistry().createId(root.name() + "latencies", root.tags()), new String[]{"point"}, SpectatorUtils.LEVELS, titusRuntime.getRegistry() ); } /** * Called at the very beginning in Jooq AbstractQuery. Captures the total time of query execution within Jooq * including the time it gets to get a free connection from the pool. */ @Override public void start(ExecuteContext ctx) { startTimestamp.set(clock.wallTime()); } @Override public void renderStart(ExecuteContext ctx) { } @Override public void renderEnd(ExecuteContext ctx) { } @Override public void prepareStart(ExecuteContext ctx) { } @Override public void prepareEnd(ExecuteContext ctx) { } @Override public void bindStart(ExecuteContext ctx) { } @Override public void bindEnd(ExecuteContext ctx) { } /** * Called just before executing a statement, after connection was acquired and all parameters were bound. */ @Override public void executeStart(ExecuteContext ctx) { executeTimestamp.set(clock.wallTime()); } /** * See {@link #executeStart(ExecuteContext)} */ @Override public void executeEnd(ExecuteContext ctx) { recordLatency(executeTimestamp, "execute"); } @Override public void outStart(ExecuteContext ctx) { } @Override public void outEnd(ExecuteContext ctx) { } @Override public void fetchStart(ExecuteContext ctx) { } @Override public void resultStart(ExecuteContext ctx) { } @Override public void recordStart(ExecuteContext ctx) { } @Override public void recordEnd(ExecuteContext ctx) { } @Override public void resultEnd(ExecuteContext ctx) { } @Override public void fetchEnd(ExecuteContext ctx) { } /** * See {@link #start(ExecuteContext)} */ @Override public void end(ExecuteContext ctx) { recordLatency(startTimestamp, "start"); } private void recordLatency(ThreadLocal<Long> timestamp, String point) { Long startTime = timestamp.get(); if (startTime != null) { latencies.withTags(point).ifPresent(m -> m.recordLevel(clock.wallTime() - startTime)); } } @Override public void exception(ExecuteContext ctx) { } @Override public void warning(ExecuteContext ctx) { } }
428
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/spectator/SpectatorUtils.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq.spectator; class SpectatorUtils { static final long[] LEVELS = new long[]{1, 10, 50, 100, 200, 500, 1_000, 2_000, 5_000, 10_000, 20_000, 60_000}; }
429
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/spectator/SpectatorHikariMetricsTrackerFactory.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq.spectator; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.spectator.MetricSelector; import com.netflix.titus.common.util.spectator.SpectatorExt; import com.netflix.titus.common.util.spectator.ValueRangeCounter; import com.zaxxer.hikari.metrics.IMetricsTracker; import com.zaxxer.hikari.metrics.MetricsTrackerFactory; import com.zaxxer.hikari.metrics.PoolStats; public class SpectatorHikariMetricsTrackerFactory implements MetricsTrackerFactory { private static final long ONE_MILLION = 1_000_000; private final Registry registry; private final Id idPoolStats; private final Id idLatencies; private final Id idConnectionTimeout; public SpectatorHikariMetricsTrackerFactory(Id root, TitusRuntime titusRuntime) { this.registry = titusRuntime.getRegistry(); this.idPoolStats = registry.createId(root.name() + ".poolStats", root.tags()); this.idLatencies = registry.createId(root.name() + ".latencies", root.tags()); this.idConnectionTimeout = registry.createId(root.name() + ".connectionTimeout", root.tags()); } @Override public IMetricsTracker create(String poolName, PoolStats poolStats) { return new SpectatorIMetricsTracker(poolName, poolStats); } private class SpectatorIMetricsTracker implements IMetricsTracker { private final MetricSelector<ValueRangeCounter> latencies; private final Counter connectionTimeoutCounter; // Keep reference to prevent it from being garbage collected. private final PoolStats poolStats; public SpectatorIMetricsTracker(String poolName, PoolStats poolStats) { this.poolStats = poolStats; PolledMeter.using(registry) .withId(idPoolStats.withTags("pool", poolName, "poolStats", "totalConnections")) .monitorValue(poolStats, PoolStats::getTotalConnections); PolledMeter.using(registry) .withId(idPoolStats.withTags("pool", poolName, "poolStats", "activeConnections")) .monitorValue(poolStats, PoolStats::getActiveConnections); PolledMeter.using(registry) .withId(idPoolStats.withTags("pool", poolName, "poolStats", "idleConnections")) .monitorValue(poolStats, PoolStats::getIdleConnections); PolledMeter.using(registry) .withId(idPoolStats.withTags("pool", poolName, "poolStats", "maxConnections")) .monitorValue(poolStats, PoolStats::getMaxConnections); PolledMeter.using(registry) .withId(idPoolStats.withTags("pool", poolName, "poolStats", "minConnections")) .monitorValue(poolStats, PoolStats::getMinConnections); PolledMeter.using(registry) .withId(idPoolStats.withTags("pool", poolName, "poolStats", "pendingThreads")) .monitorValue(poolStats, PoolStats::getPendingThreads); this.latencies = SpectatorExt.newValueRangeCounterSortable( idLatencies.withTags("pool", poolName), new String[]{"step"}, SpectatorUtils.LEVELS, registry ); this.connectionTimeoutCounter = registry.counter(idConnectionTimeout.withTag("pool", poolName)); } @Override public void recordConnectionCreatedMillis(long connectionCreatedMillis) { latencies.withTags("connectionCreated").ifPresent(m -> m.recordLevel(connectionCreatedMillis)); } @Override public void recordConnectionAcquiredNanos(long elapsedAcquiredNanos) { latencies.withTags("connectionAcquired").ifPresent(m -> m.recordLevel(elapsedAcquiredNanos / ONE_MILLION)); } @Override public void recordConnectionUsageMillis(long elapsedBorrowedMillis) { latencies.withTags("elapsedBorrowed").ifPresent(m -> m.recordLevel(elapsedBorrowedMillis)); } @Override public void recordConnectionTimeout() { connectionTimeoutCounter.increment(); } } }
430
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/embedded/EmbeddedPostgresService.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq.embedded; import java.sql.Connection; import java.sql.PreparedStatement; import javax.inject.Inject; import javax.inject.Singleton; import javax.sql.DataSource; import com.google.common.base.Preconditions; import com.opentable.db.postgres.embedded.EmbeddedPostgres; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class EmbeddedPostgresService { private static final Logger logger = LoggerFactory.getLogger(EmbeddedPostgresService.class); private static final String DB_NAME = "integration"; private static final String POSTGRES_DB_NAME = "postgres", POSTGRES_USER = "postgres", POSTGRES_PW = "postgres"; private final EmbeddedPostgres embeddedPostgres; private final DataSource dataSource; private final Connection connection; @Inject public EmbeddedPostgresService() { try { this.embeddedPostgres = EmbeddedPostgres.start(); DataSource defaultDataSource = embeddedPostgres.getDatabase(POSTGRES_USER, POSTGRES_DB_NAME); connection = defaultDataSource.getConnection(POSTGRES_USER, POSTGRES_PW); PreparedStatement statement = connection.prepareStatement("CREATE DATABASE integration"); // ignore result statement.execute(); statement.close(); this.dataSource = this.embeddedPostgres.getDatabase(POSTGRES_USER, DB_NAME); } catch (Exception error) { logger.error("Failed to start an instance of EmbeddedPostgres database", error); throw new IllegalStateException(error); } } public DataSource getDataSource() { Preconditions.checkNotNull(dataSource, "Embedded Postgres mode not enabled"); return dataSource; } }
431
0
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq
Create_ds/titus-control-plane/titus-common-ext/jooq-common/src/main/java/com/netflix/titus/ext/jooq/embedded/EmbeddedJooqContext.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.jooq.embedded; import javax.sql.DataSource; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.ExecutorsExt; import com.netflix.titus.ext.jooq.JooqContext; import com.netflix.titus.ext.jooq.profile.DatabaseProfile; import com.netflix.titus.ext.jooq.profile.DatabaseProfileLoader; import com.netflix.titus.ext.jooq.profile.DatabaseProfiles; import com.netflix.titus.ext.jooq.spectator.SpectatorHikariMetricsTrackerFactory; import com.netflix.titus.ext.jooq.spectator.SpectatorJooqExecuteListener; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.jooq.Configuration; import org.jooq.SQLDialect; import org.jooq.impl.DefaultConfiguration; import org.jooq.impl.DefaultDSLContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; public class EmbeddedJooqContext implements JooqContext { private static final Logger logger = LoggerFactory.getLogger(EmbeddedJooqContext.class); private static final SQLDialect DEFAULT_DIALECT = SQLDialect.POSTGRES; /** * Embedded jooq context is used in the integration tests only, so modest pool size is sufficient. */ private static final int DEFAULT_EXECUTOR_POOL_SIZE = 50; private final HikariDataSource dataSource; private final EmbeddedPostgresService embeddedPostgresService; private final DefaultDSLContext dslContext; public EmbeddedJooqContext(ConfigurableApplicationContext context, String profileName, TitusRuntime titusRuntime) { this(context, profileName, true, DEFAULT_EXECUTOR_POOL_SIZE, titusRuntime); } public EmbeddedJooqContext(ConfigurableApplicationContext context, String profileName, boolean ownExecutorPool, int executorPoolSize, TitusRuntime titusRuntime) { HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setAutoCommit(true); hikariConfig.setMetricsTrackerFactory(new SpectatorHikariMetricsTrackerFactory( titusRuntime.getRegistry().createId("titus.jooq.hikari"), titusRuntime )); DatabaseProfiles profiles = DatabaseProfileLoader.loadLocal(); logger.info("Loaded embedded database profiles: {}", profiles); DatabaseProfile profile = profiles.getProfiles().get(profileName); if (profile != null) { logger.info("Using embedded database profile: {}", profile); hikariConfig.setJdbcUrl(profile.getDatabaseUrl()); hikariConfig.setUsername(profile.getUser()); hikariConfig.setPassword(profile.getPassword()); this.embeddedPostgresService = null; } else { // No valid profile. Start embeddedPostgresService logger.info("No embedded database profile found. Starting embedded Postgres service"); EmbeddedPostgresService embeddedPostgresService; try { embeddedPostgresService = context.getBean(EmbeddedPostgresService.class); } catch (Exception e) { ((GenericWebApplicationContext) context).registerBean(EmbeddedPostgresService.class); embeddedPostgresService = context.getBean(EmbeddedPostgresService.class); } this.embeddedPostgresService = embeddedPostgresService; //((GenericWebApplicationContext) context).registerBean(); hikariConfig.setDataSource(this.embeddedPostgresService.getDataSource()); } // Connection management hikariConfig.setConnectionTimeout(10000); hikariConfig.setMaximumPoolSize(10); hikariConfig.setLeakDetectionThreshold(3000); this.dataSource = new HikariDataSource(hikariConfig); Configuration config = new DefaultConfiguration() .derive(dataSource) .derive(DEFAULT_DIALECT) .derive(new SpectatorJooqExecuteListener( titusRuntime.getRegistry().createId("titus.jooq.executorListener"), titusRuntime )); if (ownExecutorPool) { config = config.derive(ExecutorsExt.instrumentedFixedSizeThreadPool(titusRuntime.getRegistry(), "jooq", executorPoolSize)); } this.dslContext = new DefaultDSLContext(config); } public void close() { dslContext.close(); dataSource.close(); } public DataSource getDataSource() { return dataSource; } public DefaultDSLContext getDslContext() { return dslContext; } }
432
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector/StubbedKubeExecutors.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership; import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent; import com.netflix.titus.api.clustermembership.model.event.LeaderElectionChangeEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.DirectProcessor; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import static com.jayway.awaitility.Awaitility.await; class StubbedKubeExecutors implements KubeMembershipExecutor, KubeLeaderElectionExecutor { private static final Logger logger = LoggerFactory.getLogger(StubbedKubeExecutors.class); private final String localMemberId; private final AtomicInteger memberRevisionIdx = new AtomicInteger(); private final AtomicInteger leadershipRevisionIdx = new AtomicInteger(); private volatile ClusterMembershipRevision<ClusterMember> localMemberRevision; private volatile ClusterMembershipRevision<ClusterMemberLeadership> localLeadershipRevision; private volatile boolean firstRegistration = true; private volatile boolean inLeaderElectionProcess; private volatile boolean localLeader; private volatile RuntimeException onMembershipUpdateError; private volatile int onMembershipUpdateErrorCount; private final ConcurrentMap<String, ClusterMembershipRevision<ClusterMember>> siblings = new ConcurrentHashMap<>(); private volatile DirectProcessor<ClusterMembershipEvent> membershipEventsProcessor = DirectProcessor.create(); private volatile DirectProcessor<ClusterMembershipEvent> leadershipEventsProcessor = DirectProcessor.create(); StubbedKubeExecutors(String localMemberId) { this.localMemberId = localMemberId; } @Override public boolean isInLeaderElectionProcess() { return inLeaderElectionProcess; } @Override public boolean isLeader() { return localLeader; } @Override public boolean joinLeaderElectionProcess() { if (inLeaderElectionProcess) { return false; } this.inLeaderElectionProcess = true; return true; } @Override public void leaveLeaderElectionProcess() { if (!inLeaderElectionProcess) { return; } this.localLeadershipRevision = ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder() .withCurrent(ClusterMemberLeadership.newBuilder() .withMemberId(localMemberId) .withLeadershipState(ClusterMemberLeadershipState.Disabled) .build() ) .withCode("testing") .withMessage("Called: leaveLeaderElectionProcess") .withRevision(leadershipRevisionIdx.getAndIncrement()) .withTimestamp(System.currentTimeMillis()) .build(); if (localLeader) { localLeader = false; membershipEventsProcessor.onNext(ClusterMembershipEvent.leaderLost(localLeadershipRevision)); } else { membershipEventsProcessor.onNext(ClusterMembershipEvent.localLeftElection(localLeadershipRevision)); } } @Override public Flux<ClusterMembershipEvent> watchLeaderElectionProcessUpdates() { return Flux.defer(() -> { logger.info("Resubscribing to the leader election event stream..."); return leadershipEventsProcessor; }); } @Override public Mono<ClusterMembershipRevision<ClusterMember>> getMemberById(String memberId) { if (memberId.equals(this.localMemberId)) { return Mono.just(localMemberRevision); } ClusterMembershipRevision<ClusterMember> sibling = siblings.get(memberId); return sibling == null ? Mono.error(new IllegalArgumentException("Sibling not found: " + memberId)) : Mono.just(sibling); } @Override public Mono<ClusterMembershipRevision<ClusterMember>> createLocal(ClusterMembershipRevision<ClusterMember> localMemberRevision) { return handleMemberUpdate(() -> { Preconditions.checkState(firstRegistration, "Use updateLocal for the updates"); this.localMemberRevision = localMemberRevision.toBuilder().withRevision(memberRevisionIdx.getAndIncrement()).build(); this.firstRegistration = false; return Mono.just(this.localMemberRevision); }); } @Override public Mono<ClusterMembershipRevision<ClusterMember>> updateLocal(ClusterMembershipRevision<ClusterMember> localMemberRevision) { return handleMemberUpdate(() -> { Preconditions.checkState(!firstRegistration, "Use createLocal for the first time"); this.localMemberRevision = localMemberRevision.toBuilder().withRevision(memberRevisionIdx.getAndIncrement()).build(); return Mono.just(this.localMemberRevision); }); } @Override public Mono<Void> removeMember(String memberId) { return handleMemberUpdate(() -> { if (memberId.equals(this.localMemberId)) { this.firstRegistration = true; } else { ClusterMembershipRevision<ClusterMember> removed = siblings.remove(memberId); membershipEventsProcessor.onNext(ClusterMembershipEvent.memberRemovedEvent(removed)); } return Mono.empty(); }); } private <T> Mono<T> handleMemberUpdate(Supplier<Mono<T>> supplier) { return Mono.defer(() -> { if (onMembershipUpdateError != null && onMembershipUpdateErrorCount > 0) { onMembershipUpdateErrorCount--; return Mono.error(onMembershipUpdateError); } return supplier.get(); }); } @Override public Flux<ClusterMembershipEvent> watchMembershipEvents() { return Flux.defer(() -> { logger.info("Resubscribing to the membership event stream..."); return membershipEventsProcessor; }); } void breakMembershipEventSource() { membershipEventsProcessor.onError(new RuntimeException("Simulated membership watch error")); membershipEventsProcessor = DirectProcessor.create(); await().until(() -> membershipEventsProcessor.hasDownstreams()); } void completeMembershipEventSource() { membershipEventsProcessor.onComplete(); membershipEventsProcessor = DirectProcessor.create(); await().until(() -> membershipEventsProcessor.hasDownstreams()); } void addOrUpdateSibling(ClusterMembershipRevision<ClusterMember> siblingRevision) { String siblingId = siblingRevision.getCurrent().getMemberId(); boolean update = siblings.containsKey(siblingId); siblings.put(siblingId, siblingRevision); membershipEventsProcessor.onNext(update ? ClusterMembershipEvent.memberUpdatedEvent(siblingRevision) : ClusterMembershipEvent.memberAddedEvent(siblingRevision) ); } void removeSibling(String siblingId) { if (!siblings.containsKey(siblingId)) { return; } ClusterMembershipRevision<ClusterMember> removed = siblings.remove(siblingId); membershipEventsProcessor.onNext(ClusterMembershipEvent.memberRemovedEvent(removed)); } boolean isFailingOnMembershipUpdate() { return onMembershipUpdateErrorCount > 0; } void failOnMembershipUpdate(RuntimeException cause, int count) { onMembershipUpdateError = cause; onMembershipUpdateErrorCount = count; } void doNotFailOnMembershipUpdate() { onMembershipUpdateErrorCount = 0; } void emitLeadershipEvent(LeaderElectionChangeEvent event) { if (event.getChangeType() == LeaderElectionChangeEvent.ChangeType.LeaderElected) { if (event.getLeadershipRevision().getCurrent().getMemberId().equals(localMemberId)) { localLeader = true; localLeadershipRevision = event.getLeadershipRevision(); } else { localLeader = false; } } leadershipEventsProcessor.onNext(event); } void breakLeadershipEventSource() { leadershipEventsProcessor.onError(new RuntimeException("Simulated leadership watch error")); leadershipEventsProcessor = DirectProcessor.create(); await().until(() -> leadershipEventsProcessor.hasDownstreams()); } void completeLeadershipEventSource() { leadershipEventsProcessor.onComplete(); leadershipEventsProcessor = DirectProcessor.create(); await().until(() -> leadershipEventsProcessor.hasDownstreams()); } }
433
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector/KubeClusterMembershipConnectorTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector; import java.time.Duration; import java.util.function.Supplier; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership; import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipChangeEvent; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipSnapshotEvent; import com.netflix.titus.api.clustermembership.model.event.LeaderElectionChangeEvent; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.archaius2.Archaius2Ext; import com.netflix.titus.testkit.model.clustermembership.ClusterMemberGenerator; import com.netflix.titus.testkit.rx.TitusRxSubscriber; import org.junit.After; import org.junit.Before; import org.junit.Test; import static com.jayway.awaitility.Awaitility.await; import static com.netflix.titus.testkit.model.clustermembership.ClusterMemberGenerator.activeClusterMember; import static com.netflix.titus.testkit.model.clustermembership.ClusterMemberGenerator.clusterMemberRegistrationRevision; import static com.netflix.titus.testkit.model.clustermembership.ClusterMemberGenerator.clusterMemberUpdateRevision; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class KubeClusterMembershipConnectorTest { private static final Duration TIMEOUT = Duration.ofSeconds(30); private static final ClusterMember LOCAL_MEMBER_UNREGISTERED = activeClusterMember("local").toBuilder() .withRegistered(false) .build(); private final TitusRuntime titusRuntime = TitusRuntimes.internal(); private final KubeClusterMembershipConfiguration configuration = Archaius2Ext.newConfiguration(KubeClusterMembershipConfiguration.class, "titus.ext.kube.reRegistrationIntervalMs", "100" ); private final StubbedKubeExecutors kubeExecutors = new StubbedKubeExecutors(LOCAL_MEMBER_UNREGISTERED.getMemberId()); private KubeClusterMembershipConnector connector; private TitusRxSubscriber<ClusterMembershipEvent> connectorEvents = new TitusRxSubscriber<>(); @Before public void setUp() { connector = new KubeClusterMembershipConnector(LOCAL_MEMBER_UNREGISTERED, kubeExecutors, kubeExecutors, configuration, titusRuntime); connector.membershipChangeEvents().subscribe(connectorEvents); // Initial sequence common for all tests assertThat(connector.getLocalClusterMemberRevision().getCurrent()).isEqualTo(LOCAL_MEMBER_UNREGISTERED); ClusterMembershipEvent snapshotEvent = connectorEvents.takeNext(); assertThat(snapshotEvent).isInstanceOf(ClusterMembershipSnapshotEvent.class); } @After public void tearDown() throws InterruptedException { connector.shutdown(); } @Test public void testRegistration() throws InterruptedException { long revision1 = connector.getLocalClusterMemberRevision().getRevision(); // First registration long revision2 = doRegister().getRevision(); // Re-registration long revision3 = doRegister().getRevision(); assertThat(revision2).isGreaterThan(revision1); assertThat(revision3).isGreaterThan(revision2); } @Test public void testUnregistration() throws InterruptedException { // First cycle doRegister(); doUnregister(); // Second cycle doRegister(); doUnregister(); } @Test public void testRegistrationConnectionErrorInRegistrationRequest() throws InterruptedException { kubeExecutors.failOnMembershipUpdate(new RuntimeException("Simulated membership update error"), 1); try { connector.register(ClusterMemberGenerator::clusterMemberRegistrationRevision).block(); fail("Failure expected"); } catch (Exception ignore) { } doRegister(); } @Test public void testRegistrationConnectionErrorRecoveryInReconciler() throws InterruptedException { doRegister(); kubeExecutors.failOnMembershipUpdate(new RuntimeException("Simulated membership update error"), 1); await().until(() -> !kubeExecutors.isFailingOnMembershipUpdate()); long now = System.currentTimeMillis(); ClusterMembershipChangeEvent event; while ((event = (ClusterMembershipChangeEvent) connectorEvents.takeNext(TIMEOUT)) != null) { if (event.getRevision().getTimestamp() > now) { return; } } fail("No re-registration observed in time"); } @Test public void testUnregistrationConnectionError() throws InterruptedException { doRegister(); kubeExecutors.failOnMembershipUpdate(new RuntimeException("Simulated membership update error"), Integer.MAX_VALUE); try { connector.unregister(ClusterMemberGenerator::clusterMemberUnregistrationRevision).block(); fail("Failure expected"); } catch (Exception ignore) { } kubeExecutors.doNotFailOnMembershipUpdate(); doUnregister(); } @Test public void testSiblingAdded() throws InterruptedException { // Add some ClusterMembershipRevision<ClusterMember> sibling1 = doAddSibling("sibling1"); ClusterMembershipRevision<ClusterMember> sibling2 = doAddSibling("sibling2"); // Make updates doUpdateSibling(sibling1); doUpdateSibling(sibling2); // Now remove all siblings doRemoveSibling(sibling1); doRemoveSibling(sibling2); } @Test public void testMembershipEventStreamConnectionError() throws InterruptedException { kubeExecutors.breakMembershipEventSource(); ClusterMembershipRevision<ClusterMember> sibling1 = doAddSibling("sibling1"); kubeExecutors.breakMembershipEventSource(); doUpdateSibling(sibling1); } @Test public void testMembershipEventStreamCompleted() throws InterruptedException { kubeExecutors.completeMembershipEventSource(); ClusterMembershipRevision<ClusterMember> sibling1 = doAddSibling("sibling1"); kubeExecutors.completeMembershipEventSource(); doUpdateSibling(sibling1); } @Test public void testLeaderElection() throws InterruptedException { // Join leader election process joinLeaderElectionProcess(); // Become leader electLocalAsLeader(); // Stop being leader stopBeingLeader(); } @Test public void testDiscoveryOfSiblingLeader() throws InterruptedException { ClusterMemberLeadership sibling = electSiblingAsLeader(); ClusterMembershipRevision<ClusterMemberLeadership> leader = connector.findCurrentLeader().orElseThrow(() -> new IllegalStateException("Leader not found")); assertThat(leader.getCurrent()).isEqualTo(sibling); } @Test public void testJoinAndLeaveLeaderElectionProcess() throws InterruptedException { // Join leader election process joinLeaderElectionProcess(); // Leave leader election process leaveLeaderElectionProcess(); } @Test public void testLeadershipEventStreamConnectionError() throws InterruptedException { kubeExecutors.breakLeadershipEventSource(); electSiblingAsLeader(); kubeExecutors.breakLeadershipEventSource(); electLocalAsLeader(); } @Test public void testLeadershipEventStreamConnectionCompleted() throws InterruptedException { kubeExecutors.completeLeadershipEventSource(); electSiblingAsLeader(); kubeExecutors.completeLeadershipEventSource(); electLocalAsLeader(); } @Test public void testStaleMemberRemoval() throws InterruptedException { ClusterMembershipRevision<ClusterMember> stale = clusterMemberRegistrationRevision(activeClusterMember("staleSibling")).toBuilder() .withTimestamp(1) .build(); kubeExecutors.addOrUpdateSibling(stale); // Now add normal doAddSibling("sibling1"); assertThat(connector.getClusterMemberSiblings()).containsKey("sibling1"); await().until(() -> kubeExecutors.getMemberById("staleSibling").map(r -> "staleSibling").onErrorReturn("null").block().equals("null")); } private ClusterMembershipRevision<ClusterMember> doRegister() throws InterruptedException { ClusterMembershipRevision<ClusterMember> newRevision = doRegistrationChange(() -> connector.register(ClusterMemberGenerator::clusterMemberRegistrationRevision).block()); assertThat(connector.getLocalClusterMemberRevision().getCurrent().isRegistered()).isTrue(); return newRevision; } private ClusterMembershipRevision<ClusterMember> doUnregister() throws InterruptedException { ClusterMembershipRevision<ClusterMember> newRevision = doRegistrationChange(() -> connector.unregister(ClusterMemberGenerator::clusterMemberUnregistrationRevision).block()); assertThat(connector.getLocalClusterMemberRevision().getCurrent().isRegistered()).isFalse(); return newRevision; } private ClusterMembershipRevision<ClusterMember> doRegistrationChange(Supplier<ClusterMembershipRevision<ClusterMember>> action) throws InterruptedException { long now = titusRuntime.getClock().wallTime(); ClusterMembershipRevision<ClusterMember> newRevision = action.get(); assertThat(newRevision.getTimestamp()).isGreaterThanOrEqualTo(now); assertThat(connector.getLocalClusterMemberRevision()).isEqualTo(newRevision); ClusterMembershipEvent registrationEvent1 = connectorEvents.takeNext(TIMEOUT); assertThat(registrationEvent1).isInstanceOf(ClusterMembershipChangeEvent.class); assertThat(((ClusterMembershipChangeEvent) registrationEvent1).getChangeType()).isEqualTo(ClusterMembershipChangeEvent.ChangeType.Updated); return newRevision; } private ClusterMembershipRevision<ClusterMember> doAddSibling(String siblingId) throws InterruptedException { ClusterMembershipRevision<ClusterMember> revision = clusterMemberRegistrationRevision(activeClusterMember(siblingId)); return doAddOrUpdateSibling(revision, ClusterMembershipChangeEvent.ChangeType.Added); } private ClusterMembershipRevision<ClusterMember> doUpdateSibling(ClusterMembershipRevision<ClusterMember> revision) throws InterruptedException { return doAddOrUpdateSibling(clusterMemberUpdateRevision(revision), ClusterMembershipChangeEvent.ChangeType.Updated); } private ClusterMembershipRevision<ClusterMember> doAddOrUpdateSibling(ClusterMembershipRevision<ClusterMember> revision, ClusterMembershipChangeEvent.ChangeType changeType) throws InterruptedException { String siblingId = revision.getCurrent().getMemberId(); kubeExecutors.addOrUpdateSibling(revision); ClusterMembershipEvent event = connectorEvents.takeNext(TIMEOUT); assertThat(event).isInstanceOf(ClusterMembershipChangeEvent.class); assertThat(((ClusterMembershipChangeEvent) event).getChangeType()).isEqualTo(changeType); assertThat(((ClusterMembershipChangeEvent) event).getRevision()).isEqualTo(revision); assertThat(connector.getClusterMemberSiblings()).containsKey(siblingId); return connector.getClusterMemberSiblings().get(siblingId); } private void doRemoveSibling(ClusterMembershipRevision<ClusterMember> revision) throws InterruptedException { kubeExecutors.removeSibling(revision.getCurrent().getMemberId()); ClusterMembershipEvent event = connectorEvents.takeNext(TIMEOUT); assertThat(event).isInstanceOf(ClusterMembershipChangeEvent.class); assertThat(((ClusterMembershipChangeEvent) event).getChangeType()).isEqualTo(ClusterMembershipChangeEvent.ChangeType.Removed); } private void joinLeaderElectionProcess() throws InterruptedException { connector.joinLeadershipGroup().block(); LeaderElectionChangeEvent electionEvent = takeLeaderElectionEvent(LeaderElectionChangeEvent.ChangeType.LocalJoined); assertThat(electionEvent.getLeadershipRevision().getCurrent().getLeadershipState()).isEqualTo(ClusterMemberLeadershipState.NonLeader); assertThat(connector.getLocalLeadershipRevision().getCurrent().getLeadershipState()).isEqualTo(ClusterMemberLeadershipState.NonLeader); } private void electLocalAsLeader() throws InterruptedException { kubeExecutors.emitLeadershipEvent(ClusterMembershipEvent.leaderElected(ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder() .withCurrent(ClusterMemberLeadership.newBuilder() .withMemberId(LOCAL_MEMBER_UNREGISTERED.getMemberId()) .withLeadershipState(ClusterMemberLeadershipState.Leader) .build() ) .build()) ); LeaderElectionChangeEvent electionEvent = takeLeaderElectionEvent(LeaderElectionChangeEvent.ChangeType.LeaderElected); assertThat(electionEvent.getLeadershipRevision().getCurrent().getLeadershipState()).isEqualTo(ClusterMemberLeadershipState.Leader); } private void leaveLeaderElectionProcess() throws InterruptedException { connector.leaveLeadershipGroup(true).block(); LeaderElectionChangeEvent electionEvent = takeLeaderElectionEvent(LeaderElectionChangeEvent.ChangeType.LocalLeft); assertThat(electionEvent.getLeadershipRevision().getCurrent().getLeadershipState()).isEqualTo(ClusterMemberLeadershipState.Disabled); assertThat(connector.getLocalLeadershipRevision().getCurrent().getLeadershipState()).isEqualTo(ClusterMemberLeadershipState.Disabled); } private void stopBeingLeader() throws InterruptedException { connector.leaveLeadershipGroup(false).block(); LeaderElectionChangeEvent electionEvent = takeLeaderElectionEvent(LeaderElectionChangeEvent.ChangeType.LeaderLost); assertThat(electionEvent.getLeadershipRevision().getCurrent().getLeadershipState()).isEqualTo(ClusterMemberLeadershipState.Disabled); assertThat(connector.getLocalLeadershipRevision().getCurrent().getLeadershipState()).isEqualTo(ClusterMemberLeadershipState.Disabled); } private ClusterMemberLeadership electSiblingAsLeader() throws InterruptedException { ClusterMemberLeadership sibling = ClusterMemberLeadership.newBuilder() .withMemberId("sibling1") .withLeadershipState(ClusterMemberLeadershipState.Leader) .build(); kubeExecutors.emitLeadershipEvent(ClusterMembershipEvent.leaderElected(ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder() .withCurrent(sibling) .build() )); LeaderElectionChangeEvent electionEvent = takeLeaderElectionEvent(LeaderElectionChangeEvent.ChangeType.LeaderElected); assertThat(electionEvent.getLeadershipRevision().getCurrent().getLeadershipState()).isEqualTo(ClusterMemberLeadershipState.Leader); return sibling; } private LeaderElectionChangeEvent takeLeaderElectionEvent(LeaderElectionChangeEvent.ChangeType changeType) throws InterruptedException { ClusterMembershipEvent event = connectorEvents.takeNext(TIMEOUT); assertThat(event).isInstanceOf(LeaderElectionChangeEvent.class); LeaderElectionChangeEvent electionEvent = (LeaderElectionChangeEvent) event; assertThat(electionEvent.getChangeType()).isEqualTo(changeType); return electionEvent; } }
434
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/AbstractKubeLeaderElectionExecutorTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport; import java.time.Duration; import java.util.ArrayList; import java.util.List; import com.google.common.base.Preconditions; import com.netflix.titus.api.clustermembership.model.event.LeaderElectionChangeEvent; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.ext.kube.clustermembership.connector.KubeLeaderElectionExecutor; import com.netflix.titus.testkit.rx.TitusRxSubscriber; import org.junit.After; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; public abstract class AbstractKubeLeaderElectionExecutorTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); public static final Duration KUBE_TIMEOUT = Duration.ofSeconds(500); protected static final Duration LEASE_DURATION = Duration.ofSeconds(1); protected final TitusRuntime titusRuntime = TitusRuntimes.internal(); protected final String clusterName = newClusterId(); private final List<MemberHolder> memberHolders = new ArrayList<>(); @After public void tearDown() { memberHolders.forEach(MemberHolder::close); } protected abstract KubeLeaderElectionExecutor getKubeLeaderElectionExecutor(String memberId); @Test public void testLeaderElection() { // Join first member MemberHolder member1 = new MemberHolder(); joinLeaderElectionProcess(member1); awaitBeingLeader(member1); LeaderElectionChangeEvent leaderSelectedEvent = member1.takeNextEvent(); assertThat(leaderSelectedEvent.getLeadershipRevision().getCurrent().getMemberId()).isEqualTo(member1.getMemberId()); assertThat(leaderSelectedEvent.getChangeType()).isEqualTo(LeaderElectionChangeEvent.ChangeType.LeaderElected); // Join second member MemberHolder member2 = new MemberHolder(); joinLeaderElectionProcess(member2); // Leave leader election process. member1.getExecutor().leaveLeaderElectionProcess(); await().until(() -> { LeaderElectionChangeEvent event = member1.takeNextEvent(); return event != null && event.getChangeType() == LeaderElectionChangeEvent.ChangeType.LeaderLost; }); // Check that second member takes over leadership awaitBeingLeader(member2); } private void joinLeaderElectionProcess(MemberHolder member) { assertThat(member.getExecutor().joinLeaderElectionProcess()).isTrue(); assertThat(member.getExecutor().isInLeaderElectionProcess()).isTrue(); } private void awaitBeingLeader(MemberHolder member) { await().until(() -> member.getExecutor().isLeader()); } protected String newClusterId() { return "junit-cluster-" + System.getenv("USER") + "-" + System.currentTimeMillis(); } private String newMemberId() { return "junit-member-" + System.getenv("USER") + "-" + System.currentTimeMillis(); } private class MemberHolder { private final String memberId; private final KubeLeaderElectionExecutor executor; private final TitusRxSubscriber<LeaderElectionChangeEvent> eventSubscriber = new TitusRxSubscriber<>(); MemberHolder() { this.memberId = newMemberId(); this.executor = getKubeLeaderElectionExecutor(memberId); memberHolders.add(this); executor.watchLeaderElectionProcessUpdates() .map(event -> { logger.info("[{}] Event stream update: {}", memberId, event); if (event instanceof LeaderElectionChangeEvent) { return event; } throw new IllegalStateException("Unexpected event in the stream: " + event); }) .cast(LeaderElectionChangeEvent.class) .subscribe(eventSubscriber); assertThat(executor.isInLeaderElectionProcess()).isFalse(); } String getMemberId() { return memberId; } KubeLeaderElectionExecutor getExecutor() { return executor; } LeaderElectionChangeEvent takeNextEvent() { try { return Preconditions.checkNotNull(eventSubscriber.takeNext(KUBE_TIMEOUT)); } catch (InterruptedException e) { throw new IllegalStateException(e); } } void close() { executor.leaveLeaderElectionProcess(); } } }
435
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/AbstractKubeMembershipExecutorTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport; import java.util.ArrayList; import java.util.List; import com.netflix.titus.api.clustermembership.connector.ClusterMembershipConnectorException; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipChangeEvent; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent; import com.netflix.titus.common.util.ExceptionExt; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.ext.kube.clustermembership.connector.KubeMembershipExecutor; import com.netflix.titus.testkit.rx.TitusRxSubscriber; import org.junit.After; import org.junit.Before; import org.junit.Test; import static com.netflix.titus.ext.kube.clustermembership.connector.transport.AbstractKubeLeaderElectionExecutorTest.KUBE_TIMEOUT; import static com.netflix.titus.testkit.model.clustermembership.ClusterMemberGenerator.activeClusterMember; import static com.netflix.titus.testkit.model.clustermembership.ClusterMemberGenerator.clusterMemberRegistrationRevision; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public abstract class AbstractKubeMembershipExecutorTest { private final TitusRxSubscriber<ClusterMembershipEvent> eventSubscriber = new TitusRxSubscriber<>(); private final List<String> createdMemberIds = new ArrayList<>(); private KubeMembershipExecutor executor; @Before public void setUp() { this.executor = getExecutor(); executor.watchMembershipEvents().subscribe(eventSubscriber); } @After public void tearDown() { ReactorExt.safeDispose(eventSubscriber); createdMemberIds.forEach(memberId -> ExceptionExt.silent(() -> executor.removeMember(memberId).block(KUBE_TIMEOUT))); } protected abstract KubeMembershipExecutor getExecutor(); @Test(timeout = 30_000) public void testCreateAndGetNewMember() throws InterruptedException { ClusterMembershipRevision<ClusterMember> revision = newMemberRevision(); String memberId = revision.getCurrent().getMemberId(); ClusterMembershipRevision<ClusterMember> result = executor.createLocal(revision).block(); assertThat(result).isNotNull(); assertThat(result.getCurrent().getMemberId()).isEqualTo(memberId); assertThat(result.getRevision()).isNotNull(); expectClusterMembershipChangeEvent(result, ClusterMembershipChangeEvent.ChangeType.Added); // Now get it ClusterMembershipRevision<ClusterMember> fetched = executor.getMemberById(memberId).block(); assertThat(fetched).isEqualTo(result); } @Test(timeout = 30_000) public void testUpdateExistingMember() throws InterruptedException { ClusterMembershipRevision<ClusterMember> initialRevision = newMemberRevision(); ClusterMembershipRevision<ClusterMember> initialResponse = executor.createLocal(initialRevision).block(); ClusterMembershipRevision<ClusterMember> secondResponse = executor.updateLocal(initialResponse.toBuilder().withCode("update").build()).block(); assertThat(secondResponse).isNotNull(); assertThat(secondResponse.getCode()).isEqualTo("update"); expectClusterMembershipChangeEvent(initialResponse, ClusterMembershipChangeEvent.ChangeType.Added); expectClusterMembershipChangeEvent(secondResponse, ClusterMembershipChangeEvent.ChangeType.Updated); } @Test public void testRemoveMember() throws InterruptedException { ClusterMembershipRevision<ClusterMember> revision = newMemberRevision(); String memberId = revision.getCurrent().getMemberId(); ClusterMembershipRevision<ClusterMember> result = executor.createLocal(revision).block(); executor.removeMember(memberId).block(); try { ClusterMembershipRevision<ClusterMember> retrieved = executor.getMemberById(memberId).block(); fail("Found removed member: {}", retrieved); } catch (ClusterMembershipConnectorException e) { assertThat(e.getMessage()).contains("not found"); } catch (Exception e) { assertThat(KubeUtils.is4xx(e)).isTrue(); } expectClusterMembershipChangeEvent(result, ClusterMembershipChangeEvent.ChangeType.Added); assertThat(findNextMemberEvent(memberId)).isNotNull(); } private void expectClusterMembershipChangeEvent(ClusterMembershipRevision<ClusterMember> revision, ClusterMembershipChangeEvent.ChangeType changeType) throws InterruptedException { ClusterMembershipChangeEvent memberEvent = findNextMemberEvent(revision.getCurrent().getMemberId()); assertThat(memberEvent.getChangeType()).isEqualTo(changeType); assertThat(memberEvent.getRevision()).isEqualTo(revision); } private ClusterMembershipChangeEvent findNextMemberEvent(String memberId) throws InterruptedException { while (true) { ClusterMembershipEvent event = eventSubscriber.takeNext(KUBE_TIMEOUT); assertThat(event).isNotNull(); if (event instanceof ClusterMembershipChangeEvent) { ClusterMembershipChangeEvent memberEvent = (ClusterMembershipChangeEvent) event; if (memberEvent.getRevision().getCurrent().getMemberId().equals(memberId)) { return memberEvent; } } } } private String newMemberId() { String memberId = "junit-member-" + System.getenv("USER") + "-" + System.currentTimeMillis(); createdMemberIds.add(memberId); return memberId; } private ClusterMembershipRevision<ClusterMember> newMemberRevision() { return clusterMemberRegistrationRevision(activeClusterMember(newMemberId()).toBuilder().withRegistered(false).build()); } }
436
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector/transport
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io/Fabric8IOKubeMembershipExecutorTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io; import com.netflix.titus.ext.kube.clustermembership.connector.KubeMembershipExecutor; import com.netflix.titus.ext.kube.clustermembership.connector.transport.AbstractKubeMembershipExecutorTest; import com.netflix.titus.testkit.junit.category.RemoteIntegrationTest; import org.junit.ClassRule; import org.junit.experimental.categories.Category; @Category(RemoteIntegrationTest.class) public class Fabric8IOKubeMembershipExecutorTest extends AbstractKubeMembershipExecutorTest { @ClassRule public static final Fabric8IOKubeExternalResource KUBE_RESOURCE = new Fabric8IOKubeExternalResource(); private final Fabric8IOKubeMembershipExecutor executor = new Fabric8IOKubeMembershipExecutor(KUBE_RESOURCE.getClient(), "junit"); @Override protected KubeMembershipExecutor getExecutor() { return executor; } }
437
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector/transport
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io/Fabric8IOKubeLeaderElectionExecutorTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io; import com.netflix.titus.ext.kube.clustermembership.connector.KubeLeaderElectionExecutor; import com.netflix.titus.ext.kube.clustermembership.connector.transport.AbstractKubeLeaderElectionExecutorTest; import com.netflix.titus.testkit.junit.category.RemoteIntegrationTest; import org.junit.ClassRule; import org.junit.experimental.categories.Category; @Category(RemoteIntegrationTest.class) public class Fabric8IOKubeLeaderElectionExecutorTest extends AbstractKubeLeaderElectionExecutorTest { @ClassRule public static final Fabric8IOKubeExternalResource KUBE_RESOURCE = new Fabric8IOKubeExternalResource(); @Override protected KubeLeaderElectionExecutor getKubeLeaderElectionExecutor(String memberId) { return new Fabric8IOKubeLeaderElectionExecutor( KUBE_RESOURCE.getClient(), "default", clusterName, LEASE_DURATION, memberId, titusRuntime ); } }
438
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector/transport
Create_ds/titus-control-plane/titus-common-ext/kube/src/test/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io/Fabric8IOKubeExternalResource.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; import org.junit.rules.ExternalResource; public class Fabric8IOKubeExternalResource extends ExternalResource { private NamespacedKubernetesClient client; @Override protected void before() { String kubeServer = System.getenv("KUBE_API_SERVER_URL"); if (kubeServer == null) { this.client = new DefaultKubernetesClient(); } else { Config config = new ConfigBuilder() .withMasterUrl(kubeServer) .build(); this.client = new DefaultKubernetesClient(config); } } @Override protected void after() { if (client != null) { client.close(); } } public NamespacedKubernetesClient getClient() { return client; } }
439
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/KubeContext.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector; import com.netflix.titus.common.runtime.TitusRuntime; public class KubeContext { private final KubeMembershipExecutor kubeMembershipExecutor; private final KubeLeaderElectionExecutor kubeLeaderElectionExecutor; private final TitusRuntime titusRuntime; KubeContext(KubeMembershipExecutor kubeMembershipExecutor, KubeLeaderElectionExecutor kubeLeaderElectionExecutor, TitusRuntime titusRuntime) { this.kubeMembershipExecutor = kubeMembershipExecutor; this.kubeLeaderElectionExecutor = kubeLeaderElectionExecutor; this.titusRuntime = titusRuntime; } public KubeMembershipExecutor getKubeMembershipExecutor() { return kubeMembershipExecutor; } public KubeLeaderElectionExecutor getKubeLeaderElectionExecutor() { return kubeLeaderElectionExecutor; } public TitusRuntime getTitusRuntime() { return titusRuntime; } }
440
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/KubeClusterMembershipStateReconciler.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.function.Function; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.time.Clock; import com.netflix.titus.ext.kube.clustermembership.connector.action.KubeLeaderElectionActions; import com.netflix.titus.ext.kube.clustermembership.connector.action.KubeRegistrationActions; import reactor.core.publisher.Mono; class KubeClusterMembershipStateReconciler implements Function<KubeClusterState, List<Mono<Function<KubeClusterState, KubeClusterState>>>> { private final KubeClusterMembershipConfiguration configuration; private final Clock clock; private final TitusRuntime titusRuntime; private final KubeContext context; private final Id reconcilerMetricId; private final Registry registry; private final Random random; KubeClusterMembershipStateReconciler(KubeContext context, KubeClusterMembershipConfiguration configuration) { this.context = context; this.configuration = configuration; this.titusRuntime = context.getTitusRuntime(); this.clock = titusRuntime.getClock(); this.random = new Random(System.nanoTime()); this.registry = titusRuntime.getRegistry(); this.reconcilerMetricId = registry.createId(KubeMetrics.KUBE_METRIC_ROOT + "reconciler"); } @Override public List<Mono<Function<KubeClusterState, KubeClusterState>>> apply(KubeClusterState kubeClusterState) { // Check leader election process. boolean inLeaderElectionProcess = context.getKubeLeaderElectionExecutor().isInLeaderElectionProcess(); if (kubeClusterState.isInLeaderElectionProcess()) { if (!inLeaderElectionProcess) { return Collections.singletonList(withMetrics( "joinLeadershipGroup", KubeLeaderElectionActions.createJoinLeadershipGroupAction(context) )); } } else { if (inLeaderElectionProcess) { return Collections.singletonList(withMetrics( "leaveLeadershipGroup", KubeLeaderElectionActions.createLeaveLeadershipGroupAction(context, false) )); } } // Refresh registration data so it does not look stale to other cluster members if (kubeClusterState.isMustRegister()) { if (!kubeClusterState.isRegistered() || clock.isPast(kubeClusterState.getLocalMemberRevision().getTimestamp() + configuration.getReRegistrationIntervalMs())) { Mono<Function<KubeClusterState, KubeClusterState>> action = KubeRegistrationActions.registerLocal(context, kubeClusterState, clusterMember -> ClusterMembershipRevision.<ClusterMember>newBuilder() .withCurrent(clusterMember) .withTimestamp(titusRuntime.getClock().wallTime()) .withCode("reregistered") .withMessage("Registration update") .build()); return Collections.singletonList(withMetrics("register", action)); } } // Check for stale data long cleanupThreshold = applyJitter(configuration.getRegistrationCleanupThresholdMs(), 30); Optional<ClusterMembershipRevision<ClusterMember>> staleRegistration = kubeClusterState.getStaleClusterMemberSiblings().values().stream() .filter(s -> clock.isPast(s.getTimestamp() + cleanupThreshold)) .findFirst(); if (staleRegistration.isPresent()) { String staleMemberId = staleRegistration.get().getCurrent().getMemberId(); return Collections.singletonList(withMetrics("removeStaleMember", KubeRegistrationActions.removeStaleRegistration(context, staleMemberId))); } return Collections.emptyList(); } private <T> Mono<T> withMetrics(String name, Mono<T> action) { return action .doOnSuccess(v -> registry.counter(reconcilerMetricId.withTag("action", name)).increment()) .doOnError(error -> registry.counter(reconcilerMetricId .withTag("action", name) .withTag("error", error.getClass().getSimpleName()) ).increment()); } private long applyJitter(long value, int percent) { return ((100 + random.nextInt(percent)) * value) / 100; } }
441
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/KubeClusterMembershipConfiguration.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; import static com.netflix.titus.ext.kube.clustermembership.connector.KubeClusterMembershipConfiguration.PREFIX; @Configuration(prefix = PREFIX) public interface KubeClusterMembershipConfiguration { String PREFIX = "titus.ext.kube"; String getKubeApiServerUri(); /** * @return the path to the kubeconfig file */ @DefaultValue("/run/kubernetes/config") String getKubeConfigPath(); @DefaultValue("titus") String getNamespace(); @DefaultValue("titus") String getClusterName(); @DefaultValue("10") long getReconcilerQuickCycleMs(); @DefaultValue("100") long getReconcilerLongCycleMs(); @DefaultValue("30000") long getReRegistrationIntervalMs(); /** * Each cluster member periodically updates its registration entry. As the data in Kubernetes do not have * TTL associated with them, an entry belonging to a terminated node will stay there until it is removed by * the garbage collection process. This property defines a threshold, above which registration entries are * regarded as stale and not advertised. */ @DefaultValue("180000") long getRegistrationStaleThresholdMs(); /** * Data staleness threshold above which the registration data are removed. */ @DefaultValue("180000") long getRegistrationCleanupThresholdMs(); @DefaultValue("500") long getKubeReconnectIntervalMs(); @DefaultValue("10000") long getLeaseDurationMs(); }
442
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/KubeLeaderElectionExecutor.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent; import reactor.core.publisher.Flux; public interface KubeLeaderElectionExecutor { boolean isInLeaderElectionProcess(); boolean isLeader(); boolean joinLeaderElectionProcess(); void leaveLeaderElectionProcess(); Flux<ClusterMembershipEvent> watchLeaderElectionProcessUpdates(); }
443
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/KubeClusterMembershipConnectorComponent.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector; import java.time.Duration; import com.netflix.titus.api.clustermembership.connector.ClusterMembershipConnector; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.common.environment.MyEnvironment; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.archaius2.Archaius2Ext; import com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io.Fabric8IOKubeLeaderElectionExecutor; import com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io.Fabric8IOKubeMembershipExecutor; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConditionalOnProperty(name = "titus.ext.kube.enabled", havingValue = "true", matchIfMissing = true) public class KubeClusterMembershipConnectorComponent { public static final String LOCAL_MEMBER_INITIAL = "localMemberInitial"; @Bean public KubeClusterMembershipConfiguration getKubeClusterMembershipConfiguration(MyEnvironment environment) { return Archaius2Ext.newConfiguration(KubeClusterMembershipConfiguration.class, KubeClusterMembershipConfiguration.PREFIX, environment); } @Bean public KubeMembershipExecutor getKubeMembershipExecutor(KubeClusterMembershipConfiguration configuration, NamespacedKubernetesClient fabric8IOClient) { return new Fabric8IOKubeMembershipExecutor(fabric8IOClient, configuration.getNamespace()); } @Bean public KubeLeaderElectionExecutor getDefaultKubeLeaderElectionExecutor(KubeClusterMembershipConfiguration configuration, @Qualifier(LOCAL_MEMBER_INITIAL) ClusterMember initial, NamespacedKubernetesClient fabric8IOClient, TitusRuntime titusRuntime) { return new Fabric8IOKubeLeaderElectionExecutor( fabric8IOClient, configuration.getNamespace(), configuration.getClusterName(), Duration.ofMillis(configuration.getLeaseDurationMs()), initial.getMemberId(), titusRuntime ); } @Bean public ClusterMembershipConnector getClusterMembershipConnector( KubeClusterMembershipConfiguration configuration, @Qualifier(LOCAL_MEMBER_INITIAL) ClusterMember initial, KubeMembershipExecutor membershipExecutor, KubeLeaderElectionExecutor leaderElectionExecutor, TitusRuntime titusRuntime) { return new KubeClusterMembershipConnector( initial, membershipExecutor, leaderElectionExecutor, configuration, titusRuntime ); } }
444
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/KubeMembershipExecutor.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public interface KubeMembershipExecutor { Mono<ClusterMembershipRevision<ClusterMember>> getMemberById(String memberId); Mono<ClusterMembershipRevision<ClusterMember>> createLocal(ClusterMembershipRevision<ClusterMember> localMemberRevision); Mono<ClusterMembershipRevision<ClusterMember>> updateLocal(ClusterMembershipRevision<ClusterMember> localMemberRevision); Mono<Void> removeMember(String memberId); Flux<ClusterMembershipEvent> watchMembershipEvents(); }
445
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/KubeMetrics.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector; public final class KubeMetrics { public static final String KUBE_METRIC_ROOT = "titus.clusterMembership.kubeConnector."; }
446
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/KubeClusterMembershipConnector.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector; import java.time.Duration; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import javax.annotation.PreDestroy; import javax.inject.Singleton; import com.netflix.titus.api.clustermembership.connector.ClusterMembershipConnector; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipChangeEvent; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent; import com.netflix.titus.api.clustermembership.model.event.LeaderElectionChangeEvent; import com.netflix.titus.common.framework.simplereconciler.OneOffReconciler; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.common.util.rx.ReactorRetriers; import com.netflix.titus.ext.kube.clustermembership.connector.action.KubeLeaderElectionActions; import com.netflix.titus.ext.kube.clustermembership.connector.action.KubeRegistrationActions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.SignalType; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; @Singleton public class KubeClusterMembershipConnector implements ClusterMembershipConnector { private static final Logger logger = LoggerFactory.getLogger(KubeClusterMembershipConnector.class); private static final Duration SHUTDOWN_TIMEOUT = Duration.ofMillis(500000); private final Scheduler scheduler; private final OneOffReconciler<KubeClusterState> reconciler; private final KubeContext context; private final Disposable membershipSubscription; private final Disposable leaderElectionSubscription; private final Disposable reconcilerEventsSubscription; public KubeClusterMembershipConnector(ClusterMember initial, KubeMembershipExecutor kubeMembershipExecutor, KubeLeaderElectionExecutor kubeLeaderElectionExecutor, KubeClusterMembershipConfiguration configuration, TitusRuntime titusRuntime) { this.scheduler = Schedulers.newSingle("ClusterMembershipReconciler"); this.context = new KubeContext(kubeMembershipExecutor, kubeLeaderElectionExecutor, titusRuntime); this.reconciler = OneOffReconciler.<KubeClusterState>newBuilder("LeaderElection") .withInitial(new KubeClusterState(initial, configuration, titusRuntime.getClock())) .withReconcilerActionsProvider(new KubeClusterMembershipStateReconciler(context, configuration)) .withQuickCycle(Duration.ofMillis(configuration.getReconcilerQuickCycleMs())) .withLongCycle(Duration.ofMillis(configuration.getReconcilerLongCycleMs())) .withScheduler(scheduler) .withTitusRuntime(titusRuntime) .build(); Duration reconnectInterval = Duration.ofMillis(configuration.getKubeReconnectIntervalMs()); this.membershipSubscription = kubeMembershipExecutor.watchMembershipEvents() .materialize().flatMap(signal -> { if(signal.getType() == SignalType.ON_NEXT) { return Mono.just(signal.get()); } if(signal.getType() == SignalType.ON_ERROR) { return Mono.error(signal.getThrowable()); } if(signal.getType() == SignalType.ON_COMPLETE) { return Mono.error(new IllegalStateException("watchMembershipEvents completed, and must be restarted")); } return Mono.empty(); }) .retryWhen(ReactorRetriers.reactorRetryer(e -> { logger.info("Reconnecting membership event stream from Kubernetes terminated with an error: {}", e.getMessage()); logger.debug("Stack trace", e); return Flux.interval(reconnectInterval).take(1); })) .subscribe( event -> { if (event instanceof ClusterMembershipChangeEvent) { reconciler.apply(currentState -> Mono.just(currentState.processMembershipEventStreamEvent((ClusterMembershipChangeEvent) event))) .subscribe( next -> logger.info("Processed Kubernetes event: {}", event), e -> logger.warn("Kubernetes event processing failure", e) ); } }, e -> logger.error("Unexpected error in the Kubernetes membership event stream", e), () -> logger.info("Membership Kubernetes event stream closed") ); this.leaderElectionSubscription = kubeLeaderElectionExecutor.watchLeaderElectionProcessUpdates() .materialize().flatMap(signal -> { if(signal.getType() == SignalType.ON_NEXT) { return Mono.just(signal.get()); } if(signal.getType() == SignalType.ON_ERROR) { return Mono.error(signal.getThrowable()); } if(signal.getType() == SignalType.ON_COMPLETE) { return Mono.error(new IllegalStateException("watchLeaderElectionProcessUpdates completed, and must be restarted")); } return Mono.empty(); }) .retryWhen(ReactorRetriers.reactorRetryer(e -> { logger.info("Reconnecting leadership event stream from Kubernetes terminated with an error: {}", e.getMessage()); logger.debug("Stack trace", e); return Flux.interval(reconnectInterval).take(1); })) .subscribe( event -> { if (event instanceof LeaderElectionChangeEvent) { reconciler.apply(currentState -> Mono.just(currentState.processLeaderElectionEventStreamEvent((LeaderElectionChangeEvent) event))) .subscribe( next -> logger.debug("Processed Kubernetes event: {}", event), e -> logger.warn("Kubernetes event processing failure", e) ); } }, e -> logger.error("Unexpected error in the Kubernetes membership event stream", e), () -> logger.info("Membership Kubernetes event stream closed") ); this.reconcilerEventsSubscription = this.reconciler.changes().subscribe( next -> logger.debug("Reconciler update: {}", next.getDeltaEvents()), e -> logger.warn("Reconciler event stream terminated with an error", e), () -> logger.warn("Reconciler event stream completed") ); } @PreDestroy public void shutdown() { reconciler.close().block(SHUTDOWN_TIMEOUT); ReactorExt.safeDispose(scheduler, membershipSubscription, leaderElectionSubscription, reconcilerEventsSubscription); } @Override public ClusterMembershipRevision<ClusterMember> getLocalClusterMemberRevision() { return reconciler.getCurrent().getLocalMemberRevision(); } @Override public Map<String, ClusterMembershipRevision<ClusterMember>> getClusterMemberSiblings() { return reconciler.getCurrent().getNotStaleClusterMemberSiblings(); } @Override public ClusterMembershipRevision<ClusterMemberLeadership> getLocalLeadershipRevision() { return reconciler.getCurrent().getLocalMemberLeadershipRevision(); } @Override public Optional<ClusterMembershipRevision<ClusterMemberLeadership>> findCurrentLeader() { return reconciler.getCurrent().findCurrentLeader(); } @Override public Mono<ClusterMembershipRevision<ClusterMember>> register(Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> selfUpdate) { return reconciler.apply(current -> KubeRegistrationActions.registerLocal(context, current, selfUpdate).map(f -> f.apply(current))) .map(KubeClusterState::getLocalMemberRevision); } @Override public Mono<ClusterMembershipRevision<ClusterMember>> unregister(Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> selfUpdate) { return reconciler.apply(current -> KubeRegistrationActions.unregisterLocal(context, current, selfUpdate).map(f -> f.apply(current)) ).map(KubeClusterState::getLocalMemberRevision); } @Override public Mono<Void> joinLeadershipGroup() { return reconciler.apply(clusterState -> KubeLeaderElectionActions.createJoinLeadershipGroupAction(context).map(f -> f.apply(clusterState)) ).ignoreElement().cast(Void.class); } @Override public Mono<Boolean> leaveLeadershipGroup(boolean onlyNonLeader) { return reconciler.apply(clusterState -> KubeLeaderElectionActions.createLeaveLeadershipGroupAction(context, onlyNonLeader).map(f -> f.apply(clusterState)) ).map(currentState -> !currentState.isInLeaderElectionProcess()); } @Override public Flux<ClusterMembershipEvent> membershipChangeEvents() { return Flux.defer(() -> { AtomicBoolean firstEmit = new AtomicBoolean(true); return reconciler.changes() .flatMap(update -> firstEmit.getAndSet(false) ? Flux.just(update.getSnapshotEvent()) : Flux.fromIterable(update.getDeltaEvents()) ); }); } }
447
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/KubeClusterState.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership; import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipChangeEvent; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent; import com.netflix.titus.api.clustermembership.model.event.LeaderElectionChangeEvent; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.time.Clock; public class KubeClusterState { private final String localMemberId; private final ClusterMembershipRevision<ClusterMember> localMemberRevision; private final ClusterMembershipRevision<ClusterMemberLeadership> localMemberLeadershipRevision; private final boolean mustRegister; private final boolean inLeaderElectionProcess; private final boolean localLeader; private final Map<String, ClusterMembershipRevision<ClusterMember>> clusterMemberSiblings; private final Optional<ClusterMembershipRevision<ClusterMemberLeadership>> currentLeaderOptional; private final List<ClusterMembershipEvent> events; private final KubeClusterMembershipConfiguration configuration; private final Clock clock; public KubeClusterState(ClusterMember initial, KubeClusterMembershipConfiguration configuration, Clock clock) { this.configuration = configuration; this.clock = clock; this.localMemberId = initial.getMemberId(); this.localMemberRevision = ClusterMembershipRevision.<ClusterMember>newBuilder() .withCurrent(initial) .withRevision(-1) .withCode("initial") .withMessage("Initial") .withTimestamp(clock.wallTime()) .build(); this.mustRegister = false; this.localMemberLeadershipRevision = ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder() .withCurrent(ClusterMemberLeadership.newBuilder() .withMemberId(initial.getMemberId()) .withLeadershipState(ClusterMemberLeadershipState.Disabled) .build() ) .withRevision(-1) .withCode("initial") .withMessage("Initial") .withTimestamp(clock.wallTime()) .build(); this.inLeaderElectionProcess = false; this.localLeader = false; this.clusterMemberSiblings = Collections.emptyMap(); this.currentLeaderOptional = Optional.empty(); this.events = Collections.emptyList(); } private KubeClusterState(ClusterMembershipRevision<ClusterMember> localMemberRevision, ClusterMembershipRevision<ClusterMemberLeadership> localMemberLeadershipRevision, boolean mustRegister, boolean inLeaderElectionProcess, boolean localLeader, Map<String, ClusterMembershipRevision<ClusterMember>> clusterMemberSiblings, Optional<ClusterMembershipRevision<ClusterMemberLeadership>> currentLeaderOptional, List<ClusterMembershipEvent> events, KubeClusterMembershipConfiguration configuration, Clock clock) { this.localMemberId = localMemberLeadershipRevision.getCurrent().getMemberId(); this.localMemberRevision = localMemberRevision; this.localMemberLeadershipRevision = localMemberLeadershipRevision; this.mustRegister = mustRegister; this.inLeaderElectionProcess = inLeaderElectionProcess; this.localLeader = localLeader; this.clusterMemberSiblings = clusterMemberSiblings; this.currentLeaderOptional = currentLeaderOptional; this.events = events; this.configuration = configuration; this.clock = clock; } public boolean isMustRegister() { return mustRegister; } public boolean isRegistered() { return localMemberRevision.getCurrent().isRegistered(); } public boolean isInLeaderElectionProcess() { return inLeaderElectionProcess; } public boolean isLocalLeader() { return localLeader; } public ClusterMembershipRevision<ClusterMember> getLocalMemberRevision() { return localMemberRevision; } public ClusterMembershipRevision<ClusterMemberLeadership> getLocalMemberLeadershipRevision() { return localMemberLeadershipRevision; } public Map<String, ClusterMembershipRevision<ClusterMember>> getStaleClusterMemberSiblings() { return CollectionsExt.copyAndRemoveByValue(clusterMemberSiblings, r -> !isStale(r)); } public Map<String, ClusterMembershipRevision<ClusterMember>> getNotStaleClusterMemberSiblings() { return CollectionsExt.copyAndRemoveByValue(clusterMemberSiblings, this::isStale); } public Optional<ClusterMembershipRevision<ClusterMemberLeadership>> findCurrentLeader() { return currentLeaderOptional; } public ClusterMembershipEvent getSnapshotEvent() { return ClusterMembershipEvent.snapshotEvent( CollectionsExt.copyAndAddToList(getNotStaleClusterMemberSiblings().values(), localMemberRevision), localMemberLeadershipRevision, currentLeaderOptional ); } /** * Events describing changes since the previous version of the object. */ public List<ClusterMembershipEvent> getDeltaEvents() { return events; } public KubeClusterState setMustRegister(boolean mustRegister) { return toBuilder().withMustRegister(mustRegister).build(); } public KubeClusterState setLocalClusterMemberRevision(ClusterMembershipRevision<ClusterMember> localMemberRevision, boolean registered) { return toBuilder() .withLocalMemberRevision(setRegistered(localMemberRevision, registered)) .withEvent(ClusterMembershipEvent.memberUpdatedEvent(localMemberRevision)) .build(); } private ClusterMembershipRevision<ClusterMember> setRegistered(ClusterMembershipRevision<ClusterMember> revision, boolean registered) { return revision.toBuilder() .withCurrent(revision.getCurrent().toBuilder().withRegistered(registered).build()) .build(); } public KubeClusterState setJoinedLeaderElection() { ClusterMembershipRevision<ClusterMemberLeadership> revision = ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder() .withCurrent(ClusterMemberLeadership.newBuilder() .withMemberId(localMemberRevision.getCurrent().getMemberId()) .withLeadershipState(ClusterMemberLeadershipState.NonLeader) .build() ) .build(); return toBuilder() .withInLeaderElectionProcess(true) .withLocalMemberLeadershipRevision(revision) .withEvent(LeaderElectionChangeEvent.localJoinedElection(revision)) .build(); } public KubeClusterState setLeaveLeaderElection() { ClusterMembershipRevision<ClusterMemberLeadership> revision = ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder() .withCurrent(ClusterMemberLeadership.newBuilder() .withMemberId(localMemberId) .withLeadershipState(ClusterMemberLeadershipState.Disabled) .build() ) .build(); LeaderElectionChangeEvent event = localLeader ? LeaderElectionChangeEvent.leaderLost(revision) : LeaderElectionChangeEvent.localLeftElection(revision); return toBuilder() .withInLeaderElectionProcess(false) .withLocalMemberLeadershipRevision(revision) .withEvent(event) .build(); } public KubeClusterState processMembershipEventStreamEvent(ClusterMembershipChangeEvent event) { String eventMemberId = event.getRevision().getCurrent().getMemberId(); // We emit local events at the time updates are made. We assume here that each member modifies its data only. // If somebody else tampers with the data, the re-registration process will fix it. if (localMemberId.equals(eventMemberId)) { return this; } switch (event.getChangeType()) { case Added: case Updated: Builder builder = toBuilder() .withClusterMemberSiblings(CollectionsExt.copyAndAdd(clusterMemberSiblings, eventMemberId, event.getRevision())); // Filter out stale members not seen before if (clusterMemberSiblings.containsKey(eventMemberId) || !isStale(event.getRevision())) { builder.withEvent(event); } return builder.build(); case Removed: if (!clusterMemberSiblings.containsKey(eventMemberId)) { return this; } return toBuilder() .withClusterMemberSiblings(CollectionsExt.copyAndRemove(clusterMemberSiblings, eventMemberId)) .withEvent(event) .build(); } return this; } public KubeClusterState processLeaderElectionEventStreamEvent(LeaderElectionChangeEvent event) { String eventMemberId = event.getLeadershipRevision().getCurrent().getMemberId(); boolean local = localMemberId.equals(eventMemberId); switch (event.getChangeType()) { case LeaderElected: Builder electedBuilder = toBuilder() .withLocalLeader(local) .withCurrentLeader(event.getLeadershipRevision()) .withEvent(event); if (local) { electedBuilder.withLocalMemberLeadershipRevision(event.getLeadershipRevision()); } return electedBuilder.build(); case LeaderLost: Builder lostBuilder = toBuilder() .withLocalLeader(false) .withCurrentLeader(null) .withEvent(event); if (local) { lostBuilder.withLocalMemberLeadershipRevision(event.getLeadershipRevision()); } return lostBuilder.build(); } return this; } public KubeClusterState removeStaleMember(String memberId) { ClusterMembershipRevision<ClusterMember> staleMember = clusterMemberSiblings.get(memberId); if (staleMember == null) { return this; } return toBuilder() .withClusterMemberSiblings(CollectionsExt.copyAndRemove(clusterMemberSiblings, memberId)) .withEvent(ClusterMembershipChangeEvent.memberRemovedEvent(staleMember)) .build(); } private boolean isStale(ClusterMembershipRevision<ClusterMember> memberRevision) { return clock.isPast(memberRevision.getTimestamp() + configuration.getRegistrationStaleThresholdMs()); } public Builder toBuilder() { return new Builder() .withLocalMemberRevision(localMemberRevision) .withLocalMemberLeadershipRevision(localMemberLeadershipRevision) .withMustRegister(mustRegister) .withInLeaderElectionProcess(inLeaderElectionProcess) .withLocalLeader(localLeader) .withClusterMemberSiblings(clusterMemberSiblings) .withCurrentLeader(currentLeaderOptional.orElse(null)) .withConfiguration(configuration) .withClock(clock); } static final class Builder { private ClusterMembershipRevision<ClusterMember> localMemberRevision; private ClusterMembershipRevision<ClusterMemberLeadership> localMemberLeadershipRevision; private boolean inLeaderElectionProcess; private boolean localLeader; private Map<String, ClusterMembershipRevision<ClusterMember>> clusterMemberSiblings; private Optional<ClusterMembershipRevision<ClusterMemberLeadership>> currentLeaderOptional; private final List<ClusterMembershipEvent> events = new ArrayList<>(); private KubeClusterMembershipConfiguration configuration; private Clock clock; private boolean mustRegister; private Builder() { } Builder withLocalMemberRevision(ClusterMembershipRevision<ClusterMember> localMemberRevision) { this.localMemberRevision = localMemberRevision; return this; } Builder withLocalMemberLeadershipRevision(ClusterMembershipRevision<ClusterMemberLeadership> localMemberLeadershipRevision) { this.localMemberLeadershipRevision = localMemberLeadershipRevision; return this; } Builder withMustRegister(boolean mustRegister) { this.mustRegister = mustRegister; return this; } Builder withInLeaderElectionProcess(boolean inLeaderElectionProcess) { this.inLeaderElectionProcess = inLeaderElectionProcess; return this; } Builder withLocalLeader(boolean localLeader) { this.localLeader = localLeader; return this; } Builder withClusterMemberSiblings(Map<String, ClusterMembershipRevision<ClusterMember>> clusterMemberSiblings) { this.clusterMemberSiblings = clusterMemberSiblings; return this; } Builder withCurrentLeader(ClusterMembershipRevision<ClusterMemberLeadership> currentLeader) { this.currentLeaderOptional = Optional.ofNullable(currentLeader); return this; } Builder withEvent(ClusterMembershipEvent event) { events.add(event); return this; } Builder withConfiguration(KubeClusterMembershipConfiguration configuration) { this.configuration = configuration; return this; } Builder withClock(Clock clock) { this.clock = clock; return this; } KubeClusterState build() { return new KubeClusterState( localMemberRevision, localMemberLeadershipRevision, mustRegister, inLeaderElectionProcess, localLeader, clusterMemberSiblings, currentLeaderOptional, events, configuration, clock ); } } }
448
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/KubeUtils.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport; import com.netflix.titus.api.clustermembership.connector.ClusterMembershipConnectorException; import com.netflix.titus.common.util.ExceptionExt; import io.fabric8.kubernetes.api.model.Namespace; import io.fabric8.kubernetes.api.model.NamespaceBuilder; import io.fabric8.kubernetes.api.model.NamespaceSpecBuilder; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KubeUtils { private static final Logger logger = LoggerFactory.getLogger(KubeUtils.class); /** * Returns HTTP status code if found, or -1 otherwise. */ public static int getHttpStatusCode(Throwable error) { Throwable cause = error; do { if (cause instanceof KubernetesClientException) { return ((KubernetesClientException) cause).getCode(); } cause = cause.getCause(); } while (cause != null); return -1; } public static boolean is4xx(Throwable error) { return getHttpStatusCode(error) / 100 == 4; } public static ClusterMembershipConnectorException toConnectorException(Throwable error) { if (error instanceof KubernetesClientException) { KubernetesClientException fabric8IOException = (KubernetesClientException) error; return ClusterMembershipConnectorException.clientError( String.format("%s: httpStatus=%s", fabric8IOException.getMessage(), fabric8IOException.getCode()), error ); } return ClusterMembershipConnectorException.clientError(ExceptionExt.toMessageChain(error), error); } public static void createNamespaceIfDoesNotExist(String namespace, NamespacedKubernetesClient kubeApiClient) { // Returns null if the namespace does not exist Namespace current = kubeApiClient.namespaces().withName(namespace).get(); if (current != null) { logger.info("Namespace exists: {}", namespace); return; } Namespace namespaceResource = new NamespaceBuilder() .withMetadata(new ObjectMetaBuilder() .withName(namespace) .build() ) .withSpec(new NamespaceSpecBuilder().build()) .build(); kubeApiClient.namespaces().create(namespaceResource); logger.info("New namespace created: {}", namespace); } }
449
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io/Fabric8IOKubeMembershipExecutor.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io; import com.netflix.titus.api.clustermembership.connector.ClusterMembershipConnectorException; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.ext.kube.clustermembership.connector.KubeMembershipExecutor; import com.netflix.titus.ext.kube.clustermembership.connector.transport.KubeUtils; import com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io.crd.FClusterMembership; import com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io.crd.Fabric8IOModelConverters; import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; import io.fabric8.kubernetes.client.Watcher; import io.fabric8.kubernetes.client.WatcherException; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; public class Fabric8IOKubeMembershipExecutor implements KubeMembershipExecutor { private final NonNamespaceOperation<FClusterMembership, KubernetesResourceList<FClusterMembership>, Resource<FClusterMembership>> membershipClient; private final Scheduler scheduler; public Fabric8IOKubeMembershipExecutor(NamespacedKubernetesClient kubeApiClient, String namespace) { KubeUtils.createNamespaceIfDoesNotExist(namespace, kubeApiClient); this.membershipClient = kubeApiClient.resources(FClusterMembership.class).inNamespace(namespace); this.scheduler = Schedulers.boundedElastic(); } @Override public Mono<ClusterMembershipRevision<ClusterMember>> getMemberById(String memberId) { return Mono.fromCallable(() -> { FClusterMembership stored = membershipClient.withName(memberId).get(); if (stored == null) { throw ClusterMembershipConnectorException.clientError("not found", null); } return applyNewRevisionNumber( Fabric8IOModelConverters.toClusterMembershipRevision(stored.getSpec()), stored.getMetadata() ); }).subscribeOn(scheduler); } @Override public Mono<ClusterMembershipRevision<ClusterMember>> createLocal(ClusterMembershipRevision<ClusterMember> localMemberRevision) { return Mono.fromCallable(() -> { // Kubernetes will not accept create request if the version is set. ClusterMember currentWithoutVersion = localMemberRevision.getCurrent().toBuilder() .withLabels(CollectionsExt.copyAndRemove(localMemberRevision.getCurrent().getLabels(), "resourceVersion")) .build(); ClusterMembershipRevision<ClusterMember> noVersionRevision = localMemberRevision.toBuilder().withCurrent(currentWithoutVersion).build(); FClusterMembership crd = Fabric8IOModelConverters.toCrdFClusterMembership(noVersionRevision); FClusterMembership storedCrd = membershipClient.create(crd); return applyNewRevisionNumber( Fabric8IOModelConverters.toClusterMembershipRevision(storedCrd.getSpec()), storedCrd.getMetadata() ); }).subscribeOn(scheduler); } @Override public Mono<ClusterMembershipRevision<ClusterMember>> updateLocal(ClusterMembershipRevision<ClusterMember> localMemberRevision) { return Mono.fromCallable(() -> { FClusterMembership crd = Fabric8IOModelConverters.toCrdFClusterMembership(localMemberRevision); FClusterMembership storedCrd = membershipClient.withName(localMemberRevision.getCurrent().getMemberId()).replace(crd); return applyNewRevisionNumber( Fabric8IOModelConverters.toClusterMembershipRevision(storedCrd.getSpec()), storedCrd.getMetadata() ); }).subscribeOn(scheduler); } @Override public Mono<Void> removeMember(String memberId) { return Mono.<Void>fromRunnable(() -> { membershipClient.withName(memberId).delete(); }).subscribeOn(scheduler); } @Override public Flux<ClusterMembershipEvent> watchMembershipEvents() { return Flux.create(sink -> { membershipClient.watch( new Watcher<FClusterMembership>() { @Override public void eventReceived(Action action, FClusterMembership resource) { ClusterMembershipRevision<ClusterMember> revision = applyNewRevisionNumber( Fabric8IOModelConverters.toClusterMembershipRevision(resource.getSpec()), resource.getMetadata() ); switch (action) { case ADDED: sink.next(ClusterMembershipEvent.memberAddedEvent(revision)); break; case MODIFIED: sink.next(ClusterMembershipEvent.memberUpdatedEvent(revision)); break; case DELETED: sink.next(ClusterMembershipEvent.memberRemovedEvent(revision)); break; case ERROR: // Do nothing, as we close the flux below in onClose invocation } } @Override public void onClose(WatcherException cause) { KubernetesClientException clientException = cause.asClientException(); sink.error(new IllegalStateException("Kubernetes watch stream error: " + clientException.toString())); } }); }); } private ClusterMembershipRevision<ClusterMember> applyNewRevisionNumber(ClusterMembershipRevision<ClusterMember> localMemberRevision, ObjectMeta metadata) { ClusterMember member = localMemberRevision.getCurrent(); return localMemberRevision.toBuilder() .withRevision(metadata.getGeneration()) .withCurrent(member.toBuilder() .withLabels(CollectionsExt.copyAndAdd(member.getLabels(), "resourceVersion", metadata.getResourceVersion() )) .build() ) .build(); } }
450
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io/Fabric8IOKubeLeaderElectionExecutor.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.PreDestroy; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Tag; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership; import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.DateTimeExt; import com.netflix.titus.common.util.IOExt; import com.netflix.titus.common.util.rx.RetryHandlerBuilder; import com.netflix.titus.common.util.spectator.ActionMetrics; import com.netflix.titus.common.util.spectator.SpectatorExt; import com.netflix.titus.ext.kube.clustermembership.connector.KubeLeaderElectionExecutor; import com.netflix.titus.ext.kube.clustermembership.connector.KubeMetrics; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; import io.fabric8.kubernetes.client.extended.leaderelection.LeaderCallbacks; import io.fabric8.kubernetes.client.extended.leaderelection.LeaderElectionConfigBuilder; import io.fabric8.kubernetes.client.extended.leaderelection.LeaderElector; import io.fabric8.kubernetes.client.extended.leaderelection.resourcelock.LeaderElectionRecord; import io.fabric8.kubernetes.client.extended.leaderelection.resourcelock.LeaseLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.ReplayProcessor; import reactor.core.publisher.Sinks; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; /** * The leader election process and the current leader discovery are handled separately. The former is handled by * Kubernetes {@link LeaderElector} object, which only tells when the local node becomes a leader. To get * information about who is the leader, we check periodically the associated {@link LeaseLock}. */ public class Fabric8IOKubeLeaderElectionExecutor implements KubeLeaderElectionExecutor { private static final Logger logger = LoggerFactory.getLogger(Fabric8IOKubeLeaderElectionExecutor.class); private static final Duration LEADER_POLL_INTERVAL = Duration.ofSeconds(1); private static final int LEADER_POLL_RETRIES = 3; private static final AtomicInteger LEADER_ELECTION_THREAD_IDX = new AtomicInteger(); private static final AtomicInteger WATCHER_THREAD_IDX = new AtomicInteger(); private final NamespacedKubernetesClient kubeApiClient; private final String namespace; private final String clusterName; private final Duration leaseDuration; private final String localMemberId; private final Duration renewDeadline; private final Duration retryPeriod; private final TitusRuntime titusRuntime; private final AtomicReference<LeaderElectionHandler> leaderElectionHandlerRef = new AtomicReference<>(); private final ReplayProcessor<LeaderElectionHandler> handlerProcessor = ReplayProcessor.create(); // Metrics private final Registry registry; private final Id inLeaderElectionProcessMetricId; private final Id isLeaderMetricId; private final ActionMetrics lastElectionAttemptAction; private final ActionMetrics electedLeaderRefreshAction; private final LeaseLock readOnlyEndpointsLock; public Fabric8IOKubeLeaderElectionExecutor(NamespacedKubernetesClient kubeApiClient, String namespace, String clusterName, Duration leaseDuration, String localMemberId, TitusRuntime titusRuntime) { this.kubeApiClient = kubeApiClient; this.namespace = namespace; this.clusterName = clusterName; this.leaseDuration = leaseDuration; this.renewDeadline = leaseDuration.dividedBy(2); this.retryPeriod = leaseDuration.dividedBy(5); this.localMemberId = localMemberId; this.registry = titusRuntime.getRegistry(); List<Tag> tags = Arrays.asList( new BasicTag("kubeNamespace", namespace), new BasicTag("kubeCluster", clusterName), new BasicTag("memberId", localMemberId) ); this.inLeaderElectionProcessMetricId = registry.createId(KubeMetrics.KUBE_METRIC_ROOT + "inLeaderElectionProcess", tags); this.isLeaderMetricId = registry.createId(KubeMetrics.KUBE_METRIC_ROOT + "isLeader", tags); PolledMeter.using(registry).withId(inLeaderElectionProcessMetricId).monitorValue(this, self -> self.isInLeaderElectionProcess() ? 1 : 0); PolledMeter.using(registry).withId(isLeaderMetricId).monitorValue(this, self -> self.isLeader() ? 1 : 0); Id lastElectionAttemptMetricId = registry.createId(KubeMetrics.KUBE_METRIC_ROOT + "lastElectionAttempt", tags); Id electedLeaderRefreshId = registry.createId(KubeMetrics.KUBE_METRIC_ROOT + "electedLeaderRefresh", tags); this.lastElectionAttemptAction = SpectatorExt.actionMetrics(lastElectionAttemptMetricId, registry); this.electedLeaderRefreshAction = SpectatorExt.actionMetrics(electedLeaderRefreshId, registry); this.titusRuntime = titusRuntime; this.readOnlyEndpointsLock = new LeaseLock(namespace, clusterName, localMemberId); } @PreDestroy public void shutdown() { PolledMeter.remove(registry, inLeaderElectionProcessMetricId); PolledMeter.remove(registry, isLeaderMetricId); IOExt.closeSilently(lastElectionAttemptAction, electedLeaderRefreshAction); } @Override public boolean isInLeaderElectionProcess() { LeaderElectionHandler handler = leaderElectionHandlerRef.get(); return handler != null && !handler.isDone(); } @Override public boolean isLeader() { LeaderElectionHandler handler = leaderElectionHandlerRef.get(); return handler != null && handler.isLeader(); } @Override public boolean joinLeaderElectionProcess() { synchronized (leaderElectionHandlerRef) { if (leaderElectionHandlerRef.get() != null && !leaderElectionHandlerRef.get().isDone()) { return false; } LeaderElectionHandler newHandler = new LeaderElectionHandler(); leaderElectionHandlerRef.set(newHandler); handlerProcessor.onNext(newHandler); } return true; } @Override public void leaveLeaderElectionProcess() { LeaderElectionHandler current = leaderElectionHandlerRef.get(); if (current != null) { current.leave(); } } /** * Kubernetes leader lock observer. */ @Override public Flux<ClusterMembershipEvent> watchLeaderElectionProcessUpdates() { Flux<ClusterMembershipEvent> lockWatcher = Flux.defer(() -> { Scheduler singleScheduler = Schedulers.newSingle("LeaderWatcher-" + WATCHER_THREAD_IDX.getAndIncrement()); return Flux.interval(LEADER_POLL_INTERVAL, singleScheduler) .flatMap(tick -> { long started = electedLeaderRefreshAction.start(); ClusterMembershipRevision<ClusterMemberLeadership> revision; try { revision = refreshCurrentLeaderRevision(); electedLeaderRefreshAction.finish(started); } catch (Exception e) { Throwable unwrapped = e.getCause() != null ? e.getCause() : e; electedLeaderRefreshAction.failure(unwrapped); return Flux.error(unwrapped); } return Flux.<ClusterMembershipEvent>just(ClusterMembershipEvent.leaderElected(revision)); }) .retryWhen(RetryHandlerBuilder.retryHandler() .withRetryCount(LEADER_POLL_RETRIES) .withDelay(Math.max(1, leaseDuration.toMillis() / 10), leaseDuration.toMillis(), TimeUnit.MILLISECONDS) .withReactorScheduler(Schedulers.parallel()) .buildRetryExponentialBackoff() ) .doOnCancel(singleScheduler::dispose) .doAfterTerminate(singleScheduler::dispose); }).distinctUntilChanged(); return lockWatcher.mergeWith(handlerProcessor.flatMap(LeaderElectionHandler::events)); } private ClusterMembershipRevision<ClusterMemberLeadership> refreshCurrentLeaderRevision() { try { return createClusterMemberLeadershipObject(readOnlyEndpointsLock.get(kubeApiClient), readOnlyEndpointsLock.get(kubeApiClient).getHolderIdentity()); } catch (Exception e) { throw new IllegalStateException(e); } } /** * Build {@link ClusterMemberLeadership} after the local node became a leader. */ private ClusterMembershipRevision<ClusterMemberLeadership> createLocalNodeLeaderRevisionAfterElection() { LeaderElectionRecord record = null; try { record = readOnlyEndpointsLock.get(kubeApiClient); } catch (Exception e) { logger.warn("Could not read back leader data after being elected", e); } return createClusterMemberLeadershipObject(record, localMemberId); } private ClusterMembershipRevision<ClusterMemberLeadership> createClusterMemberLeadershipObject(LeaderElectionRecord record, String memberId) { ClusterMemberLeadership.Builder leadershipBuilder = ClusterMemberLeadership.newBuilder() .withMemberId(memberId) .withLeadershipState(ClusterMemberLeadershipState.Leader); long acquireTime; if (record != null) { acquireTime = record.getAcquireTime().toEpochSecond() * 1_000; Map<String, String> labels = new HashMap<>(); labels.put("kube.elector.leaseDurationSeconds", "" + record.getLeaseDuration().getSeconds()); labels.put("kube.elector.leaderTransitions", "" + record.getLeaderTransitions()); labels.put("kube.elector.acquireTime", DateTimeExt.toUtcDateTimeString(record.getAcquireTime().toEpochSecond() * 1_000)); labels.put("kube.elector.renewTime", DateTimeExt.toUtcDateTimeString(record.getRenewTime().toEpochSecond() * 1_000)); leadershipBuilder.withLabels(labels); } else { acquireTime = titusRuntime.getClock().wallTime(); leadershipBuilder.withLabels(Collections.emptyMap()); } return ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder() .withCurrent(leadershipBuilder.build()) .withCode("elected") .withMessage("Leadership lock acquired in Kubernetes") .withRevision(acquireTime) .withTimestamp(acquireTime) .build(); } private class LeaderElectionHandler { private final Thread leaderThread; private final Sinks.Many<ClusterMembershipEvent> leadershipStateProcessor = Sinks.many().replay().limit(1); private final AtomicBoolean leaderFlag = new AtomicBoolean(); private final AtomicBoolean closed = new AtomicBoolean(); private LeaderElectionHandler() { LeaderElector<?> leaderElector = kubeApiClient.leaderElector() .withConfig(new LeaderElectionConfigBuilder() .withName(clusterName) .withLeaseDuration(leaseDuration) .withLock(new LeaseLock(namespace, clusterName, localMemberId)) .withRenewDeadline(renewDeadline) .withRetryPeriod(retryPeriod) .withLeaderCallbacks(new LeaderCallbacks( () -> { logger.info("Local member elected a leader"); processLeaderElectedCallback(); }, () -> { logger.info("Local member lost leadership"); processLostLeadershipCallback(); }, newLeader -> logger.info("New leader elected: {}", newLeader) )).build() ) .build(); this.leaderThread = new Thread("LeaderElectionHandler-" + LEADER_ELECTION_THREAD_IDX.getAndIncrement()) { @Override public void run() { while (!closed.get()) { long started = lastElectionAttemptAction.start(); try { leaderElector.run(); if (leaderFlag.getAndSet(false)) { processLostLeadershipCallback(); } lastElectionAttemptAction.finish(started); } catch (Throwable e) { lastElectionAttemptAction.failure(started, e); leaderFlag.set(false); logger.info("Leader election attempt error: {}", e.getMessage()); logger.debug("Stack trace:", e); } } leadershipStateProcessor.tryEmitComplete(); logger.info("Leaving {} thread", Thread.currentThread().getName()); } }; leaderThread.start(); } private Flux<ClusterMembershipEvent> events() { return leadershipStateProcessor.asFlux(); } private boolean isLeader() { return leaderFlag.get(); } private boolean isDone() { return !leaderThread.isAlive(); } private void leave() { closed.set(true); leaderThread.interrupt(); } private void processLeaderElectedCallback() { leaderFlag.set(true); ClusterMembershipRevision<ClusterMemberLeadership> revision = createLocalNodeLeaderRevisionAfterElection(); leadershipStateProcessor.tryEmitNext(ClusterMembershipEvent.leaderElected(revision)); } private void processLostLeadershipCallback() { leaderFlag.set(false); ClusterMemberLeadership.Builder leadershipBuilder = ClusterMemberLeadership.newBuilder() .withMemberId(localMemberId) .withLeadershipState(ClusterMemberLeadershipState.NonLeader); ClusterMembershipRevision<ClusterMemberLeadership> revision = ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder() .withCurrent(leadershipBuilder.build()) .build(); leadershipStateProcessor.tryEmitNext(ClusterMembershipEvent.leaderLost(revision)); leadershipStateProcessor.tryEmitComplete(); } } }
451
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io/crd/FClusterMembershipStatus.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io.crd; /** * Empty now, as both spec and status are in the spec part. * * TODO Clean the membership model ot separate dynamic part from spec. */ public class FClusterMembershipStatus { }
452
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io/crd/FClusterMember.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io.crd; import java.util.List; import java.util.Map; public class FClusterMember { private String memberId; private boolean enabled; private boolean active; private List<FClusterMemberAddress> clusterMemberAddresses; private Map<String, String> labels; private Object state; public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public List<FClusterMemberAddress> getClusterMemberAddresses() { return clusterMemberAddresses; } public void setClusterMemberAddresses(List<FClusterMemberAddress> clusterMemberAddresses) { this.clusterMemberAddresses = clusterMemberAddresses; } public Map<String, String> getLabels() { return labels; } public void setLabels(Map<String, String> labels) { this.labels = labels; } public Object getState() { return state; } public void setState(Object state) { this.state = state; } }
453
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io/crd/FClusterMemberAddress.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io.crd; public class FClusterMemberAddress { private String ipAddress; private int portNumber; private String protocol; private boolean secure; private String description; public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public int getPortNumber() { return portNumber; } public void setPortNumber(int portNumber) { this.portNumber = portNumber; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public boolean isSecure() { return secure; } public void setSecure(boolean secure) { this.secure = secure; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
454
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io/crd/FClusterMembership.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io.crd; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.model.annotation.Group; import io.fabric8.kubernetes.model.annotation.Kind; import io.fabric8.kubernetes.model.annotation.Plural; import io.fabric8.kubernetes.model.annotation.Singular; import io.fabric8.kubernetes.model.annotation.Version; @Group("clustermembership.titus.netflix") @Version("v1alpha1") @Kind("Members") @Singular("member") @Plural("members") public class FClusterMembership extends CustomResource<FClusterMembershipSpec, FClusterMembershipStatus> implements Namespaced { }
455
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io/crd/Fabric8IOModelConverters.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io.crd; import java.util.List; import java.util.stream.Collectors; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.api.clustermembership.model.ClusterMemberAddress; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import io.fabric8.kubernetes.api.model.ObjectMeta; public class Fabric8IOModelConverters { public static ClusterMembershipRevision<ClusterMember> toClusterMembershipRevision(FClusterMembershipSpec spec) { return ClusterMembershipRevision.<ClusterMember>newBuilder() .withCurrent(toClusterMember(spec.getCurrent())) .withCode(spec.getCode()) .withMessage(spec.getMessage()) .withTimestamp(spec.getTimestamp()) .build(); } public static ClusterMember toClusterMember(FClusterMember kubeClusterMember) { return ClusterMember.newBuilder() .withMemberId(kubeClusterMember.getMemberId()) .withEnabled(kubeClusterMember.isEnabled()) .withActive(kubeClusterMember.isActive()) .withClusterMemberAddresses(toClusterMemberAddresses(kubeClusterMember.getClusterMemberAddresses())) .withLabels(kubeClusterMember.getLabels()) .build(); } public static List<ClusterMemberAddress> toClusterMemberAddresses(List<FClusterMemberAddress> kubeAddresses) { return kubeAddresses.stream().map(Fabric8IOModelConverters::toClusterMemberAddress).collect(Collectors.toList()); } public static ClusterMemberAddress toClusterMemberAddress(FClusterMemberAddress kubeAddress) { return ClusterMemberAddress.newBuilder() .withIpAddress(kubeAddress.getIpAddress()) .withPortNumber(kubeAddress.getPortNumber()) .withProtocol(kubeAddress.getProtocol()) .withSecure(kubeAddress.isSecure()) .withDescription(kubeAddress.getDescription()) .build(); } public static FClusterMembership toCrdFClusterMembership(ClusterMembershipRevision<ClusterMember> revision) { FClusterMembership crd = new FClusterMembership(); ObjectMeta metadata = new ObjectMeta(); metadata.setName(revision.getCurrent().getMemberId()); crd.setMetadata(metadata); crd.setSpec(toCrdClusterMembershipRevisionResource(revision)); return crd; } public static FClusterMembershipSpec toCrdClusterMembershipRevisionResource(ClusterMembershipRevision<ClusterMember> revision) { FClusterMembershipSpec fClusterMembership = new FClusterMembershipSpec(); fClusterMembership.setCurrent(toCrdClusterMember(revision.getCurrent())); fClusterMembership.setCode(revision.getCode()); fClusterMembership.setMessage(revision.getMessage()); fClusterMembership.setTimestamp(revision.getTimestamp()); return fClusterMembership; } public static FClusterMember toCrdClusterMember(ClusterMember clusterMember) { FClusterMember fClusterMember = new FClusterMember(); fClusterMember.setMemberId(clusterMember.getMemberId()); fClusterMember.setEnabled(clusterMember.isEnabled()); fClusterMember.setActive(clusterMember.isActive()); fClusterMember.setLabels(clusterMember.getLabels()); fClusterMember.setClusterMemberAddresses(toCrdClusterMemberAddresses(clusterMember.getClusterMemberAddresses())); return fClusterMember; } public static List<FClusterMemberAddress> toCrdClusterMemberAddresses(List<ClusterMemberAddress> addresses) { return addresses.stream().map(Fabric8IOModelConverters::toCrdClusterMemberAddress).collect(Collectors.toList()); } public static FClusterMemberAddress toCrdClusterMemberAddress(ClusterMemberAddress address) { FClusterMemberAddress fClusterMemberAddress = new FClusterMemberAddress(); fClusterMemberAddress.setIpAddress(address.getIpAddress()); fClusterMemberAddress.setPortNumber(address.getPortNumber()); fClusterMemberAddress.setProtocol(address.getProtocol()); fClusterMemberAddress.setSecure(address.isSecure()); fClusterMemberAddress.setDescription(address.getDescription()); return fClusterMemberAddress; } }
456
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/transport/fabric8io/crd/FClusterMembershipSpec.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.transport.fabric8io.crd; public class FClusterMembershipSpec { private FClusterMember current; private String code; private String message; private long timestamp; public FClusterMember getCurrent() { return current; } public void setCurrent(FClusterMember current) { this.current = current; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } }
457
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/action/KubeRegistrationActions.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.action; import java.util.function.Function; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import com.netflix.titus.ext.kube.clustermembership.connector.KubeClusterState; import com.netflix.titus.ext.kube.clustermembership.connector.KubeContext; import com.netflix.titus.ext.kube.clustermembership.connector.KubeMembershipExecutor; import com.netflix.titus.ext.kube.clustermembership.connector.transport.KubeUtils; import reactor.core.publisher.Mono; public class KubeRegistrationActions { public static Mono<Function<KubeClusterState, KubeClusterState>> registerLocal(KubeContext context, KubeClusterState kubeClusterState, Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> selfUpdate) { ClusterMember localMember = kubeClusterState.getLocalMemberRevision().getCurrent(); ClusterMembershipRevision<ClusterMember> newRevision = setRegistrationStatus(selfUpdate.apply(localMember), true); KubeMembershipExecutor membershipExecutor = context.getKubeMembershipExecutor(); Mono<ClusterMembershipRevision<ClusterMember>> monoAction; if (kubeClusterState.isRegistered()) { monoAction = membershipExecutor .updateLocal(newRevision) .onErrorResume(e -> { if (!KubeUtils.is4xx(e)) { return Mono.error(e); } int status = KubeUtils.getHttpStatusCode(e); if (status == 404) { return membershipExecutor.createLocal(newRevision); } // Bad or stale data record. Remove it first and than register. return membershipExecutor .removeMember(newRevision.getCurrent().getMemberId()) .then(membershipExecutor.createLocal(newRevision)); }); } else { monoAction = membershipExecutor .createLocal(newRevision) .onErrorResume(e -> { if (!KubeUtils.is4xx(e)) { return Mono.error(e); } // Bad or stale data record. Remove it first and than register. return membershipExecutor .removeMember(newRevision.getCurrent().getMemberId()) .then(membershipExecutor.createLocal(newRevision)); }); } return monoAction .onErrorMap(KubeUtils::toConnectorException) .map(update -> currentState -> currentState.setMustRegister(true).setLocalClusterMemberRevision(update, true)); } public static Mono<Function<KubeClusterState, KubeClusterState>> unregisterLocal(KubeContext context, KubeClusterState kubeClusterState, Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> selfUpdate) { if (!kubeClusterState.isRegistered()) { return Mono.just(Function.identity()); } ClusterMember localMember = kubeClusterState.getLocalMemberRevision().getCurrent(); ClusterMembershipRevision<ClusterMember> newRevision = setRegistrationStatus(selfUpdate.apply(localMember), false); Mono monoAction = context.getKubeMembershipExecutor().removeMember(kubeClusterState.getLocalMemberRevision().getCurrent().getMemberId()); return ((Mono<Function<KubeClusterState, KubeClusterState>>) monoAction) .onErrorMap(KubeUtils::toConnectorException) .thenReturn(currentState -> currentState.setMustRegister(false).setLocalClusterMemberRevision(newRevision, false)); } public static Mono<Function<KubeClusterState, KubeClusterState>> removeStaleRegistration(KubeContext context, String memberId) { return context.getKubeMembershipExecutor().removeMember(memberId) .onErrorMap(KubeUtils::toConnectorException) .thenReturn(s -> s.removeStaleMember(memberId)); } private static ClusterMembershipRevision<ClusterMember> setRegistrationStatus(ClusterMembershipRevision<ClusterMember> revision, boolean registered) { return revision.toBuilder() .withCurrent(revision.getCurrent().toBuilder().withRegistered(registered).build()) .build(); } }
458
0
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector
Create_ds/titus-control-plane/titus-common-ext/kube/src/main/java/com/netflix/titus/ext/kube/clustermembership/connector/action/KubeLeaderElectionActions.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.kube.clustermembership.connector.action; import java.util.function.Function; import com.netflix.titus.ext.kube.clustermembership.connector.KubeClusterState; import com.netflix.titus.ext.kube.clustermembership.connector.KubeContext; import reactor.core.publisher.Mono; public class KubeLeaderElectionActions { public static Mono<Function<KubeClusterState, KubeClusterState>> createJoinLeadershipGroupAction(KubeContext context) { return Mono.just(currentState -> { if (currentState.isInLeaderElectionProcess()) { return currentState; } context.getKubeLeaderElectionExecutor().joinLeaderElectionProcess(); return currentState.setJoinedLeaderElection(); }); } public static Mono<Function<KubeClusterState, KubeClusterState>> createLeaveLeadershipGroupAction(KubeContext context, boolean onlyNonLeader) { return Mono.just(currentState -> { if (!currentState.isInLeaderElectionProcess()) { return currentState; } if (currentState.isLocalLeader() && onlyNonLeader) { return currentState; } context.getKubeLeaderElectionExecutor().leaveLeaderElectionProcess(); return currentState.setLeaveLeaderElection(); }); } }
459
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/test/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/test/java/com/netflix/titus/ext/elasticsearch/DefaultEsClientTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch; import java.time.Instant; import java.util.Arrays; import java.util.List; import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultEsClientTest { private EsClientConfiguration getClientConfiguration() { EsClientConfiguration mockConfig = mock(EsClientConfiguration.class); when(mockConfig.getHost()).thenReturn("localhost"); when(mockConfig.getPort()).thenReturn(9200); return mockConfig; } @Test public void bulkIndexPayload() { TestDoc testDoc1 = new TestDoc("id1", "Accepted", Instant.now().getEpochSecond()); TestDoc testDoc2 = new TestDoc("id2", "Running", Instant.now().getEpochSecond()); TestDoc testDoc3 = new TestDoc("id3", "Stopped", Instant.now().getEpochSecond()); List<TestDoc> testDocs = Arrays.asList(testDoc1, testDoc2, testDoc3); DefaultEsWebClientFactory defaultEsWebClientFactory = new DefaultEsWebClientFactory(getClientConfiguration()); DefaultEsClient<TestDoc> esClient = new DefaultEsClient<>(defaultEsWebClientFactory); final String bulkIndexPayload = esClient.buildBulkIndexPayload(testDocs, "titustasks", "default"); assertThat(bulkIndexPayload).isNotNull(); assertThat(bulkIndexPayload).isNotEmpty(); final String[] payloadLines = bulkIndexPayload.split("\n"); assertThat(payloadLines.length).isEqualTo(testDocs.size() * 2); String line1 = "{\"index\":{\"_index\":\"titustasks\",\"_type\":\"default\",\"_id\":\"id1\"}}"; String line2 = "{\"index\":{\"_index\":\"titustasks\",\"_type\":\"default\",\"_id\":\"id2\"}}"; String line3 = "{\"index\":{\"_index\":\"titustasks\",\"_type\":\"default\",\"_id\":\"id3\"}}"; assertThat(payloadLines[0]).isEqualTo(line1); assertThat(payloadLines[2]).isEqualTo(line2); assertThat(payloadLines[4]).isEqualTo(line3); } }
460
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/test/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/test/java/com/netflix/titus/ext/elasticsearch/TestDoc.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch; public class TestDoc implements EsDoc { String id; String state; long ts; public TestDoc() { } public TestDoc(String id, String state, long ts) { this.id = id; this.state = state; this.ts = ts; } public void setId(String id) { this.id = id; } public void setState(String state) { this.state = state; } public void setTs(long ts) { this.ts = ts; } public String getId() { return id; } public String getState() { return state; } public long getTs() { return ts; } }
461
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/test/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/test/java/com/netflix/titus/ext/elasticsearch/DefaultEsWebClientFactoryTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch; import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultEsWebClientFactoryTest { private EsClientConfiguration getClientConfiguration() { EsClientConfiguration mockConfig = mock(EsClientConfiguration.class); when(mockConfig.getHost()).thenReturn("localhost"); when(mockConfig.getPort()).thenReturn(9200); return mockConfig; } @Test public void verifyEsHost() { final DefaultEsWebClientFactory defaultEsWebClientFactory = new DefaultEsWebClientFactory(getClientConfiguration()); String esUri = defaultEsWebClientFactory.buildEsUrl(); assertThat(esUri).isEqualTo("http://localhost:9200"); } }
462
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/test/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/test/java/com/netflix/titus/ext/elasticsearch/EsExternalResource.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch; import com.google.common.base.Preconditions; import org.junit.rules.ExternalResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.reactive.function.client.WebClient; public class EsExternalResource extends ExternalResource { private static final Logger logger = LoggerFactory.getLogger(EsExternalResource.class); private EsClientConfiguration esClientConfiguration; @Override protected void before() throws Throwable { String esHostName = Preconditions.checkNotNull(System.getenv("ES_HOST_NAME"), "'ES_HOST_NAME' environment variable not set" ); String esPortStr = Preconditions.checkNotNull(System.getenv("ES_PORT"), "'ES_PORT' environment variable not set" ); int esPort = Integer.parseInt(esPortStr); // check if a ES cluster state is Green WebClient webClient = WebClient.builder() .baseUrl(String.format("http://%s:%d", esHostName, esPort)).build(); String resp = webClient.get() .uri("/_cat/health") .retrieve() .bodyToMono(String.class).block(); if (resp == null || !resp.contains("green")) { throw new IllegalStateException(String.format("Elastic search cluster %s:%d not READY", esHostName, esPort)); } buildEsClientConfiguration(esHostName, esPort); } public EsClientConfiguration getEsClientConfiguration() { return esClientConfiguration; } private void buildEsClientConfiguration(String esHostName, int esPort) { esClientConfiguration = new EsClientConfiguration() { @Override public int getReadTimeoutSeconds() { return 20; } @Override public int getConnectTimeoutMillis() { return 1000; } @Override public String getHost() { return esHostName; } @Override public int getPort() { return esPort; } }; } }
463
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/test/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/test/java/com/netflix/titus/ext/elasticsearch/DefaultEsClientIntegrationTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch; import java.time.Instant; import java.util.Arrays; import com.netflix.titus.ext.elasticsearch.model.EsRespSrc; import com.netflix.titus.testkit.junit.category.RemoteIntegrationTest; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.springframework.core.ParameterizedTypeReference; import reactor.test.StepVerifier; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; @Category(RemoteIntegrationTest.class) public class DefaultEsClientIntegrationTest { @ClassRule public static final EsExternalResource ES_RESOURCE = new EsExternalResource(); private static final ParameterizedTypeReference<EsRespSrc<TestDoc>> esRespTypeRef = new ParameterizedTypeReference<EsRespSrc<TestDoc>>() { }; private DefaultEsClient<TestDoc> client; @Before public void setup() { client = new DefaultEsClient<>(new DefaultEsWebClientFactory(ES_RESOURCE.getEsClientConfiguration())); } @Test public void indexDocument() { String index = "jobs"; String type = "_doc"; String docId = "foo-13"; TestDoc testDoc = new TestDoc(docId, "Accepted", Instant.now().getEpochSecond()); client.indexDocument(testDoc, index, type).block(); EsRespSrc<TestDoc> respSrc = client.findDocumentById(docId, index, type, esRespTypeRef).block(); assertThat(respSrc).isNotNull(); assertThat(respSrc.getSource()).isNotNull(); TestDoc testDocResp = respSrc.getSource(); assertThat(testDocResp.getId()).isEqualTo(docId); } @Test public void bulkIndexDocument() { String index = "jobs"; String type = "_doc"; String id1 = "foo-100"; String id2 = "foo-102"; String id3 = "foo-104"; String id1State = "Running"; String id2State = "Starting"; String id3State = "Queued"; TestDoc testDoc1 = new TestDoc(id1, id1State, Instant.now().getEpochSecond()); TestDoc testDoc2 = new TestDoc(id2, id2State, Instant.now().getEpochSecond()); TestDoc testDoc3 = new TestDoc(id3, id3State, Instant.now().getEpochSecond()); StepVerifier.create(client.bulkIndexDocuments(Arrays.asList(testDoc1, testDoc2, testDoc3), index, type)) .assertNext(bulkEsIndexResp -> { assertThat(bulkEsIndexResp.getItems()).isNotNull(); assertThat(bulkEsIndexResp.getItems().size()).isGreaterThan(0); }) .verifyComplete(); StepVerifier.create(client.getTotalDocumentCount(index, type)) .assertNext(esRespCount -> { assertThat(esRespCount).isNotNull(); assertThat(esRespCount.getCount()).isGreaterThan(0); }) .verifyComplete(); StepVerifier.create(client.findDocumentById(id1, index, type, esRespTypeRef)) .assertNext(testDocEsRespSrc -> { assertThat(testDocEsRespSrc.getSource()).isNotNull(); assertThat(testDocEsRespSrc.getSource().getId()).isEqualTo(id1); assertThat(testDocEsRespSrc.getSource().getState()).isEqualTo(id1State); }) .verifyComplete(); StepVerifier.create(client.findDocumentById(id2, index, type, esRespTypeRef)) .assertNext(testDocEsRespSrc -> { assertThat(testDocEsRespSrc.getSource()).isNotNull(); assertThat(testDocEsRespSrc.getSource().getId()).isEqualTo(id2); assertThat(testDocEsRespSrc.getSource().getState()).isEqualTo(id2State); }) .verifyComplete(); StepVerifier.create(client.findDocumentById(id3, index, type, esRespTypeRef)) .assertNext(testDocEsRespSrc -> { assertThat(testDocEsRespSrc.getSource()).isNotNull(); assertThat(testDocEsRespSrc.getSource().getId()).isEqualTo(id3); assertThat(testDocEsRespSrc.getSource().getState()).isEqualTo(id3State); }) .verifyComplete(); } }
464
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/EsClient.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch; import java.util.List; import com.netflix.titus.ext.elasticsearch.model.BulkEsIndexResp; import com.netflix.titus.ext.elasticsearch.model.EsIndexResp; import com.netflix.titus.ext.elasticsearch.model.EsRespCount; import com.netflix.titus.ext.elasticsearch.model.EsRespSrc; import org.springframework.core.ParameterizedTypeReference; import reactor.core.publisher.Mono; public interface EsClient<T extends EsDoc> { Mono<EsIndexResp> indexDocument(T document, String indexName, String documentType); Mono<BulkEsIndexResp> bulkIndexDocuments(List<T> documents, String index, String type); Mono<EsRespSrc<T>> findDocumentById(String id, String index, String type, ParameterizedTypeReference<EsRespSrc<T>> responseTypeRef); Mono<EsRespCount> getTotalDocumentCount(String index, String type); }
465
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/EsWebClientFactory.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch; import org.springframework.web.reactive.function.client.WebClient; public interface EsWebClientFactory { WebClient buildWebClient(); }
466
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/DefaultEsWebClientFactory.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch; import io.netty.channel.ChannelOption; import io.netty.handler.timeout.ReadTimeoutHandler; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.web.reactive.function.client.WebClient; import reactor.netty.http.client.HttpClient; import reactor.netty.tcp.TcpClient; public class DefaultEsWebClientFactory implements EsWebClientFactory { private EsClientConfiguration esClientConfiguration; public DefaultEsWebClientFactory(EsClientConfiguration esClientConfiguration) { this.esClientConfiguration = esClientConfiguration; } @Override public WebClient buildWebClient() { return WebClient.builder().clientConnector(new ReactorClientHttpConnector(buildHttpClient())) .baseUrl(buildEsUrl()).build(); } public String buildEsUrl() { return String.format("http://%s:%s", esClientConfiguration.getHost(), esClientConfiguration.getPort()); } private HttpClient buildHttpClient() { return HttpClient.create().tcpConfiguration(tcpClient -> { TcpClient tcpClientWithConnectionTimeout = tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, esClientConfiguration.getConnectTimeoutMillis()); return tcpClientWithConnectionTimeout.doOnConnected(connection -> { //TODO Investigate why WriteTimeoutHandler appears to be broken in netty-handler 4.1.36.RELEASE package. connection.addHandlerLast(new ReadTimeoutHandler(esClientConfiguration.getReadTimeoutSeconds())); }); }); } }
467
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/EsDoc.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch; public interface EsDoc { String getId(); }
468
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/DefaultEsClient.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.common.util.jackson.CommonObjectMappers; import com.netflix.titus.ext.elasticsearch.model.BulkEsIndexResp; import com.netflix.titus.ext.elasticsearch.model.EsIndexResp; import com.netflix.titus.ext.elasticsearch.model.EsRespCount; import com.netflix.titus.ext.elasticsearch.model.EsRespSrc; import com.netflix.titus.ext.elasticsearch.model.IndexHeader; import com.netflix.titus.ext.elasticsearch.model.IndexHeaderLine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; public class DefaultEsClient<T extends EsDoc> implements EsClient<T> { private static final Logger logger = LoggerFactory.getLogger(DefaultEsClient.class); private final WebClient client; public DefaultEsClient(EsWebClientFactory esWebClientFactory) { client = esWebClientFactory.buildWebClient(); } @Override public Mono<EsIndexResp> indexDocument(T document, String indexName, String documentType) { return client.post() .uri(String.format("/%s/%s/%s", indexName, documentType, document.getId())) .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(document)) .retrieve() .bodyToMono(EsIndexResp.class); } @Override public Mono<BulkEsIndexResp> bulkIndexDocuments(List<T> taskDocuments, String index, String type) { return client.post() .uri("/_bulk") .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(buildBulkIndexPayload(taskDocuments, index, type))) .retrieve() .bodyToMono(BulkEsIndexResp.class); } @Override public Mono<EsRespSrc<T>> findDocumentById(String id, String index, String type, ParameterizedTypeReference<EsRespSrc<T>> responseTypeRef) { return client.get() .uri(uriBuilder -> uriBuilder.path(String.format("%s/%s/%s", index, type, id)).build()) .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(responseTypeRef); } @Override public Mono<EsRespCount> getTotalDocumentCount(String index, String type) { return client.get() .uri(uriBuilder -> uriBuilder.path(String.format("%s/%s/_count", index, type)).build()) .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(new ParameterizedTypeReference<EsRespCount>() { }); } @VisibleForTesting String buildBulkIndexPayload(List<T> tasks, String index, String type) { StringBuilder sb = new StringBuilder(); final ObjectMapper mapper = CommonObjectMappers.jacksonDefaultMapper(); tasks.forEach(taskDocument -> { final IndexHeader indexHeader = new IndexHeader(index, type, taskDocument.getId()); final IndexHeaderLine indexHeaderLine = new IndexHeaderLine(indexHeader); try { final String indexLine = mapper.writeValueAsString(indexHeaderLine); sb.append(indexLine); sb.append("\n"); final String fieldsLine = mapper.writeValueAsString(taskDocument); sb.append(fieldsLine); sb.append("\n"); } catch (JsonProcessingException e) { logger.error("Exception in transforming taskDocument into JSON ", e); } }); return sb.toString(); } }
469
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/EsClientConfiguration.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titus.es") public interface EsClientConfiguration { int DEFAULT_READ_TIMEOUT_SECONDS = 20; int DEFAULT_CONNECT_TIMEOUT_MILLIS = 1000; @DefaultValue("" + DEFAULT_READ_TIMEOUT_SECONDS) int getReadTimeoutSeconds(); @DefaultValue("" + DEFAULT_CONNECT_TIMEOUT_MILLIS) int getConnectTimeoutMillis(); String getHost(); int getPort(); }
470
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/model/EsRespHits.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Elastic search data model as defined by REST API documentation * https://www.elastic.co/guide/en/elasticsearch/reference/master/rest-apis.html */ public class EsRespHits<T> { private final List<EsRespSrc<T>> hits; @JsonCreator public EsRespHits(@JsonProperty("hits") List<EsRespSrc<T>> hits) { this.hits = hits; } public List<EsRespSrc<T>> getHits() { return hits; } }
471
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/model/BulkEsIndexRespItem.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Elastic search data model as defined by REST API documentation * https://www.elastic.co/guide/en/elasticsearch/reference/master/rest-apis.html */ public class BulkEsIndexRespItem { private EsIndexResp index; @JsonCreator public BulkEsIndexRespItem(@JsonProperty("index") EsIndexResp index) { this.index = index; } public EsIndexResp getIndex() { return index; } }
472
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/model/EsIndexResp.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonProperty; /** * Elastic search data model as defined by REST API documentation * https://www.elastic.co/guide/en/elasticsearch/reference/master/rest-apis.html */ public class EsIndexResp { private final boolean created; private final String result; private final String id; @JsonCreator public EsIndexResp(@JsonProperty("created") boolean created, @JsonProperty("result") String result, @JsonProperty("_id") String id) { this.created = created; this.result = result; this.id = id; } public boolean isCreated() { return created; } public String getResult() { return result; } @JsonGetter("_id") public String getId() { return id; } }
473
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/model/EsSearchResp.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Elastic search data model as defined by REST API documentation * https://www.elastic.co/guide/en/elasticsearch/reference/master/rest-apis.html */ public class EsSearchResp<T> { private final EsRespHits<T> hits; @JsonCreator public EsSearchResp(@JsonProperty("hits") EsRespHits<T> hits) { this.hits = hits; } public EsRespHits<T> getHits() { return hits; } }
474
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/model/IndexHeaderLine.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Elastic search data model as defined by REST API documentation * https://www.elastic.co/guide/en/elasticsearch/reference/master/rest-apis.html */ public class IndexHeaderLine { private final IndexHeader index; @JsonCreator public IndexHeaderLine(@JsonProperty("index") IndexHeader index) { this.index = index; } public IndexHeader getIndex() { return index; } }
475
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/model/BulkEsIndexResp.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Elastic search data model as defined by REST API documentation * https://www.elastic.co/guide/en/elasticsearch/reference/master/rest-apis.html */ public class BulkEsIndexResp { private final List<BulkEsIndexRespItem> items; @JsonCreator public BulkEsIndexResp(@JsonProperty("items") List<BulkEsIndexRespItem> items) { this.items = items; } public List<BulkEsIndexRespItem> getItems() { return items; } }
476
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/model/IndexHeader.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonProperty; /** * Elastic search data model as defined by REST API documentation * https://www.elastic.co/guide/en/elasticsearch/reference/master/rest-apis.html */ public class IndexHeader { private final String index; private final String type; private final String id; @JsonCreator public IndexHeader(@JsonProperty("_index") String index, @JsonProperty("_type") String type, @JsonProperty("_id") String id) { this.index = index; this.type = type; this.id = id; } @JsonGetter("_index") public String getIndex() { return index; } @JsonGetter("_type") public String getType() { return type; } @JsonGetter("_id") public String getId() { return id; } }
477
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/model/EsRespCount.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Elastic search data model as defined by REST API documentation * https://www.elastic.co/guide/en/elasticsearch/reference/master/rest-apis.html */ public class EsRespCount { private final int count; @JsonCreator public EsRespCount(@JsonProperty("count") int count) { this.count = count; } public int getCount() { return count; } }
478
0
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch
Create_ds/titus-control-plane/titus-common-ext/elasticsearch/src/main/java/com/netflix/titus/ext/elasticsearch/model/EsRespSrc.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.ext.elasticsearch.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonProperty; /** * Elastic search data model as defined by REST API documentation * https://www.elastic.co/guide/en/elasticsearch/reference/master/rest-apis.html */ public class EsRespSrc<T> { private final T source; @JsonCreator public EsRespSrc(@JsonProperty("_source") T source) { this.source = source; } @JsonGetter("_source") public T getSource() { return source; } }
479
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/NumberSequenceTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.util.Collections; import java.util.Iterator; import java.util.List; import com.netflix.titus.common.util.tuple.Either; import org.junit.Test; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class NumberSequenceTest { @Test public void testParse() { checkSequence(tryParse(""), Collections.emptyList(), false); checkSequence(tryParse("1,2,3"), asList(1L, 2L, 3L), false); checkSequence(tryParse("1..5"), asList(1L, 2L, 3L, 4L), false); checkSequence(tryParse("1.."), asList(1L, 2L, 3L, 4L, 5L, 6L), true); checkSequence(tryParse("1, 2, 3, 4..6, 10"), asList(1L, 2L, 3L, 4L, 5L, 10L), false); } @Test public void testSkip() { checkSequence(tryParse("1,2,3,4,5").skip(2), asList(3L, 4L, 5L), false); checkSequence(tryParse("1..10").skip(5), asList(6L, 7L, 8L, 9L), false); checkSequence(tryParse("1,2,3,8..10,15,16").skip(5), asList(15L, 16L), false); checkSequence(tryParse("1,2,3,8..10,15,16").skip(1000), Collections.emptyList(), false); } @Test public void testStep() { checkSequence(tryParse("1,2,3,4,5").step(2), asList(1L, 3L, 5L), false); checkSequence(tryParse("1..5").step(2), asList(1L, 3L), false); checkSequence(tryParse("1,2,3,4..7,12..14").step(2), asList(1L, 3L, 5L, 12L), false); checkSequence(tryParse("1,2,3,4..7,12..14").skip(2).step(2), asList(3L, 5L, 12L), false); } private NumberSequence tryParse(String value) { Either<NumberSequence, String> result = NumberSequence.parse(value); if (result.hasError()) { fail(result.getError()); } return result.getValue(); } private void checkSequence(NumberSequence sequence, List<Long> expected, boolean infinite) { Iterator<Long> it = sequence.getIterator(); for (long nextExpected : expected) { assertThat(it.next()).isEqualTo(nextExpected); } if (infinite) { assertThat(it.hasNext()).isTrue(); } else { assertThat(it.hasNext()).isFalse(); } } }
480
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/CollectionsExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.junit.Test; import static com.netflix.titus.common.util.CollectionsExt.asSet; import static com.netflix.titus.common.util.CollectionsExt.xor; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class CollectionsExtTest { @Test public void testSetXor() { assertThat(xor(asSet(1, 2, 3), asSet(2, 3, 4), asSet(3, 4, 5))).contains(1, 5); } @Test public void testContainsAnyKeys() { Map<String, String> map = new HashMap<>(); map.put("a", "1"); map.put("b", "2"); assertThat(CollectionsExt.containsAnyKeys(map, "a", "c")).isTrue(); assertThat(CollectionsExt.containsAnyKeys(map, "c", "a")).isTrue(); assertThat(CollectionsExt.containsAnyKeys(map, "c", "d")).isFalse(); } @Test public void testBinarySearchLeftMostCornerCases() { testBinarySearchLeftMost(Collections.emptyList(), 1); testBinarySearchLeftMost(Collections.singletonList(1), -100); testBinarySearchLeftMost(Collections.singletonList(1), 100); } @Test public void testBinarySearchLeftMostNoDuplicates() { Random random = new Random(123); Set<Integer> numbers = new HashSet<>(); while (numbers.size() < 100) { numbers.add(2 * random.nextInt(1_000)); } List<Integer> orderedNumbers = new ArrayList<>(numbers); orderedNumbers.sort(Integer::compare); for (int i = 0; i < numbers.size(); i++) { for (int delta = -1; delta <= 1; delta++) { testBinarySearchLeftMost(orderedNumbers, orderedNumbers.get(i) + delta); } } } @Test public void testBinarySearchLeftMostWithDuplicates() { List<Integer> orderedNumbers = Arrays.asList(1, 2, 3, 3, 3, 5); int result = CollectionsExt.binarySearchLeftMost( orderedNumbers, item -> Integer.compare(3, item) ); assertThat(result).isEqualTo(2); } private void testBinarySearchLeftMost(List<Integer> orderedNumbers, int target) { int result = CollectionsExt.binarySearchLeftMost( orderedNumbers, item -> Integer.compare(target, item) ); int stdResult = Collections.binarySearch(orderedNumbers, target); if (result != stdResult) { fail("Result different from returned by JDK binarySearch function: list=%s, our=%s, std=%s", orderedNumbers, result, stdResult ); } } @Test public void mapLowerCaseKeys() { Map<String, String> result = CollectionsExt.toLowerCaseKeys(CollectionsExt.asMap("a", "foo", "b", "bar", "mIxEd", "UntouChed")); assertThat(result).containsOnlyKeys("a", "b", "mixed"); assertThat(result).containsValues("foo", "bar", "UntouChed"); } }
481
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/ProtoMessageBuilder.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.util.Arrays; import com.google.protobuf.DescriptorProtos; import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; import com.google.protobuf.DescriptorProtos.FileDescriptorProto; import com.google.protobuf.Descriptors; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.DynamicMessage; import com.google.protobuf.Message; import static org.assertj.core.api.Assertions.assertThat; class ProtoMessageBuilder { private static final Descriptors.Descriptor INNER_TYPE; private static final Descriptors.Descriptor OUTER_TYPE; static { // Inner type FieldDescriptorProto innerField1 = FieldDescriptorProto.newBuilder() .setName("stringField1") .setNumber(1) .setType(FieldDescriptorProto.Type.TYPE_STRING) .build(); FieldDescriptorProto innerField2 = FieldDescriptorProto.newBuilder() .setName("stringField2") .setNumber(2) .setType(FieldDescriptorProto.Type.TYPE_STRING) .build(); DescriptorProtos.DescriptorProto innerBuilder = DescriptorProtos.DescriptorProto.newBuilder() .setName("InnerEntity") .addField(innerField1) .addField(innerField2) .build(); // Outer type FieldDescriptorProto outerField1 = FieldDescriptorProto.newBuilder() .setName("objectField") .setNumber(1) .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName("InnerEntity") .build(); FieldDescriptorProto outerField2 = FieldDescriptorProto.newBuilder() .setName("primitiveField") .setNumber(3) .setType(FieldDescriptorProto.Type.TYPE_INT32) .build(); FieldDescriptorProto outerField3 = FieldDescriptorProto.newBuilder() .setName("objectArrayField") .setNumber(2) .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName("InnerEntity") .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) .build(); DescriptorProtos.DescriptorProto outerBuilder = DescriptorProtos.DescriptorProto.newBuilder() .setName("OuterEntity") .addField(outerField1) .addField(outerField2) .addField(outerField3) .build(); FileDescriptorProto proto = FileDescriptorProto.newBuilder() .setName("sampleProtoModel") .addMessageType(innerBuilder) .addMessageType(outerBuilder) .build(); FileDescriptor fileDescriptor = null; try { fileDescriptor = FileDescriptor.buildFrom(proto, new FileDescriptor[0]); } catch (Descriptors.DescriptorValidationException e) { throw new RuntimeException(e); } INNER_TYPE = fileDescriptor.getMessageTypes().get(0); OUTER_TYPE = fileDescriptor.getMessageTypes().get(1); } static Message newInner(String value1, String value2) { FieldDescriptor field1 = INNER_TYPE.getFields().get(0); FieldDescriptor field2 = INNER_TYPE.getFields().get(1); return DynamicMessage.newBuilder(INNER_TYPE) .setField(field1, value1) .setField(field2, value2) .build(); } static Message newOuter(Message value1, int value2, Message... value3) { FieldDescriptor field1 = OUTER_TYPE.getFields().get(0); FieldDescriptor field2 = OUTER_TYPE.getFields().get(1); FieldDescriptor field3 = OUTER_TYPE.getFields().get(2); return DynamicMessage.newBuilder(OUTER_TYPE) .setField(field1, value1) .setField(field2, value2) .setField(field3, Arrays.asList(value3)) .build(); } static FieldDescriptor getAndAssertField(Descriptors.Descriptor descriptor, String name) { FieldDescriptor field = descriptor.findFieldByName(name); assertThat(field).isNotNull(); return field; } static FieldDescriptor getAndAssertField(Message message, String name) { return getAndAssertField(message.getDescriptorForType(), name); } }
482
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/StringExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import com.google.common.collect.ImmutableMap; import com.netflix.titus.common.util.tuple.Either; import org.junit.Test; import static com.netflix.titus.common.util.StringExt.parseEnumListIgnoreCase; import static com.netflix.titus.common.util.StringExt.parseKeyValueList; import static java.util.Arrays.asList; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class StringExtTest { private enum EnumValue {A, B, C, D} @Test public void testUUID() { assertThat(StringExt.isUUID("")).isFalse(); assertThat(StringExt.isUUID("abc")).isFalse(); assertThat(StringExt.isUUID(UUID.randomUUID().toString())).isTrue(); } @Test public void testParseEnumListIgnoreCase() { assertThat(parseEnumListIgnoreCase("", EnumValue.class)).isEmpty(); assertThat(parseEnumListIgnoreCase(" ", EnumValue.class)).isEmpty(); assertThat(parseEnumListIgnoreCase("a , B", EnumValue.class)).contains(EnumValue.A, EnumValue.B); Map<String, List<EnumValue>> grouping = singletonMap("ab", asList(EnumValue.C, EnumValue.D)); assertThat(parseEnumListIgnoreCase("a , B, AB", EnumValue.class, grouping::get)).contains(EnumValue.A, EnumValue.B); try { parseEnumListIgnoreCase("a , bb", EnumValue.class); fail("Expected to fail during parsing invalid enum value"); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).contains("bb"); } } @Test public void testParseKeyValueList() { Map<String, String> actual = parseKeyValueList("key1:value1,key2:value2,key3:,key4"); assertThat(actual).containsAllEntriesOf(ImmutableMap.<String, String> builder().put("key1", "value1").put("key2", "value2").put("key3", "").put("key4", "").build() ); } @Test public void testRemoveQuotes() { assertThat(StringExt.removeSurroundingQuotes("\"abc")).isEqualTo("\"abc"); assertThat(StringExt.removeSurroundingQuotes("\"abc\"")).isEqualTo("abc"); assertThat(StringExt.removeSurroundingQuotes("abc\"")).isEqualTo("abc\""); } @Test public void testParseDurationList() { assertThat(StringExt.parseDurationMsList("abc")).isEmpty(); assertThat(StringExt.parseDurationMsList("1, ,")).isEmpty(); assertThat(StringExt.parseDurationMsList("1, 2 ").orElse(Collections.emptyList())).contains( Duration.ofMillis(1), Duration.ofMillis(2) ); assertThat(StringExt.parseDurationMsList("1,2,3").orElse(Collections.emptyList())).contains( Duration.ofMillis(1), Duration.ofMillis(2), Duration.ofMillis(3) ); } @Test public void testGzipAndBase64Encode() { String input = "{aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:bbbbbbbbbbbbbbbbbbbbbbbbbbb}"; String output = StringExt.gzipAndBase64Encode(input); assertThat(output.length()).isLessThan(input.length()); } @Test public void testNameFromJavaBeanGetter() { assertNameFromJavaBeanGetterReturnsName("getMyName", "myName"); assertNameFromJavaBeanGetterReturnsName("isMyName", "myName"); assertNameFromJavaBeanGetterReturnsName("hasMyName", "myName"); assertNameFromJavaBeanGetterReturnsError("badPrefix"); assertNameFromJavaBeanGetterReturnsError(""); assertNameFromJavaBeanGetterReturnsError("has"); } private void assertNameFromJavaBeanGetterReturnsName(String methodName, String propertyName) { Either<String, IllegalArgumentException> result = StringExt.nameFromJavaBeanGetter(methodName); assertThat(result.hasValue()).isTrue(); assertThat(result.getValue()).isEqualTo(propertyName); } private void assertNameFromJavaBeanGetterReturnsError(String methodName) { Either<String, IllegalArgumentException> result = StringExt.nameFromJavaBeanGetter(methodName); assertThat(result.hasError()).isTrue(); } }
483
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/ExceptionExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ExceptionExtTest { @Test public void testToMessageChain() throws Exception { String messageChain = ExceptionExt.toMessageChain(new RuntimeException("outside", new Exception("inside"))); assertThat(messageChain).contains("(RuntimeException) outside -CAUSED BY-> (Exception) inside"); } }
484
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/ProtobufDiffTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.util.Optional; import com.google.protobuf.Message; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ProtobufDiffTest { @Test public void testNoDifferences() { Message one = ProtoMessageBuilder.newInner("value1", "value2"); Message other = ProtoMessageBuilder.newInner("value1", "value2"); assertThat(ProtobufExt.diffReport(one, other)).isNotPresent(); Message composed1 = ProtoMessageBuilder.newOuter(one, 5, one, other); Message composed2 = ProtoMessageBuilder.newOuter(one, 5, one, other); assertThat(ProtobufExt.diffReport(composed1, composed2)).isNotPresent(); } @Test public void testTopLevelDifferences() { Message one = ProtoMessageBuilder.newInner("value1", "value2"); Message other = ProtoMessageBuilder.newInner("value3", "value2"); Message another = ProtoMessageBuilder.newInner("value3", "value4"); Optional<String> diffOneOther = ProtobufExt.diffReport(one, other); assertThat(diffOneOther).hasValueSatisfying(report -> assertThat(report) .contains("stringField1") .doesNotContain("stringField2") ); Optional<String> diffOneAnother = ProtobufExt.diffReport(one, another); assertThat(diffOneAnother).hasValueSatisfying(report -> assertThat(report) .contains("stringField1") .contains("stringField2") ); } @Test public void testNestedDifferences() { Message one = ProtoMessageBuilder.newInner("value1", "value2"); Message other = ProtoMessageBuilder.newInner("value3", "value2"); Message another = ProtoMessageBuilder.newInner("value3", "value4"); Message composed1 = ProtoMessageBuilder.newOuter(one, 5, one, other); Message composed2 = ProtoMessageBuilder.newOuter(one, 4, one, other); Message composed3 = ProtoMessageBuilder.newOuter(other, 5, one, other); Message composed4 = ProtoMessageBuilder.newOuter(other, 3, one, another); Message composed5 = ProtoMessageBuilder.newOuter(other, 5); assertThat(ProtobufExt.diffReport(composed1, composed2)) .hasValueSatisfying(report -> assertThat(report) .contains("primitiveField") .doesNotContain("objectField") ); assertThat(ProtobufExt.diffReport(composed1, composed3)) .hasValueSatisfying(report -> assertThat(report) .contains("objectField.stringField1") .doesNotContain("objectField.stringField2") ); assertThat(ProtobufExt.diffReport(composed1, composed4)) .hasValueSatisfying(report -> assertThat(report) .contains("primitiveField") .contains("objectField.stringField1") .doesNotContain("objectField.stringField2") .doesNotContain("objectArrayField[0]") .doesNotContain("objectArrayField[1].stringField1") .contains("objectArrayField[1].stringField2") ); assertThat(ProtobufExt.diffReport(composed1, composed5)) .hasValueSatisfying(report -> assertThat(report) .doesNotContain("primitiveField") .contains("objectField.stringField1") .doesNotContain("objectField.stringField2") .contains("objectArrayField[0]") .contains("objectArrayField[1]") ); } }
485
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/ProtobufCopyTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.util.Collection; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.DynamicMessage; import com.google.protobuf.Message; import org.junit.BeforeClass; import org.junit.Test; import static com.netflix.titus.common.util.CollectionsExt.asSet; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class ProtobufCopyTest { private static Message OUTER_VALUE; @BeforeClass public static void setUp() throws Exception { Message innerValue = ProtoMessageBuilder.newInner("innerValue1", "innerValue2"); Message innerValue2 = ProtoMessageBuilder.newInner("inner2Value1", "inner2Value2"); OUTER_VALUE = ProtoMessageBuilder.newOuter(innerValue, 10, innerValue, innerValue2); } @Test public void testTopLevelFieldSelection() throws Exception { // Include all fields Message all = ProtobufExt.copy(OUTER_VALUE, asSet("objectField", "primitiveField")); FieldDescriptor objectField = ProtoMessageBuilder.getAndAssertField(OUTER_VALUE, "objectField"); FieldDescriptor primitiveField = ProtoMessageBuilder.getAndAssertField(OUTER_VALUE, "primitiveField"); assertFieldHasValue(all, objectField); assertFieldHasValue(all, primitiveField); // Include only second field Message secondOnly = ProtobufExt.copy(OUTER_VALUE, asSet("primitiveField")); assertFieldHasNoValue(secondOnly, objectField); assertFieldHasValue(secondOnly, primitiveField); } @Test public void testNestedSimpleFieldSelection() throws Exception { Message filtered = ProtobufExt.copy(OUTER_VALUE, asSet("objectField.stringField1", "primitiveField")); FieldDescriptor objectField = ProtoMessageBuilder.getAndAssertField(OUTER_VALUE, "objectField"); FieldDescriptor primitiveField = ProtoMessageBuilder.getAndAssertField(OUTER_VALUE, "primitiveField"); FieldDescriptor objectArrayField = ProtoMessageBuilder.getAndAssertField(OUTER_VALUE, "objectArrayField"); FieldDescriptor stringField1 = ProtoMessageBuilder.getAndAssertField(objectField.getMessageType(), "stringField1"); FieldDescriptor stringField2 = ProtoMessageBuilder.getAndAssertField(objectField.getMessageType(), "stringField2"); assertFieldHasValue(filtered, objectField); assertFieldHasValue((Message) filtered.getField(objectField), stringField1); assertFieldHasNoValue((Message) filtered.getField(objectField), stringField2); assertFieldHasValue(filtered, primitiveField); assertFieldHasNoValue(filtered, objectArrayField); } @Test public void testCollectionFieldSelection() throws Exception { Message filtered = ProtobufExt.copy(OUTER_VALUE, asSet("objectArrayField", "primitiveField")); FieldDescriptor objectField = OUTER_VALUE.getDescriptorForType().findFieldByName("objectField"); FieldDescriptor primitiveField = OUTER_VALUE.getDescriptorForType().findFieldByName("primitiveField"); FieldDescriptor objectArrayField = OUTER_VALUE.getDescriptorForType().findFieldByName("objectArrayField"); FieldDescriptor stringField1 = ProtoMessageBuilder.getAndAssertField(objectField.getMessageType(), "stringField1"); FieldDescriptor stringField2 = ProtoMessageBuilder.getAndAssertField(objectField.getMessageType(), "stringField2"); assertFieldHasNoValue(filtered, objectField); assertFieldHasValue(filtered, primitiveField); assertFieldHasValue(filtered, objectArrayField); Collection<Message> collection = (Collection<Message>) filtered.getField(objectArrayField); assertThat(collection).hasSize(2); for (Message inner : collection) { assertFieldHasValue(inner, stringField1); assertFieldHasValue(inner, stringField2); } } @Test public void testNestedCollectionFieldSelection() throws Exception { Message filtered = ProtobufExt.copy(OUTER_VALUE, asSet("objectArrayField.stringField1", "primitiveField")); FieldDescriptor objectField = OUTER_VALUE.getDescriptorForType().findFieldByName("objectField"); FieldDescriptor objectArrayField = OUTER_VALUE.getDescriptorForType().findFieldByName("objectArrayField"); FieldDescriptor stringField1 = ProtoMessageBuilder.getAndAssertField(objectField.getMessageType(), "stringField1"); FieldDescriptor stringField2 = ProtoMessageBuilder.getAndAssertField(objectField.getMessageType(), "stringField2"); assertFieldHasNoValue(filtered, objectField); assertFieldHasValue(filtered, objectArrayField); Collection<Message> collection = (Collection<Message>) filtered.getField(objectArrayField); for (Message inner : collection) { assertFieldHasValue(inner, stringField1); assertFieldHasNoValue(inner, stringField2); } } private void assertFieldHasValue(Message entity, FieldDescriptor field) { Object value = entity.getField(field); assertThat(value).isNotNull(); if (value instanceof DynamicMessage) { assertThat(((DynamicMessage) value).getAllFields()).isNotEmpty(); } else if (value instanceof Collection) { assertThat((Collection) value).isNotEmpty(); } else { assertThat(value).isNotNull(); } } private void assertFieldHasNoValue(Message entity, FieldDescriptor field) { Object value = entity.getField(field); if (value != null) { if (value instanceof DynamicMessage) { assertThat(((DynamicMessage) value).getAllFields()).isEmpty(); } else if (value instanceof String) { assertThat(value).isEqualTo(""); } else if (value instanceof Collection) { assertThat((Collection) value).isEmpty(); } else { fail("Expected null value for field " + field); } } } }
486
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/IOExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.util.List; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class IOExtTest { @Test public void testReadLines() throws Exception { File file = File.createTempFile("junit", ".txt", new File("build")); try (Writer fwr = new FileWriter(file)) { fwr.write("line1\n"); fwr.write("line2"); } List<String> lines = IOExt.readLines(file); assertThat(lines).containsExactly("line1", "line2"); } }
487
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/ReflectionExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.lang.reflect.Method; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.PostConstruct; import org.junit.Test; import static com.netflix.titus.common.util.ReflectionExt.isNumeric; import static org.assertj.core.api.Assertions.assertThat; public class ReflectionExtTest { private static final Set<String> SERVICE_METHOD_NAMES = Stream.of(MyService.class.getMethods()) .map(Method::getName) .collect(Collectors.toSet()); @Test public void testFindAnnotatedMethods() { List<Method> annotatedMethods = ReflectionExt.findAnnotatedMethods(new MyServiceImpl(), PostConstruct.class); assertThat(annotatedMethods).hasSize(1); assertThat(annotatedMethods.get(0).getName()).isEqualTo("classAnnotated"); } @Test public void testIsNumeric() throws Exception { assertThat(isNumeric(Integer.class)).isTrue(); assertThat(isNumeric(Long.class)).isTrue(); assertThat(isNumeric(IntegerHolder.class.getDeclaredField("intValue").getType())).isTrue(); } @Test public void testIsObjectMethod() { MyServiceImpl service = new MyServiceImpl(); for (Method method : service.getClass().getMethods()) { if (SERVICE_METHOD_NAMES.contains(method.getName())) { assertThat(ReflectionExt.isObjectMethod(method)).describedAs("Service method: %s", method).isFalse(); } else { assertThat(ReflectionExt.isObjectMethod(method)).isTrue(); } } } static class IntegerHolder { int intValue; } interface MyService { @PostConstruct void interfaceAnnotated(); void classAnnotated(); void notAnnotated(); } static class MyServiceImpl implements MyService { public void interfaceAnnotated() { } @PostConstruct public void classAnnotated() { } public void notAnnotated() { } @Override public String toString() { return "MyServiceImpl{}"; } } }
488
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/DateTimeExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.concurrent.TimeUnit; import org.junit.Test; import static com.netflix.titus.common.util.DateTimeExt.toRateString; import static com.netflix.titus.common.util.DateTimeExt.toTimeUnitString; import static org.assertj.core.api.Assertions.assertThat; public class DateTimeExtTest { @Test public void testUtcDateTimeStringConversion() { ZonedDateTime now = ZonedDateTime.now(); String expected = DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.of("UTC")).format(now) + 'Z'; String actual = DateTimeExt.toUtcDateTimeString(Instant.from(now).toEpochMilli()); assertThat(actual).isEqualTo(expected); } @Test public void testTime() { long msDuration = 123; assertThat(toTimeUnitString(msDuration)).isEqualTo("123ms"); long secDuration = 3 * 1000 + 123; assertThat(toTimeUnitString(secDuration)).isEqualTo("3s 123ms"); long minDuration = (2 * 60 + 3) * 1000 + 123; assertThat(toTimeUnitString(minDuration)).isEqualTo("2min 3s 123ms"); long hourDuration = ((1 * 60 + 2) * 60 + 3) * 1000 + 123; assertThat(toTimeUnitString(hourDuration)).isEqualTo("1h 2min 3s 123ms"); long oneSecond = 1 * 1000; assertThat(toTimeUnitString(oneSecond)).isEqualTo("1s"); long oneMillis = 1; assertThat(toTimeUnitString(oneMillis)).isEqualTo("1ms"); long zeroMillis = 0; assertThat(toTimeUnitString(zeroMillis)).isEqualTo("0ms"); long twoDays = TimeUnit.DAYS.toMillis(2); assertThat(toTimeUnitString(twoDays)).isEqualTo("2d"); } @Test public void testRoundedTime() { long msDuration = 123; assertThat(toTimeUnitString(msDuration, 2)).isEqualTo("123ms"); long secDuration = 3 * 1000 + 123; assertThat(toTimeUnitString(secDuration, 1)).isEqualTo("3s"); assertThat(toTimeUnitString(secDuration, 2)).isEqualTo("3s 123ms"); long minDuration = (2 * 60 + 3) * 1000 + 123; assertThat(toTimeUnitString(minDuration, 1)).isEqualTo("2min"); assertThat(toTimeUnitString(minDuration, 2)).isEqualTo("2min 3s"); assertThat(toTimeUnitString(minDuration, 3)).isEqualTo("2min 3s 123ms"); long hourDuration = ((1 * 60 + 2) * 60 + 3) * 1000 + 123; assertThat(toTimeUnitString(hourDuration, 1)).isEqualTo("1h"); assertThat(toTimeUnitString(hourDuration, 2)).isEqualTo("1h 2min"); assertThat(toTimeUnitString(hourDuration, 3)).isEqualTo("1h 2min 3s"); assertThat(toTimeUnitString(hourDuration, 4)).isEqualTo("1h 2min 3s 123ms"); long oneSecond = 1 * 1000; assertThat(toTimeUnitString(oneSecond, 2)).isEqualTo("1s"); long oneMillis = 1; assertThat(toTimeUnitString(oneMillis, 2)).isEqualTo("1ms"); long zeroMillis = 0; assertThat(toTimeUnitString(zeroMillis, 2)).isEqualTo("0ms"); long twoDays = TimeUnit.DAYS.toMillis(2); assertThat(toTimeUnitString(twoDays, 2)).isEqualTo("2d"); } @Test public void testToRateString() { assertThat(toRateString(1, 1, TimeUnit.MILLISECONDS, "action")).isEqualTo("1.00 action/ms"); assertThat(toRateString(60, 5, TimeUnit.SECONDS, "action")).isEqualTo("5.00 action/min"); } @Test public void testFromMillis() { long timestamp = 1234; OffsetDateTime dateTime = DateTimeExt.fromMillis(timestamp); assertThat(dateTime.toInstant().toEpochMilli()).isEqualTo(timestamp); } }
489
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/GraphExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.util.Arrays; import java.util.List; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class GraphExtTest { @Test public void testOrdering() throws Exception { // Already in order List<Character> ordered = GraphExt.order(Arrays.asList('A', 'B', 'C'), (s1, s2) -> s1 == 'A' && s2 == 'C'); assertThat(ordered).containsExactlyInAnyOrder('A', 'B', 'C'); // Out of order List<Character> notOrdered = GraphExt.order(Arrays.asList('A', 'B', 'C'), (s1, s2) -> s1 == 'C' && s2 == 'A'); assertThat(notOrdered).containsExactlyInAnyOrder('B', 'C', 'A'); } }
490
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/PropertiesExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; import static com.netflix.titus.common.util.CollectionsExt.asMap; import static com.netflix.titus.common.util.CollectionsExt.asSet; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class PropertiesExtTest { @Test public void testSplitByRootName() throws Exception { Map<String, String> properties = asMap( "my.a", "valueA", "my.b", "valueB", "your.x", "valueX", "your.y", "valueY" ); Map<String, Map<String, String>> groups = PropertiesExt.groupByRootName(properties, 1); assertThat(groups).hasSize(2); assertThat(groups.get("my")).containsAllEntriesOf(asMap("a", "valueA", "b", "valueB")); assertThat(groups.get("your")).containsAllEntriesOf(asMap("y", "valueX", "y", "valueY")); } @Test public void testGetPropertiesOf() throws Exception { Map<String, String> properties = asMap( "root.my.a", "valueA", "root.my.b", "valueB", "your.x", "valueX" ); Map<String, String> subProps = PropertiesExt.getPropertiesOf("root.my", properties); assertThat(subProps).containsAllEntriesOf(asMap("a", "valueA", "b", "valueB")); } @Test public void testVerifyRootName() throws Exception { Map<String, String> properties = asMap( "my", "valueA", "your.x", "valueX", "their.y", "valueY" ); List<String> notMatching = PropertiesExt.verifyRootNames(properties, asSet("my", "your")); assertThat(notMatching).containsExactly("their.y"); } @Test public void testGetRootNames() { Set<String> result = PropertiesExt.getRootNames(asList("top1.a", "top2.b", "single"), 1); assertThat(result).contains("top1", "top2"); } @Test public void testSplitNames() throws Exception { Map<String, Set<String>> result = PropertiesExt.splitNames(asList("top1", "top2.nested2"), 1); assertThat(result).containsEntry("top1", null); assertThat(result).containsEntry("top2", asSet("nested2")); } @Test public void testFullSplit() throws Exception { PropertiesExt.PropertyNode<Boolean> result = PropertiesExt.fullSplit(asList("top1", "top2.nested2")); assertThat(result.getChildren()).containsKeys("top1", "top2"); assertThat(result.getChildren().get("top1").getValue()).contains(true); assertThat(result.getChildren().get("top2").getValue()).isEmpty(); assertThat(result.getChildren().get("top2").getChildren()).containsKeys("nested2"); assertThat(result.getChildren().get("top2").getChildren().get("nested2").getValue()).contains(true); } }
491
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/EvaluatorsTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class EvaluatorsTest { private static final RuntimeException SIMULATED_ERROR = new RuntimeException("simulated error"); private int counter; @Test public void testMemoizeLast() { Function<String, String> evaluator = Evaluators.memoizeLast(s -> { counter++; return ("" + s).toUpperCase(); }); assertThat(evaluator.apply("a")).isEqualTo("A"); assertThat(evaluator.apply("a")).isEqualTo("A"); assertThat(counter).isEqualTo(1); assertThat(evaluator.apply(null)).isEqualTo("NULL"); assertThat(evaluator.apply(null)).isEqualTo("NULL"); assertThat(counter).isEqualTo(2); assertThat(evaluator.apply("b")).isEqualTo("B"); assertThat(evaluator.apply("b")).isEqualTo("B"); assertThat(counter).isEqualTo(3); } @Test public void testMemoizeLastError() { Function<String, String> evaluator = Evaluators.memoizeLast(s -> { counter++; if (s.equals("error")) { throw SIMULATED_ERROR; } return s.toUpperCase(); }); applyWithErrorResult(evaluator); applyWithErrorResult(evaluator); assertThat(counter).isEqualTo(1); assertThat(evaluator.apply("a")).isEqualTo("A"); assertThat(counter).isEqualTo(2); } @Test public void testMemoizeLastWithBiFunction() { AtomicInteger counter = new AtomicInteger(0); Function<String, Integer> timesCalled = Evaluators.memoizeLast((input, lastResult) -> counter.incrementAndGet()); for (int i = 0; i < 5; i++) { assertThat(timesCalled.apply("foo")).isEqualTo(1); } for (int i = 0; i < 5; i++) { assertThat(timesCalled.apply("bar")).isEqualTo(2); } // no caching if inputs are different assertThat(timesCalled.apply("foo")).isEqualTo(3); assertThat(timesCalled.apply("bar")).isEqualTo(4); } private void applyWithErrorResult(Function<String, String> evaluator) { try { evaluator.apply("error"); } catch (RuntimeException e) { assertThat(e.getMessage()).contains("simulated error"); } } }
492
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/NetworkExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.util.List; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class NetworkExtTest { @Test public void testToIPv4() { long address = (((((1L << 8) | 1) << 8) | 1) << 8) | 1; assertThat(NetworkExt.toIPv4(address)).isEqualTo("1.1.1.1"); } @Test public void testGetLocalIPs() { List<String> allIps = NetworkExt.getLocalIPs(false).orElse(null); assertThat(allIps).isNotNull(); assertThat(allIps).allSatisfy(address -> assertThat(NetworkExt.isIpV4(address) || NetworkExt.isIPv6(address)).isTrue()); } @Test public void testGetLocalIPsV4Only() { List<String> allIps = NetworkExt.getLocalIPs().orElse(null); assertThat(allIps).isNotNull(); assertThat(allIps).allSatisfy(address -> assertThat(NetworkExt.isIpV4(address)).isTrue()); } }
493
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/MathExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import org.assertj.core.api.Assertions; import org.junit.Test; public class MathExtTest { @Test public void testScaleBetween0And1() { double scaledValue = MathExt.scale(10.0, 0.0, 100.0); Assertions.assertThat(scaledValue).isEqualTo(0.1); } @Test(expected = IllegalArgumentException.class) public void testScaleMinAndMaxValidation() { MathExt.scale(10.0, 10.0, 10.0); } @Test public void testScaleBetween1and10() { double scaledValue = MathExt.scale(10.0, 0.0, 100.0, 0.0, 10.0); Assertions.assertThat(scaledValue).isEqualTo(1.0); } @Test(expected = IllegalArgumentException.class) public void testScaleRangeValueValidation() { MathExt.scale(10.0, 9.0, 10.0, 10.0, 9.0); } @Test public void testBetween0And1() { Assertions.assertThat(MathExt.between(1.1, 0.0, 1.0)).isEqualTo(1.0); Assertions.assertThat(MathExt.between(1.0, 2.0, 10.0)).isEqualTo(2.0); Assertions.assertThat(MathExt.between(0.5, 0.0, 1.0)).isEqualTo(0.5); } @Test public void testBetween0And1Long() { Assertions.assertThat(MathExt.between(0, 5, 10)).isEqualTo(5); Assertions.assertThat(MathExt.between(1, 2, 10)).isEqualTo(2); Assertions.assertThat(MathExt.between(5, 0, 10)).isEqualTo(5); } }
494
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/RegExpExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class RegExpExtTest { @Test public void testDynamicMatcher() { String message = "hello\nend"; boolean matches = RegExpExt.dynamicMatcher(() -> ".*hello.*", Pattern.DOTALL, e -> { throw new IllegalStateException(e); }).apply(message).matches(); assertThat(matches).isTrue(); } @Test public void testDynamicModifications() { String message = "hello\nend"; AtomicReference<String> config = new AtomicReference<>(".*hello.*"); Function<String, Matcher> matcher = RegExpExt.dynamicMatcher(() -> config.get(), Pattern.DOTALL, e -> { throw new IllegalStateException(e); }); assertThat(matcher.apply(message).matches()).isTrue(); config.set(".*foobar.*"); assertThat(matcher.apply(message).matches()).isFalse(); } }
495
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/TimeSeriesDataTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util; import java.util.concurrent.TimeUnit; import com.netflix.titus.common.util.time.Clocks; import com.netflix.titus.common.util.time.TestClock; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class TimeSeriesDataTest { private static final long RETENTION_MS = 60_000; private static final long STEP_MS = 1_000; private final TestClock testClock = Clocks.test(); private final TimeSeriesData timeSeriesData = new TimeSeriesData( RETENTION_MS, STEP_MS, (value, delayMs) -> value / (1 + delayMs / 1_000), testClock ); @Test public void testAggregate() { timeSeriesData.add(30, testClock.wallTime()); testClock.advanceTime(2_000, TimeUnit.MILLISECONDS); timeSeriesData.add(20, testClock.wallTime()); assertThat(timeSeriesData.getAggregatedValue()).isEqualTo(30); } @Test public void testDataExpiry() { timeSeriesData.add(10, testClock.wallTime()); testClock.advanceTime(60_000, TimeUnit.MILLISECONDS); timeSeriesData.add(10, testClock.wallTime()); assertThat(timeSeriesData.getAggregatedValue()).isEqualTo(10); } @Test public void testClear() { timeSeriesData.add(10, testClock.wallTime()); timeSeriesData.clear(); assertThat(timeSeriesData.getAggregatedValue()).isEqualTo(0); } }
496
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/unit/TimeUnitExtTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.unit; import java.util.Optional; import java.util.concurrent.TimeUnit; import com.netflix.titus.common.util.tuple.Pair; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class TimeUnitExtTest { @Test public void testParse() { testParse("1ms", 1, TimeUnit.MILLISECONDS); testParse("2s", 2, TimeUnit.SECONDS); testParse("3m", 3, TimeUnit.MINUTES); testParse("4h", 4, TimeUnit.HOURS); testParse("5d", 5, TimeUnit.DAYS); } @Test public void testParseWithInvalidData() { assertThat(TimeUnitExt.parse("1b2mss")).isNotPresent(); } @Test public void testToMillis() { assertThat(TimeUnitExt.toMillis("1m").get()).isEqualTo(60_000); } private void testParse(String value, long expectedInterval, TimeUnit expectedUnit) { Optional<Pair<Long, TimeUnit>> result = TimeUnitExt.parse(value); assertThat(result).isPresent(); assertThat(result.get().getLeft()).isEqualTo(expectedInterval); assertThat(result.get().getRight()).isEqualTo(expectedUnit); } }
497
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/unit/MemoryUnitTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.unit; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class MemoryUnitTest { @Test public void testParsing() throws Exception { assertThat(MemoryUnit.bytesOf("100b")).isEqualTo(100); assertThat(MemoryUnit.bytesOf(" 100 BYTES ")).isEqualTo(100); assertThat(MemoryUnit.bytesOf("100k")).isEqualTo(100 * MemoryUnit._1KB); assertThat(MemoryUnit.bytesOf(" 100 KB ")).isEqualTo(100 * MemoryUnit._1KB); assertThat(MemoryUnit.bytesOf("100m")).isEqualTo(100 * MemoryUnit._1MB); assertThat(MemoryUnit.bytesOf(" 100 MB ")).isEqualTo(100 * MemoryUnit._1MB); assertThat(MemoryUnit.bytesOf("100g")).isEqualTo(100 * MemoryUnit._1GB); assertThat(MemoryUnit.bytesOf(" 100 GB ")).isEqualTo(100 * MemoryUnit._1GB); } }
498
0
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/util/unit/BandwidthUnitTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.unit; import org.junit.Test; import static com.netflix.titus.common.util.unit.BandwidthUnit._1G; import static com.netflix.titus.common.util.unit.BandwidthUnit._1K; import static com.netflix.titus.common.util.unit.BandwidthUnit._1M; import static org.assertj.core.api.Assertions.assertThat; public class BandwidthUnitTest { @Test public void testParsing() throws Exception { assertThat(BandwidthUnit.bpsOf("100b")).isEqualTo(100); assertThat(BandwidthUnit.bpsOf(" 100 BPS ")).isEqualTo(100); assertThat(BandwidthUnit.bpsOf("100k")).isEqualTo(100 * _1K); assertThat(BandwidthUnit.bpsOf(" 100 KBps ")).isEqualTo(100 * _1K); assertThat(BandwidthUnit.bpsOf("100m")).isEqualTo(100 * _1M); assertThat(BandwidthUnit.bpsOf(" 100 MBps ")).isEqualTo(100 * _1M); assertThat(BandwidthUnit.bpsOf("100g")).isEqualTo(100 * _1G); assertThat(BandwidthUnit.bpsOf(" 100 GBps ")).isEqualTo(100 * _1G); } }
499