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-api/src/main/java/com/netflix/titus/api/supervisor | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service/SupervisorServiceException.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.api.supervisor.service;
import com.netflix.titus.api.supervisor.model.MasterInstance;
import static java.lang.String.format;
public class SupervisorServiceException extends RuntimeException {
public enum ErrorCode {
MasterInstanceNotFound,
NotLeader,
}
private final ErrorCode errorCode;
private SupervisorServiceException(ErrorCode errorCode, String message) {
this(errorCode, message, null);
}
private SupervisorServiceException(ErrorCode errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public ErrorCode getErrorCode() {
return errorCode;
}
public static SupervisorServiceException masterInstanceNotFound(String instanceId) {
return new SupervisorServiceException(ErrorCode.MasterInstanceNotFound, format("TitusMaster instance with id %s does not exist", instanceId));
}
public static SupervisorServiceException notLeader(MasterInstance currentMasterInstance) {
return new SupervisorServiceException(ErrorCode.NotLeader, String.format("TitusMaster instance %s is not a leader", currentMasterInstance.getInstanceId()));
}
}
| 9,700 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service/MasterMonitor.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.api.supervisor.service;
import java.util.List;
import com.netflix.titus.api.supervisor.model.MasterInstance;
import rx.Completable;
import rx.Observable;
public interface MasterMonitor {
@Deprecated
Observable<MasterDescription> getLeaderObservable();
@Deprecated
MasterDescription getLatestLeader();
/**
* Get current {@link MasterInstance} value. This method never returns null.
*/
MasterInstance getCurrentMasterInstance();
/**
* Update the local {@link MasterInstance} data record.
*/
Completable updateOwnMasterInstance(MasterInstance self);
/**
* On subscribe emits information about all known TitusMaster instances. Next, emit the full list of known
* instances whenever anything changes.
*/
Observable<List<MasterInstance>> observeMasters();
}
| 9,701 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service/LeaderElector.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.api.supervisor.service;
import com.netflix.titus.api.supervisor.model.MasterState;
import rx.Observable;
/**
* Leader elector interface.
*/
public interface LeaderElector {
/**
* Instruct the {@link LeaderElector} instance to join the leader election process.
*/
boolean join();
/**
* Instruct the {@link LeaderElector} instance to leave the leader election process. If the current TitusMaster
* is already the leader, does not do anything.
*/
boolean leaveIfNotLeader();
/**
* Emits {@link MasterState#LeaderActivating} when the given instance of TitusMaster becomes the leader, and
* starts the activation process. Emits {@link MasterState#LeaderActivated} when the activation process is
* completed, and than completes. When subscription happens after the activation happened, the observable
* emits {@link MasterState#LeaderActivated} immediately and completes.
*/
Observable<MasterState> awaitElection();
}
| 9,702 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service/LocalMasterReadinessResolver.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.api.supervisor.service;
import com.netflix.titus.api.supervisor.model.ReadinessStatus;
import reactor.core.publisher.Flux;
/**
* A given master instance can join a leader election process when multiple criteria are met. For example:
* <ul>
* <li>bootstrap process has finished</li>
* <li>an instance is health/li>
* <li>an administrator configured the instance to be part of the leader election process</li>
* <p>
* {@link LocalMasterReadinessResolver} implementations provide different readiness checks. A given master instance
* is ready, if all the constituents agree on it.
*/
public interface LocalMasterReadinessResolver {
Flux<ReadinessStatus> observeLocalMasterReadinessUpdates();
}
| 9,703 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service/SupervisorOperations.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.api.supervisor.service;
import java.util.List;
import java.util.Optional;
import com.netflix.titus.api.supervisor.model.MasterInstance;
import com.netflix.titus.api.supervisor.model.event.SupervisorEvent;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import rx.Observable;
public interface SupervisorOperations {
String COMPONENT = "supervisor";
List<MasterInstance> getMasterInstances();
Optional<MasterInstance> findMasterInstance(String instanceId);
MasterInstance getMasterInstance(String instanceId);
Optional<MasterInstance> findLeader();
Observable<SupervisorEvent> events();
void stopBeingLeader(CallMetadata callMetadata);
}
| 9,704 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service/LocalMasterInstanceResolver.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.api.supervisor.service;
import com.netflix.titus.api.supervisor.model.MasterInstance;
import reactor.core.publisher.Flux;
/**
* Each cluster/supervised member must resolve its own state and advertise it to other members.
* This interface is implemented by components providing their own state resolution strategies.
*/
public interface LocalMasterInstanceResolver {
/**
* Emits the current member state, and state updates subsequently. The stream never completes, unless explicitly
* terminated by a subscriber.
*/
Flux<MasterInstance> observeLocalMasterInstanceUpdates();
}
| 9,705 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service/MasterDescription.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.api.supervisor.service;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import com.netflix.titus.api.supervisor.model.MasterInstance;
/**
* A JSON-serializable data transfer object for Titus master descriptions. It's used to transfer
* metadata between master and workers.
*
* Use {@link MasterInstance} instead.
*/
@Deprecated
public class MasterDescription {
public static final String JSON_PROP_HOSTNAME = "hostname";
public static final String JSON_PROP_HOST_IP = "hostIP";
public static final String JSON_PROP_API_PORT = "apiPort";
public static final String JSON_PROP_API_STATUS_URI = "apiStatusUri";
public static final String JSON_PROP_CREATE_TIME = "createTime";
private final String hostname;
private final String hostIP;
private final int apiPort;
private final String apiStatusUri;
private final long createTime;
@JsonCreator
@JsonIgnoreProperties(ignoreUnknown = true)
public MasterDescription(
@JsonProperty(JSON_PROP_HOSTNAME) String hostname,
@JsonProperty(JSON_PROP_HOST_IP) String hostIP,
@JsonProperty(JSON_PROP_API_PORT) int apiPort,
@JsonProperty(JSON_PROP_API_STATUS_URI) String apiStatusUri,
@JsonProperty(JSON_PROP_CREATE_TIME) long createTime
) {
this.hostname = hostname;
this.hostIP = hostIP;
this.apiPort = apiPort;
this.apiStatusUri = apiStatusUri;
this.createTime = createTime;
}
@JsonProperty(JSON_PROP_HOSTNAME)
public String getHostname() {
return hostname;
}
@JsonProperty(JSON_PROP_HOST_IP)
public String getHostIP() {
return hostIP;
}
@JsonProperty(JSON_PROP_API_PORT)
public int getApiPort() {
return apiPort;
}
@JsonProperty(JSON_PROP_API_STATUS_URI)
public String getApiStatusUri() {
return apiStatusUri;
}
@JsonProperty(JSON_PROP_CREATE_TIME)
public long getCreateTime() {
return createTime;
}
public String getFullApiStatusUri() {
String uri = getApiStatusUri().trim();
if (uri.startsWith("/")) {
uri = uri.substring(1);
}
return String.format("http://%s:%d/%s", getHostname(), getApiPort(), uri);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("hostname", hostname)
.add("hostIP", hostIP)
.add("apiPort", apiPort)
.add("apiStatusUri", apiStatusUri)
.add("createTime", createTime)
.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MasterDescription that = (MasterDescription) o;
if (apiPort != that.apiPort) {
return false;
}
if (createTime != that.createTime) {
return false;
}
if (apiStatusUri != null ? !apiStatusUri.equals(that.apiStatusUri) : that.apiStatusUri != null) {
return false;
}
if (hostIP != null ? !hostIP.equals(that.hostIP) : that.hostIP != null) {
return false;
}
return hostname != null ? hostname.equals(that.hostname) : that.hostname == null;
}
@Override
public int hashCode() {
int result = hostname != null ? hostname.hashCode() : 0;
result = 31 * result + (hostIP != null ? hostIP.hashCode() : 0);
result = 31 * result + apiPort;
result = 31 * result + (apiStatusUri != null ? apiStatusUri.hashCode() : 0);
result = 31 * result + (int) (createTime ^ (createTime >>> 32));
return result;
}
}
| 9,706 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service/LeaderActivator.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.api.supervisor.service;
/**
* Counterpart of {@link LeaderElector} that performs lead activation/inactivation mechanics.
*/
public interface LeaderActivator {
String COMPONENT = "clusterManager";
long getElectionTimestamp();
long getActivationEndTimestamp();
long getActivationTime();
boolean isLeader();
boolean isActivated();
void becomeLeader();
void stopBeingLeader();
}
| 9,707 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service/resolver/AlwaysEnabledLocalMasterReadinessResolver.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.api.supervisor.service.resolver;
import com.netflix.titus.api.supervisor.model.ReadinessState;
import com.netflix.titus.api.supervisor.model.ReadinessStatus;
import com.netflix.titus.api.supervisor.service.LocalMasterReadinessResolver;
import reactor.core.publisher.Flux;
public class AlwaysEnabledLocalMasterReadinessResolver implements LocalMasterReadinessResolver {
private static final ReadinessStatus ALWAYS_READY = ReadinessStatus.newBuilder()
.withState(ReadinessState.Enabled)
.withMessage("Always enabled")
.build();
private static final AlwaysEnabledLocalMasterReadinessResolver INSTANCE = new AlwaysEnabledLocalMasterReadinessResolver();
private AlwaysEnabledLocalMasterReadinessResolver() {
}
@Override
public Flux<ReadinessStatus> observeLocalMasterReadinessUpdates() {
return Flux.just(ALWAYS_READY).concatWith(Flux.never());
}
public static LocalMasterReadinessResolver getInstance() {
return INSTANCE;
}
}
| 9,708 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service/resolver/PollingLocalMasterReadinessResolver.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.api.supervisor.service.resolver;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.PreDestroy;
import com.netflix.titus.api.supervisor.model.MasterInstanceFunctions;
import com.netflix.titus.api.supervisor.model.ReadinessStatus;
import com.netflix.titus.api.supervisor.service.LocalMasterReadinessResolver;
import com.netflix.titus.common.framework.scheduler.ScheduleReference;
import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.rx.ReactorExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
public class PollingLocalMasterReadinessResolver implements LocalMasterReadinessResolver {
private static final Logger logger = LoggerFactory.getLogger(PollingLocalMasterReadinessResolver.class);
private final AtomicReference<ReadinessStatus> readinessStatusRef = new AtomicReference<>();
private final DirectProcessor<ReadinessStatus> readinessUpdatesProcessor = DirectProcessor.create();
private final ScheduleReference refreshReference;
private PollingLocalMasterReadinessResolver(Mono<ReadinessStatus> readinessStatusMono,
ScheduleDescriptor scheduleDescriptor,
TitusRuntime titusRuntime,
Scheduler scheduler) {
readinessStatusRef.set(ReadinessStatus.notReadyNow(titusRuntime.getClock().wallTime()));
refreshReference = titusRuntime.getLocalScheduler().scheduleMono(
scheduleDescriptor,
context ->
readinessStatusMono
.doOnNext(this::process)
.ignoreElement()
.cast(Void.class),
scheduler
);
}
@PreDestroy
public void shutdown() {
refreshReference.cancel();
readinessUpdatesProcessor.onComplete();
}
@Override
public Flux<ReadinessStatus> observeLocalMasterReadinessUpdates() {
return readinessUpdatesProcessor
.transformDeferred(ReactorExt.head(() -> Collections.singletonList(readinessStatusRef.get())))
.transformDeferred(ReactorExt.badSubscriberHandler(logger));
}
private void process(ReadinessStatus newReadinessStatus) {
if (newReadinessStatus == null) {
return;
}
ReadinessStatus previousReadinessStatus = readinessStatusRef.get();
if (MasterInstanceFunctions.areDifferent(newReadinessStatus, previousReadinessStatus)) {
logger.info("Changing Master readiness status: previous={}, new={}", previousReadinessStatus, newReadinessStatus);
} else {
logger.debug("Master readiness status not changed: current={}", previousReadinessStatus);
}
readinessStatusRef.set(newReadinessStatus);
readinessUpdatesProcessor.onNext(newReadinessStatus);
}
public static PollingLocalMasterReadinessResolver newPollingResolver(Mono<ReadinessStatus> readinessStatusMono,
ScheduleDescriptor scheduleDescriptor,
TitusRuntime titusRuntime,
Scheduler scheduler) {
return new PollingLocalMasterReadinessResolver(readinessStatusMono, scheduleDescriptor, titusRuntime, scheduler);
}
}
| 9,709 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/supervisor/service/resolver/AggregatingLocalMasterReadinessResolver.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.api.supervisor.service.resolver;
import java.util.List;
import java.util.stream.Collectors;
import com.netflix.titus.api.supervisor.model.ReadinessState;
import com.netflix.titus.api.supervisor.model.ReadinessStatus;
import com.netflix.titus.api.supervisor.service.LocalMasterReadinessResolver;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.time.Clock;
import reactor.core.publisher.Flux;
public class AggregatingLocalMasterReadinessResolver implements LocalMasterReadinessResolver {
private final Flux<ReadinessStatus> stream;
private final Clock clock;
public AggregatingLocalMasterReadinessResolver(List<LocalMasterReadinessResolver> delegates, TitusRuntime titusRuntime) {
this.clock = titusRuntime.getClock();
this.stream = Flux.combineLatest(
delegates.stream().map(LocalMasterReadinessResolver::observeLocalMasterReadinessUpdates).collect(Collectors.toList()),
this::combine
);
}
@Override
public Flux<ReadinessStatus> observeLocalMasterReadinessUpdates() {
return stream;
}
private ReadinessStatus combine(Object[] values) {
for (Object value : values) {
ReadinessStatus status = (ReadinessStatus) value;
if (status.getState() != ReadinessState.Enabled) {
return status;
}
}
return ReadinessStatus.newBuilder()
.withState(ReadinessState.Enabled)
.withMessage("All master readiness components report status Enabled")
.withTimestamp(clock.wallTime())
.build();
}
}
| 9,710 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/store | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/store/v2/ResourceDimensionMixin.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.api.store.v2;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class ResourceDimensionMixin {
@JsonCreator
public ResourceDimensionMixin(@JsonProperty("cpu") double cpu,
@JsonProperty("gpu") long gpu,
@JsonProperty("memoryMB") long memoryMB,
@JsonProperty("diskMB") long diskMB,
@JsonProperty("networkMbs") long networkMbs,
@JsonProperty("opportunisticCpu") long opportunisticCpu) {
}
}
| 9,711 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/store | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/store/v2/ApplicationSlaMixIn.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.api.store.v2;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.netflix.titus.api.model.ResourceDimension;
import com.netflix.titus.api.model.Tier;
import static com.netflix.titus.api.model.SchedulerConstants.SCHEDULER_NAME_FENZO;
/**
* To better decouple service layer model from the persistence layer, we provide serialization
* specific annotations via Jackson mix-ins.
*/
public abstract class ApplicationSlaMixIn {
@JsonCreator
public ApplicationSlaMixIn(
@JsonProperty("appName") String appName,
@JsonProperty("tier") Tier tier,
@JsonProperty("resourceDimension") ResourceDimension resourceDimension,
@JsonProperty("instanceCount") int instanceCount,
@JsonProperty(value = "schedulerName", defaultValue = SCHEDULER_NAME_FENZO) String schedulerName,
@JsonProperty("resourcePool") String resourcePool) {
}
}
| 9,712 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/store/v2 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/store/v2/exception/TitusStoreException.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.api.store.v2.exception;
public class TitusStoreException extends RuntimeException {
public TitusStoreException(String message) {
super(message);
}
public TitusStoreException(String message, Throwable cause) {
super(message, cause);
}
}
| 9,713 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/store/v2 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/store/v2/exception/NotFoundException.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.api.store.v2.exception;
public class NotFoundException extends TitusStoreException {
public NotFoundException(Class<?> type, String key) {
super("Not found " + type.getSimpleName() + " with key " + key);
}
}
| 9,714 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model/SystemDisruptionBudget.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.api.eviction.model;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import com.google.common.base.Preconditions;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.TimeWindow;
import com.netflix.titus.api.model.FixedIntervalTokenBucketRefillPolicy;
import com.netflix.titus.api.model.TokenBucketPolicy;
import com.netflix.titus.api.model.reference.Reference;
public class SystemDisruptionBudget {
private final Reference reference;
private final TokenBucketPolicy tokenBucketPolicy;
private final List<TimeWindow> timeWindows;
public SystemDisruptionBudget(Reference reference, TokenBucketPolicy tokenBucketPolicy, List<TimeWindow> timeWindows) {
this.reference = reference;
this.tokenBucketPolicy = tokenBucketPolicy;
this.timeWindows = timeWindows;
}
public Reference getReference() {
return reference;
}
public TokenBucketPolicy getTokenBucketPolicy() {
return tokenBucketPolicy;
}
public List<TimeWindow> getTimeWindows() {
return timeWindows;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SystemDisruptionBudget that = (SystemDisruptionBudget) o;
return Objects.equals(reference, that.reference) &&
Objects.equals(tokenBucketPolicy, that.tokenBucketPolicy) &&
Objects.equals(timeWindows, that.timeWindows);
}
@Override
public int hashCode() {
return Objects.hash(reference, tokenBucketPolicy, timeWindows);
}
@Override
public String toString() {
return "SystemDisruptionBudget{" +
"reference=" + reference +
", tokenBucketPolicy=" + tokenBucketPolicy +
", timeWindows=" + timeWindows +
'}';
}
public Builder toBuilder() {
return newBuilder().withReference(reference).withTokenBucketDescriptor(tokenBucketPolicy);
}
public static SystemDisruptionBudget newBasicSystemDisruptionBudget(long refillRatePerSecond, long capacity, TimeWindow... timeWindows) {
return newBuilder()
.withReference(Reference.system())
.withTokenBucketDescriptor(TokenBucketPolicy.newBuilder()
.withInitialNumberOfTokens(0)
.withCapacity(capacity)
.withRefillPolicy(FixedIntervalTokenBucketRefillPolicy.newBuilder()
.withNumberOfTokensPerInterval(refillRatePerSecond)
.withIntervalMs(1_000)
.build()
)
.build()
)
.withTimeWindows(timeWindows.length == 0 ? Collections.emptyList() : Arrays.asList(timeWindows))
.build();
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private Reference reference;
private TokenBucketPolicy tokenBucketPolicy;
private List<TimeWindow> timeWindows;
private Builder() {
}
public Builder withReference(Reference reference) {
this.reference = reference;
return this;
}
public Builder withTokenBucketDescriptor(TokenBucketPolicy tokenBucketPolicy) {
this.tokenBucketPolicy = tokenBucketPolicy;
return this;
}
public Builder withTimeWindows(List<TimeWindow> timeWindows) {
this.timeWindows = timeWindows;
return this;
}
public SystemDisruptionBudget build() {
Preconditions.checkNotNull(reference, "Reference is null");
Preconditions.checkNotNull(tokenBucketPolicy, "Token bucket is null");
Preconditions.checkNotNull(timeWindows, "Time windows collection is null");
return new SystemDisruptionBudget(reference, tokenBucketPolicy, timeWindows);
}
}
}
| 9,715 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model/EvictionQuota.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.api.eviction.model;
import java.util.Objects;
import com.google.common.base.Preconditions;
import com.netflix.titus.api.model.Tier;
import com.netflix.titus.api.model.reference.Reference;
public class EvictionQuota {
private final Reference reference;
private final long quota;
private final String message;
public EvictionQuota(Reference reference, long quota, String message) {
this.reference = reference;
this.quota = quota;
this.message = message;
}
public Reference getReference() {
return reference;
}
public long getQuota() {
return quota;
}
public String getMessage() {
return message;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EvictionQuota that = (EvictionQuota) o;
return quota == that.quota &&
Objects.equals(reference, that.reference) &&
Objects.equals(message, that.message);
}
@Override
public int hashCode() {
return Objects.hash(reference, quota, message);
}
@Override
public String toString() {
return "EvictionQuota{" +
"reference=" + reference +
", quota=" + quota +
", message='" + message + '\'' +
'}';
}
public Builder toBuilder() {
return newBuilder().withReference(reference).withQuota(quota).withMessage(message);
}
public static EvictionQuota emptyQuota(Reference reference) {
return newBuilder()
.withReference(reference)
.withQuota(0L)
.withMessage("Empty")
.build();
}
public static EvictionQuota unlimited(Reference reference) {
return newBuilder()
.withReference(reference)
.withQuota(Long.MAX_VALUE / 2)
.withMessage("No limits")
.build();
}
public static EvictionQuota systemQuota(long quota, String message) {
return newBuilder()
.withReference(Reference.system())
.withQuota(quota)
.withMessage(message)
.build();
}
public static EvictionQuota tierQuota(Tier tier, int quota, String message) {
return newBuilder()
.withReference(Reference.tier(tier))
.withQuota(quota)
.withMessage(message)
.build();
}
public static EvictionQuota jobQuota(String jobId, long quota, String message) {
return newBuilder()
.withReference(Reference.job(jobId))
.withQuota(quota)
.withMessage(message)
.build();
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private Reference reference;
private long quota;
private String message;
private Builder() {
}
public Builder withReference(Reference reference) {
this.reference = reference;
return this;
}
public Builder withQuota(long quota) {
this.quota = quota;
return this;
}
public Builder withMessage(String message, Object... args) {
this.message = args.length > 0 ? String.format(message, args) : message;
return this;
}
public EvictionQuota build() {
Preconditions.checkNotNull(reference, "Reference not set");
Preconditions.checkNotNull(message, "Message not set");
return new EvictionQuota(reference, quota, message);
}
}
}
| 9,716 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model/event/EvictionQuotaEvent.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.api.eviction.model.event;
import java.util.Objects;
import com.netflix.titus.api.eviction.model.EvictionQuota;
public class EvictionQuotaEvent extends EvictionEvent {
private final EvictionQuota quota;
public EvictionQuotaEvent(EvictionQuota quota) {
this.quota = quota;
}
public EvictionQuota getQuota() {
return quota;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EvictionQuotaEvent that = (EvictionQuotaEvent) o;
return Objects.equals(quota, that.quota);
}
@Override
public int hashCode() {
return Objects.hash(quota);
}
@Override
public String toString() {
return "EvictionQuotaEvent{" +
"quota=" + quota +
"} " + super.toString();
}
}
| 9,717 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model/event/SystemDisruptionBudgetUpdateEvent.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.api.eviction.model.event;
import java.util.Objects;
import com.netflix.titus.api.eviction.model.SystemDisruptionBudget;
public class SystemDisruptionBudgetUpdateEvent extends EvictionEvent {
private final SystemDisruptionBudget systemDisruptionBudget;
public SystemDisruptionBudgetUpdateEvent(SystemDisruptionBudget systemDisruptionBudget) {
this.systemDisruptionBudget = systemDisruptionBudget;
}
public SystemDisruptionBudget getSystemDisruptionBudget() {
return systemDisruptionBudget;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SystemDisruptionBudgetUpdateEvent that = (SystemDisruptionBudgetUpdateEvent) o;
return Objects.equals(systemDisruptionBudget, that.systemDisruptionBudget);
}
@Override
public int hashCode() {
return Objects.hash(systemDisruptionBudget);
}
@Override
public String toString() {
return "SystemDisruptionBudgetUpdateEvent{" +
"systemDisruptionBudget=" + systemDisruptionBudget +
"} " + super.toString();
}
}
| 9,718 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model/event/EvictionEvent.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.api.eviction.model.event;
import com.netflix.titus.api.eviction.model.EvictionQuota;
public abstract class EvictionEvent {
public static EvictionSnapshotEndEvent newSnapshotEndEvent() {
return EvictionSnapshotEndEvent.getInstance();
}
public static EvictionQuotaEvent newQuotaEvent(EvictionQuota evictionQuota) {
return new EvictionQuotaEvent(evictionQuota);
}
public static TaskTerminationEvent newSuccessfulTaskTerminationEvent(String taskId, String reason) {
return new TaskTerminationEvent(taskId, reason);
}
public static TaskTerminationEvent newFailedTaskTerminationEvent(String taskId, String reason, Throwable error) {
return new TaskTerminationEvent(taskId, reason, error);
}
}
| 9,719 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model/event/EvictionKeepAliveEvent.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.api.eviction.model.event;
public class EvictionKeepAliveEvent extends EvictionEvent {
private static final EvictionKeepAliveEvent INSTANCE = new EvictionKeepAliveEvent();
public static EvictionKeepAliveEvent getInstance() {
return INSTANCE;
}
}
| 9,720 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model/event/TaskTerminationEvent.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.api.eviction.model.event;
import java.util.Objects;
import java.util.Optional;
public class TaskTerminationEvent extends EvictionEvent {
private final String taskId;
private final String reason;
private final boolean approved;
private final Optional<Throwable> error;
public TaskTerminationEvent(String taskId, String reason) {
this.taskId = taskId;
this.reason = reason;
this.approved = true;
this.error = Optional.empty();
}
public TaskTerminationEvent(String taskId, String reason, Throwable error) {
this.taskId = taskId;
this.reason = reason;
this.approved = false;
this.error = Optional.of(error);
}
public String getTaskId() {
return taskId;
}
public String getReason() {
return reason;
}
public boolean isApproved() {
return approved;
}
public Optional<Throwable> getError() {
return error;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TaskTerminationEvent that = (TaskTerminationEvent) o;
return approved == that.approved &&
Objects.equals(taskId, that.taskId) &&
Objects.equals(reason, that.reason) &&
Objects.equals(error, that.error);
}
@Override
public int hashCode() {
return Objects.hash(taskId, reason, approved, error);
}
@Override
public String toString() {
return "TaskTerminationEvent{" +
"taskId='" + taskId + '\'' +
", reason='" + reason + '\'' +
", approved=" + approved +
", error=" + error +
'}';
}
}
| 9,721 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/model/event/EvictionSnapshotEndEvent.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.api.eviction.model.event;
public class EvictionSnapshotEndEvent extends EvictionEvent {
private static final EvictionSnapshotEndEvent INSTANCE = new EvictionSnapshotEndEvent();
public static EvictionSnapshotEndEvent getInstance() {
return INSTANCE;
}
}
| 9,722 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/service/ReadOnlyEvictionOperations.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.api.eviction.service;
import java.util.Optional;
import com.netflix.titus.api.eviction.model.EvictionQuota;
import com.netflix.titus.api.eviction.model.event.EvictionEvent;
import com.netflix.titus.api.model.reference.Reference;
import reactor.core.publisher.Flux;
public interface ReadOnlyEvictionOperations {
/**
* For tiers and capacity groups we do not enforce quota yet, so we set it to a very high value.
*/
int VERY_HIGH_QUOTA = 1_000;
EvictionQuota getEvictionQuota(Reference reference);
Optional<EvictionQuota> findEvictionQuota(Reference reference);
Flux<EvictionEvent> events(boolean includeSnapshot);
}
| 9,723 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/service/EvictionOperations.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.api.eviction.service;
import reactor.core.publisher.Mono;
public interface EvictionOperations extends ReadOnlyEvictionOperations {
Mono<Void> terminateTask(String taskId, String reason, String callerId);
}
| 9,724 |
0 | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction | Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/eviction/service/EvictionException.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.api.eviction.service;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.api.model.reference.Reference;
import com.netflix.titus.common.util.StringExt;
public class EvictionException extends RuntimeException {
public enum ErrorCode {
BadConfiguration,
CapacityGroupNotFound,
TaskNotFound,
TaskNotScheduledYet,
TaskAlreadyStopped,
NoQuota,
Unknown,
}
private final ErrorCode errorCode;
private EvictionException(ErrorCode errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public ErrorCode getErrorCode() {
return errorCode;
}
public static EvictionException badConfiguration(String reason, Object... args) {
return new EvictionException(ErrorCode.BadConfiguration, String.format("Bad configuration data: %s", String.format(reason, args)));
}
public static EvictionException taskNotFound(String taskId) {
return new EvictionException(ErrorCode.TaskNotFound, "Task not found: " + taskId);
}
public static EvictionException capacityGroupNotFound(String capacityGroupName) {
return new EvictionException(ErrorCode.CapacityGroupNotFound, "Capacity group not found: " + capacityGroupName);
}
public static EvictionException taskAlreadyStopped(Task task) {
TaskState state = task.getStatus().getState();
return state == TaskState.Finished
? new EvictionException(ErrorCode.TaskAlreadyStopped, "Task already finished: " + task.getId())
: new EvictionException(ErrorCode.TaskAlreadyStopped, String.format("Task terminating: taskId=%s, state=%s", task.getId(), state));
}
public static EvictionException taskNotScheduledYet(Task task) {
return new EvictionException(ErrorCode.TaskNotScheduledYet, "Task not scheduled yet: " + task.getId());
}
public static EvictionException noQuotaFound(Reference reference) {
return new EvictionException(ErrorCode.NoQuota, String.format("Eviction quota not found for %s=%s", reference.getLevel(), reference.getName()));
}
public static EvictionException noAvailableJobQuota(Job<?> job, String quotaRestrictions) {
return new EvictionException(ErrorCode.NoQuota, String.format("No job quota: jobId=%s, restrictions=%s", job.getId(), quotaRestrictions));
}
public static EvictionException deconstruct(String restrictionCode, String restrictionMessage) {
ErrorCode errorCode;
try {
errorCode = StringExt.parseEnumIgnoreCase(restrictionCode, ErrorCode.class);
} catch (Exception e) {
return new EvictionException(ErrorCode.Unknown, StringExt.safeTrim(restrictionMessage));
}
return new EvictionException(errorCode, StringExt.safeTrim(restrictionMessage));
}
}
| 9,725 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/test/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/test/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/Fabric8IOUtilTest.java | /*
* Copyright 2022 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.kubernetes.fabric8io;
import java.time.OffsetDateTime;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class Fabric8IOUtilTest {
private static final String TIMESTAMP = "2022-01-20T23:19:52Z";
@Test
public void testDateParseAndFormat() {
OffsetDateTime parsed = Fabric8IOUtil.parseTimestamp(TIMESTAMP);
assertThat(parsed.toInstant().toEpochMilli()).isGreaterThan(0);
// Now format it back
String formatted = Fabric8IOUtil.formatTimestamp(parsed);
assertThat(formatted).isEqualTo(TIMESTAMP);
}
} | 9,726 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/test/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/test/java/com/netflix/titus/runtime/connector/kubernetes/std/StdKubeApiClientsTest.java | /*
* Copyright 2022 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.kubernetes.std;
import java.util.UUID;
import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiClients;
import okhttp3.Request;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StdKubeApiClientsTest {
@Test
public void testMapUri() {
String uuid = UUID.randomUUID().toString();
String instanceId = "i-07d1b67286b43458e";
String path = "/segment1_" + uuid + "/segment2_" + instanceId;
assertThat(StdKubeApiClients.mapUri(newRequest(path))).isEqualTo("/segment1_/segment2_");
}
private Request newRequest(String path) {
return new Request.Builder().url("http://myservice" + path).build();
}
} | 9,727 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/common | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/common/grpc/GrpcClientErrorUtils.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.common.grpc;
import java.util.Optional;
import com.google.protobuf.Any;
import com.google.protobuf.Descriptors;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.rpc.BadRequest;
import com.google.rpc.DebugInfo;
import com.google.rpc.Status;
import com.netflix.titus.common.util.ExceptionExt;
import io.grpc.Metadata;
import io.grpc.StatusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Titus GRPC error replies are based on Google RPC model: https://github.com/googleapis/googleapis/tree/master/google/rpc.
* Additional error context data is encoded in HTTP2 headers. A client is not required to understand and process the error
* context, but it will provide more insight into the cause of the error.
*/
public final class GrpcClientErrorUtils {
private static final Logger logger = LoggerFactory.getLogger(GrpcClientErrorUtils.class);
public static final String X_TITUS_ERROR = "X-Titus-Error";
public static final String X_TITUS_ERROR_BIN = "X-Titus-Error-bin";
public static final Metadata.Key<String> KEY_TITUS_ERROR_REPORT = Metadata.Key.of(X_TITUS_ERROR, Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<byte[]> KEY_TITUS_ERROR_REPORT_BIN = Metadata.Key.of(X_TITUS_ERROR_BIN, Metadata.BINARY_BYTE_MARSHALLER);
private GrpcClientErrorUtils() {
}
public static String toDetailedMessage(Throwable error) {
if (error == null) {
return "<empty throwable in method invocation>";
}
Throwable next = error;
while (!(next instanceof StatusRuntimeException) && next.getCause() != null) {
next = next.getCause();
}
// If this is not GRPC error, return full message chain.
if (!(next instanceof StatusRuntimeException)) {
return ExceptionExt.toMessageChain(error);
}
return next.getMessage();
}
public static Status getStatus(StatusRuntimeException error) {
if (error.getTrailers() == null) {
return Status.newBuilder().setCode(-1).setMessage(error.getMessage()).build();
}
try {
byte[] data = error.getTrailers().get(KEY_TITUS_ERROR_REPORT_BIN);
if (data == null) {
return Status.newBuilder().setCode(-1).setMessage(error.getMessage()).build();
}
return Status.parseFrom(data);
} catch (InvalidProtocolBufferException e) {
logger.error("Something went wrong with status parsing", e);
throw new IllegalArgumentException(e);
}
}
public static <D extends MessageOrBuilder> Optional<D> getDetail(StatusRuntimeException error, Class<D> detailType) {
Status status = getStatus(error);
for (Any any : status.getDetailsList()) {
Descriptors.Descriptor descriptor = any.getDescriptorForType();
Descriptors.FieldDescriptor typeUrlField = descriptor.findFieldByName("type_url");
String typeUrl = (String) any.getField(typeUrlField);
Class type;
if (typeUrl.contains(DebugInfo.class.getSimpleName())) {
type = DebugInfo.class;
} else if (typeUrl.contains(BadRequest.class.getSimpleName())) {
type = BadRequest.class;
} else {
return Optional.empty();
}
if (type == detailType) {
Message unpack;
try {
unpack = any.unpack(type);
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException("Cannot unpack error details", e);
}
return Optional.of((D) unpack);
}
}
return Optional.empty();
}
}
| 9,728 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/QueryUtils.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.endpoint.common;
import java.util.Map;
import java.util.Set;
public final class QueryUtils {
public static boolean matchesAttributes(Map<String, Set<String>> expectedLabels, Map<String, String> labels, boolean andOp) {
if (labels.isEmpty()) {
return false;
}
// and
if (andOp) {
for (Map.Entry<String, Set<String>> expected : expectedLabels.entrySet()) {
String expectedKey = expected.getKey();
if (!labels.containsKey(expectedKey)) {
return false;
}
Set<String> expectedValues = expected.getValue();
if (!expectedValues.isEmpty() && !expectedValues.contains(labels.get(expectedKey))) {
return false;
}
}
return true;
}
// or
for (Map.Entry<String, Set<String>> expected : expectedLabels.entrySet()) {
String expectedKey = expected.getKey();
if (labels.containsKey(expectedKey)) {
Set<String> expectedValues = expected.getValue();
if (expectedValues.isEmpty() || expectedValues.contains(labels.get(expectedKey))) {
return true;
}
}
}
return false;
}
}
| 9,729 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/ClientInvocationMetrics.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.endpoint.common;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import com.netflix.spectator.api.Timer;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.runtime.endpoint.resolver.HostCallerIdResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClientInvocationMetrics {
private static final Logger logger = LoggerFactory.getLogger(ClientInvocationMetrics.class);
private static final BasicTag SUCCESS_TAG = new BasicTag("status", "success");
private static final BasicTag FAILURE_TAG = new BasicTag("status", "failure");
private final String rootName;
private final HostCallerIdResolver hostCallerIdResolver;
private final Registry registry;
private final ConcurrentMap<ClientKey, ClientMetrics> counterMap = new ConcurrentHashMap<>();
public ClientInvocationMetrics(String rootName,
HostCallerIdResolver hostCallerIdResolver,
Registry registry) {
this.rootName = rootName;
this.hostCallerIdResolver = hostCallerIdResolver;
this.registry = registry;
}
public void registerSuccess(String callerHost, List<Tag> tags, long durationMs) {
register(callerHost, CollectionsExt.copyAndAdd(tags, SUCCESS_TAG), durationMs);
}
public void registerFailure(String callerHost, List<Tag> tags, long durationMs) {
register(callerHost, CollectionsExt.copyAndAdd(tags, FAILURE_TAG), durationMs);
}
private void register(String callerHost, List<Tag> tags, long durationMs) {
String application = hostCallerIdResolver.resolve(callerHost).orElseGet(() -> {
logger.info("Cannot identify source with host address {}", callerHost);
return "UNKNOWN";
});
ClientKey clientKey = new ClientKey(application, tags);
ClientMetrics clientMetrics = counterMap.computeIfAbsent(clientKey, ClientMetrics::new);
clientMetrics.registerInvocation(durationMs);
}
private static class ClientKey {
private final String application;
private final List<Tag> tags;
private ClientKey(String application, List<Tag> tags) {
this.application = application;
this.tags = tags;
}
private String getApplication() {
return application;
}
private List<Tag> getTags() {
return tags;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClientKey clientKey = (ClientKey) o;
if (application != null ? !application.equals(clientKey.application) : clientKey.application != null) {
return false;
}
return tags != null ? tags.equals(clientKey.tags) : clientKey.tags == null;
}
@Override
public int hashCode() {
int result = application != null ? application.hashCode() : 0;
result = 31 * result + (tags != null ? tags.hashCode() : 0);
return result;
}
}
private class ClientMetrics {
private final Counter counter;
private final Timer latency;
private ClientMetrics(ClientKey clientKey) {
List<Tag> tags = CollectionsExt.copyAndAdd(clientKey.getTags(), new BasicTag("application", clientKey.getApplication()));
this.counter = registry.counter(rootName + "requests", tags);
this.latency = registry.timer(rootName + "latency", tags);
}
private void registerInvocation(long durationMs) {
counter.increment();
latency.record(durationMs, TimeUnit.MILLISECONDS);
}
}
}
| 9,730 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/CommonRuntimeGrpcModelConverters.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.endpoint.common.grpc;
import java.util.stream.Collectors;
import com.netflix.titus.api.model.Page;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.api.model.callmetadata.Caller;
import com.netflix.titus.api.model.callmetadata.CallerType;
import com.netflix.titus.grpc.protogen.Pagination;
public class CommonRuntimeGrpcModelConverters {
public static Page toPage(com.netflix.titus.grpc.protogen.Page grpcPage) {
return new Page(grpcPage.getPageNumber(), grpcPage.getPageSize(), grpcPage.getCursor());
}
public static com.netflix.titus.grpc.protogen.Page toGrpcPage(Page runtimePage) {
return com.netflix.titus.grpc.protogen.Page.newBuilder()
.setPageNumber(runtimePage.getPageNumber())
.setPageSize(runtimePage.getPageSize())
.setCursor(runtimePage.getCursor())
.build();
}
public static com.netflix.titus.api.model.Pagination toPagination(Pagination grpcPagination) {
return new com.netflix.titus.api.model.Pagination(
toPage(grpcPagination.getCurrentPage()),
grpcPagination.getHasMore(),
grpcPagination.getTotalPages(),
grpcPagination.getTotalItems(),
grpcPagination.getCursor(),
grpcPagination.getCursorPosition()
);
}
public static Pagination toGrpcPagination(com.netflix.titus.api.model.Pagination runtimePagination) {
return Pagination.newBuilder()
.setCurrentPage(toGrpcPage(runtimePagination.getCurrentPage()))
.setTotalItems(runtimePagination.getTotalItems())
.setTotalPages(runtimePagination.getTotalPages())
.setHasMore(runtimePagination.hasMore())
.setCursor(runtimePagination.getCursor())
.setCursorPosition(runtimePagination.getCursorPosition())
.build();
}
public static Pagination emptyGrpcPagination(com.netflix.titus.grpc.protogen.Page page) {
return Pagination.newBuilder()
.setCurrentPage(page)
.setTotalItems(0)
.setTotalPages(0)
.setHasMore(false)
.setCursor("")
.setCursorPosition(0)
.build();
}
public static CallMetadata toCallMetadata(com.netflix.titus.grpc.protogen.CallMetadata grpcCallContext) {
return CallMetadata.newBuilder()
.withCallerId(grpcCallContext.getCallerId())
.withCallReason(grpcCallContext.getCallReason())
.withCallPath(grpcCallContext.getCallPathList())
.withCallers(grpcCallContext.getCallersList().stream().map(CommonRuntimeGrpcModelConverters::toCoreCaller).collect(Collectors.toList()))
.withDebug(grpcCallContext.getDebug())
.build();
}
public static CallerType toCoreCallerType(com.netflix.titus.grpc.protogen.CallMetadata.CallerType grpcCallerType) {
switch (grpcCallerType) {
case Application:
return CallerType.Application;
case User:
return CallerType.User;
case Unknown:
case UNRECOGNIZED:
default:
return CallerType.Unknown;
}
}
private static Caller toCoreCaller(com.netflix.titus.grpc.protogen.CallMetadata.Caller grpcCaller) {
return Caller.newBuilder()
.withId(grpcCaller.getId())
.withCallerType(toCoreCallerType(grpcCaller.getType()))
.withContext(grpcCaller.getContextMap())
.build();
}
public static com.netflix.titus.grpc.protogen.CallMetadata toGrpcCallMetadata(CallMetadata callMetadata) {
return com.netflix.titus.grpc.protogen.CallMetadata.newBuilder()
.setCallerId(callMetadata.getCallerId())
.addAllCallers(callMetadata.getCallers().stream().map(CommonRuntimeGrpcModelConverters::toGrpcCaller).collect(Collectors.toList()))
.setCallReason(callMetadata.getCallReason())
.addAllCallPath(callMetadata.getCallPath())
.setDebug(callMetadata.isDebug())
.build();
}
public static com.netflix.titus.grpc.protogen.CallMetadata.CallerType toGrpcCallerType(CallerType callerType) {
if (callerType == null) {
return com.netflix.titus.grpc.protogen.CallMetadata.CallerType.Unknown;
}
switch (callerType) {
case Application:
return com.netflix.titus.grpc.protogen.CallMetadata.CallerType.Application;
case User:
return com.netflix.titus.grpc.protogen.CallMetadata.CallerType.User;
case Unknown:
default:
return com.netflix.titus.grpc.protogen.CallMetadata.CallerType.Unknown;
}
}
public static com.netflix.titus.grpc.protogen.CallMetadata.Caller toGrpcCaller(Caller coreCaller) {
return com.netflix.titus.grpc.protogen.CallMetadata.Caller.newBuilder()
.setId(coreCaller.getId())
.setType(toGrpcCallerType(coreCaller.getCallerType()))
.putAllContext(coreCaller.getContext())
.build();
}
}
| 9,731 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint/resolver/HostCallerIdResolver.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.endpoint.resolver;
/**
* Resolves caller id from its host name or IP address.
*/
public interface HostCallerIdResolver extends CallerIdResolver<String> {
}
| 9,732 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint/resolver/CallerIdResolver.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.endpoint.resolver;
import java.util.Optional;
/**
* External client (caller) id resolver. The caller data type depends on actual transport protocol used.
* It is also possible that for a single request, multiple caller identities exist.
*/
public interface CallerIdResolver<CALLER_DATA> {
Optional<String> resolve(CALLER_DATA callerData);
}
| 9,733 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint/resolver/HttpCallerIdResolver.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.endpoint.resolver;
import javax.servlet.http.HttpServletRequest;
/**
* Extract from the HTTP request information about a caller.
*/
public interface HttpCallerIdResolver extends CallerIdResolver<HttpServletRequest> {
}
| 9,734 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint/resolver/NoOpHostCallerIdResolver.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.endpoint.resolver;
import java.util.Optional;
import javax.inject.Singleton;
/**
* {@link HostCallerIdResolver} implementation that returns always an empty response.
*/
@Singleton
public class NoOpHostCallerIdResolver implements HostCallerIdResolver {
private static final NoOpHostCallerIdResolver INSTANCE = new NoOpHostCallerIdResolver();
@Override
public Optional<String> resolve(String address) {
return Optional.of("Anonymous");
}
public static NoOpHostCallerIdResolver getInstance() {
return INSTANCE;
}
}
| 9,735 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint/resolver/ByRemoteAddressHttpCallerIdResolver.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.endpoint.resolver;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
/**
* Extract caller id from HTTP request.
*/
public class ByRemoteAddressHttpCallerIdResolver implements HttpCallerIdResolver {
private static final String TITUS_HEADER_CALLER_HOST_ADDRESS = "X-Titus-CallerHostAddress";
@Override
public Optional<String> resolve(HttpServletRequest httpServletRequest) {
String originalCallerId = httpServletRequest.getHeader(TITUS_HEADER_CALLER_HOST_ADDRESS);
if (originalCallerId != null) {
return Optional.of(originalCallerId);
}
return Optional.ofNullable(httpServletRequest.getRemoteHost());
}
}
| 9,736 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/endpoint/resolver/NoOpHttpCallerIdResolver.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.endpoint.resolver;
import java.util.Optional;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
/**
* {@link HttpCallerIdResolver} implementation that returns always an empty response.
*/
@Singleton
public class NoOpHttpCallerIdResolver implements HttpCallerIdResolver {
public static final NoOpHttpCallerIdResolver INSTANCE = new NoOpHttpCallerIdResolver();
@Override
public Optional<String> resolve(HttpServletRequest httpServletRequest) {
return Optional.empty();
}
}
| 9,737 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/KubeUtil.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.runtime.connector.kubernetes;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import io.kubernetes.client.openapi.ApiCallback;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import okhttp3.Call;
import reactor.core.publisher.Mono;
public final class KubeUtil {
/**
* Like {@link Function}, but with {@link ApiException} throws clause.
*/
public interface KubeFunction<I, O> {
O apply(I argument) throws ApiException;
}
/**
* Get Kube object name
*/
public static String getMetadataName(V1ObjectMeta metadata) {
if (metadata == null) {
return "";
}
return metadata.getName();
}
public static <T> Mono<T> toReact(KubeFunction<ApiCallback<T>, Call> handler) {
return Mono.create(sink -> {
Call call;
try {
call = handler.apply(new ApiCallback<T>() {
@Override
public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
sink.error(e);
}
@Override
public void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders) {
if (result == null) {
sink.success();
} else {
sink.success(result);
}
}
@Override
public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
}
@Override
public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
}
});
} catch (ApiException e) {
sink.error(e);
return;
}
sink.onCancel(call::cancel);
});
}
}
| 9,738 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/KubeConnectorConfiguration.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.connector.kubernetes;
import com.netflix.archaius.api.annotations.DefaultValue;
public interface KubeConnectorConfiguration {
/**
* @return how often to trigger a full reconciliation of nodes/pods
*/
@DefaultValue("300000" /* 5 min */)
long getKubeApiServerIntegratorRefreshIntervalMs();
}
| 9,739 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/KubeApiException.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.runtime.connector.kubernetes;
import io.kubernetes.client.openapi.ApiException;
public class KubeApiException extends RuntimeException {
private static final String NOT_FOUND = "Not Found";
public enum ErrorCode {
CONFLICT_ALREADY_EXISTS,
INTERNAL,
NOT_FOUND,
}
private final ErrorCode errorCode;
public KubeApiException(String message, Throwable cause) {
super(message, cause);
this.errorCode = cause instanceof ApiException ? toErrorCode((ApiException) cause) : ErrorCode.INTERNAL;
}
public KubeApiException(ApiException cause) {
this(String.format("%s: httpStatus=%s, body=%s", cause.getMessage(), cause.getCode(), cause.getResponseBody()), cause);
}
public ErrorCode getErrorCode() {
return errorCode;
}
private ErrorCode toErrorCode(ApiException e) {
if (e.getMessage() == null) {
return ErrorCode.INTERNAL;
}
if (e.getMessage().equalsIgnoreCase(NOT_FOUND)) {
return ErrorCode.NOT_FOUND;
}
if (e.getCode() == 409 && e.getMessage().equals("Conflict") && e.getResponseBody().contains("AlreadyExists")) {
return ErrorCode.CONFLICT_ALREADY_EXISTS;
}
return ErrorCode.INTERNAL;
}
}
| 9,740 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/DefaultFabric8IOConnector.java | /*
* Copyright 2022 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.kubernetes.fabric8io;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.Evaluators;
import com.netflix.titus.common.util.ExceptionExt;
import com.netflix.titus.common.util.ExecutorsExt;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.common.util.guice.annotation.Activator;
import com.netflix.titus.common.util.guice.annotation.Deactivator;
import com.netflix.titus.common.util.rx.ReactorExt;
import com.netflix.titus.runtime.connector.kubernetes.fabric8io.model.PodDeletedEvent;
import com.netflix.titus.runtime.connector.kubernetes.fabric8io.model.PodEvent;
import com.netflix.titus.runtime.connector.kubernetes.fabric8io.model.PodUpdatedEvent;
import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.informers.ResourceEventHandler;
import io.fabric8.kubernetes.client.informers.SharedIndexInformer;
import io.fabric8.kubernetes.client.informers.SharedInformerFactory;
import org.pcollections.HashTreePMap;
import org.pcollections.PMap;
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.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.util.retry.Retry;
import static com.netflix.titus.runtime.connector.kubernetes.fabric8io.model.F8KubeObjectFormatter.formatPodEssentials;
@Singleton
public class DefaultFabric8IOConnector implements Fabric8IOConnector {
private static final Logger logger = LoggerFactory.getLogger("KubeSharedInformerLogger");
private final NamespacedKubernetesClient kubernetesClient;
private final TitusRuntime titusRuntime;
private volatile PMap<String, Pod> pods = HashTreePMap.empty();
private volatile SharedInformerFactory sharedInformerFactory;
private volatile SharedIndexInformer<Pod> podInformer;
private volatile SharedIndexInformer<Node> nodeInformer;
private ExecutorService notificationHandlerExecutor;
private Scheduler scheduler;
private Disposable subscription;
private Fabric8IOInformerMetrics<Pod> podInformerMetrics;
private Fabric8IOInformerMetrics<Node> nodeInformerMetrics;
@Inject
public DefaultFabric8IOConnector(NamespacedKubernetesClient kubernetesClient, TitusRuntime titusRuntime) {
this.kubernetesClient = kubernetesClient;
this.titusRuntime = titusRuntime;
enterActiveMode();
}
private final Object activationLock = new Object();
private volatile boolean deactivated;
@PreDestroy
public void shutdown() {
Evaluators.acceptNotNull(subscription, Disposable::dispose);
if (sharedInformerFactory != null) {
Evaluators.acceptNotNull(podInformerMetrics, Fabric8IOInformerMetrics::close);
Evaluators.acceptNotNull(nodeInformerMetrics, Fabric8IOInformerMetrics::close);
sharedInformerFactory.stopAllRegisteredInformers();
}
}
@Activator
public void enterActiveMode() {
logger.info("Kube api connector entering active mode");
this.scheduler = initializeNotificationScheduler();
AtomicLong pendingCounter = new AtomicLong();
this.subscription = this.events().subscribeOn(scheduler)
.publishOn(scheduler)
.doOnError(error -> logger.warn("Kube integration event stream terminated with an error (retrying soon)", error))
.retryWhen(Retry.backoff(Long.MAX_VALUE, Duration.ofSeconds(1)))
.subscribe(
event -> {
Stopwatch stopwatch = Stopwatch.createStarted();
pendingCounter.getAndIncrement();
logger.info("New event [pending={}, lag={}]: {}", pendingCounter.get(), PodEvent.nextSequence() - event.getSequenceNumber(), event);
processEvent(event)
.doAfterTerminate(() -> {
pendingCounter.decrementAndGet();
long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
logger.info("Event processed [pending={}]: event={}, elapsed={}", pendingCounter.get(), event, elapsed);
})
.subscribe(
next -> {
// nothing
},
error -> {
logger.info("Kube api connector event state update error: event={}, error={}", event, error.getMessage());
logger.debug("Stack trace", error);
},
() -> {
// nothing
}
);
},
e -> logger.error("Event stream terminated"),
() -> logger.info("Event stream completed")
);
}
@Deactivator
public void deactivate() {
if (!deactivated) {
synchronized (activationLock) {
shutdown();
this.deactivated = true;
}
}
}
@Override
public Map<String, Pod> getPods() {
return pods;
}
@Override
public SharedIndexInformer<Pod> getPodInformer() {
activate();
return podInformer;
}
@Override
public SharedIndexInformer<Node> getNodeInformer() {
activate();
return nodeInformer;
}
@Override
public Flux<PodEvent> events() {
return kubeInformerEvents().transformDeferred(ReactorExt.badSubscriberHandler(logger));
}
private void activate() {
synchronized (activationLock) {
if (sharedInformerFactory != null) {
return;
}
try {
this.sharedInformerFactory = kubernetesClient.informers();
this.podInformer = createPodInformer(sharedInformerFactory);
this.nodeInformer = createNodeInformer(sharedInformerFactory);
this.podInformerMetrics = new Fabric8IOInformerMetrics<>("podInformer", podInformer, titusRuntime);
this.nodeInformerMetrics = new Fabric8IOInformerMetrics<>("nodeInformer", nodeInformer, titusRuntime);
sharedInformerFactory.startAllRegisteredInformers();
logger.info("Kube pod informer activated");
} catch (Exception e) {
logger.error("Could not intialize kubernetes shared informer", e);
if (sharedInformerFactory != null) {
ExceptionExt.silent(() -> sharedInformerFactory.stopAllRegisteredInformers());
}
sharedInformerFactory = null;
podInformer = null;
}
}
}
private Optional<Node> findNode(Pod pod) {
String nodeName = pod.getSpec().getNodeName();
if (StringExt.isEmpty(nodeName)) {
return Optional.empty();
}
return Optional.ofNullable(this.getNodeInformer().getIndexer().getByKey(nodeName));
}
private Flux<PodEvent> kubeInformerEvents() {
return Flux.create(sink -> {
ResourceEventHandler<Pod> handler = new ResourceEventHandler<Pod>() {
@Override
public void onAdd(Pod pod) {
Stopwatch stopwatch = Stopwatch.createStarted();
try {
String taskId = pod.getMetadata().getName();
Pod old = pods.get(taskId);
pods = pods.plus(taskId, pod);
PodEvent podEvent;
if (old != null) {
podEvent = PodEvent.onUpdate(old, pod, findNode(pod));
//metrics.onUpdate(pod);
} else {
podEvent = PodEvent.onAdd(pod);
//metrics.onAdd(pod);
}
sink.next(podEvent);
logger.info("Pod Added: pod={}, sequenceNumber={}", formatPodEssentials(pod), podEvent.getSequenceNumber());
logger.debug("complete pod data: {}", pod);
} finally {
logger.info("Pod informer onAdd: pod={}, elapsedMs={}", pod.getMetadata().getName(), stopwatch.elapsed().toMillis());
}
}
@Override
public void onUpdate(Pod oldPod, Pod newPod) {
Stopwatch stopwatch = Stopwatch.createStarted();
try {
String taskId = newPod.getMetadata().getName();
pods = pods.plus(taskId, newPod);
PodUpdatedEvent podEvent = PodEvent.onUpdate(oldPod, newPod, findNode(newPod));
sink.next(podEvent);
logger.info("Pod Updated: old={}, new={}, sequenceNumber={}", formatPodEssentials(oldPod), formatPodEssentials(newPod), podEvent.getSequenceNumber());
logger.debug("Complete pod data: old={}, new={}", oldPod, newPod);
} finally {
logger.info("Pod informer onUpdate: pod={}, elapsedMs={}", newPod.getMetadata().getName(), stopwatch.elapsed().toMillis());
}
}
@Override
public void onDelete(Pod pod, boolean deletedFinalStateUnknown) {
Stopwatch stopwatch = Stopwatch.createStarted();
try {
String taskId = pod.getMetadata().getName();
pods = pods.minus(taskId);
PodDeletedEvent podEvent = PodEvent.onDelete(pod, deletedFinalStateUnknown, findNode(pod));
sink.next(podEvent);
logger.info("Pod Deleted: {}, deletedFinalStateUnknown={}, sequenceNumber={}", formatPodEssentials(pod), deletedFinalStateUnknown, podEvent.getSequenceNumber());
logger.debug("complete pod data: {}", pod);
} finally {
logger.info("Pod informer onDelete: pod={}, elapsedMs={}", pod.getMetadata().getName(), stopwatch.elapsed().toMillis());
}
}
};
this.getPodInformer().addEventHandler(handler);
// A listener cannot be removed from shared informer.
// sink.onCancel(() -> ???);
});
}
private Mono<Void> processEvent(PodEvent event) {
// TODO drop if not needed
return Mono.empty();
}
@VisibleForTesting
protected Scheduler initializeNotificationScheduler() {
this.notificationHandlerExecutor = ExecutorsExt.namedSingleThreadExecutor(DefaultFabric8IOConnector.class.getSimpleName());
return Schedulers.fromExecutor(notificationHandlerExecutor);
}
private SharedIndexInformer<Pod> createPodInformer(SharedInformerFactory sharedInformerFactory) {
return sharedInformerFactory.sharedIndexInformerFor(
Pod.class,
3000);
}
private SharedIndexInformer<Node> createNodeInformer(SharedInformerFactory sharedInformerFactory) {
return sharedInformerFactory.sharedIndexInformerFor(
Node.class,
3000);
}
}
| 9,741 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/Fabric8IOConnectorComponent.java | /*
* Copyright 2022 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.kubernetes.fabric8io;
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.runtime.connector.kubernetes.KubeConnectorConfiguration;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class Fabric8IOConnectorComponent {
@Bean
public KubeConnectorConfiguration getKubeConnectorConfiguration(MyEnvironment environment) {
return Archaius2Ext.newConfiguration(KubeConnectorConfiguration.class, "titus.kubeClient", environment);
}
@Bean
public Fabric8IOConnector getFabric8IOConnector(NamespacedKubernetesClient kubernetesClient, TitusRuntime titusRuntime) {
return new DefaultFabric8IOConnector(kubernetesClient, titusRuntime);
}
}
| 9,742 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/Fabric8IOUtil.java | /*
* Copyright 2022 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.kubernetes.fabric8io;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public final class Fabric8IOUtil {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.of("Z"));
private Fabric8IOUtil() {
}
/**
* Kubernetes timestamps are returned as string values. For example "2022-01-20T15:31:20Z".
*/
public static OffsetDateTime parseTimestamp(String timestamp) {
return DATE_TIME_FORMATTER.parse(timestamp, ZonedDateTime::from).toOffsetDateTime();
}
public static String formatTimestamp(OffsetDateTime timestamp) {
return DATE_TIME_FORMATTER.format(timestamp.toInstant());
}
}
| 9,743 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/Fabric8IOConnector.java | /*
* Copyright 2022 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.kubernetes.fabric8io;
import java.util.Map;
import com.netflix.titus.runtime.connector.kubernetes.fabric8io.model.PodEvent;
import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.informers.SharedIndexInformer;
import reactor.core.publisher.Flux;
public interface Fabric8IOConnector {
Map<String, Pod> getPods();
SharedIndexInformer<Pod> getPodInformer();
SharedIndexInformer<Node> getNodeInformer();
Flux<PodEvent> events();
}
| 9,744 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/Fabric8IOClients.java | /*
* Copyright 2022 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.kubernetes.fabric8io;
import java.util.Optional;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
public final class Fabric8IOClients {
private Fabric8IOClients() {
}
/**
* TODO Add metrics
*/
public static NamespacedKubernetesClient createFabric8IOClient() {
return new DefaultKubernetesClient();
}
public static Optional<Throwable> checkKubeConnectivity(NamespacedKubernetesClient fabric8IOClient) {
try {
fabric8IOClient.apiServices().list();
} catch (Throwable e) {
return Optional.of(e);
}
return Optional.empty();
}
public static NamespacedKubernetesClient mustHaveKubeConnectivity(NamespacedKubernetesClient fabric8IOClient) {
checkKubeConnectivity(fabric8IOClient).ifPresent(error -> {
throw new IllegalStateException("Kube client connectivity error", error);
});
return fabric8IOClient;
}
}
| 9,745 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/Fabric8IOInformerMetrics.java | /*
* Copyright 2022 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.kubernetes.fabric8io;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.StringExt;
import io.fabric8.kubernetes.client.informers.SharedIndexInformer;
public class Fabric8IOInformerMetrics<T> {
private static final String ROOT = "titus.kubeClient.fabric8io.";
private final TitusRuntime titusRuntime;
private final Id syncedId;
private final Id watchingId;
private final Id resourceVersionId;
private final Id sizeId;
public Fabric8IOInformerMetrics(String name, SharedIndexInformer<T> informer, TitusRuntime titusRuntime) {
this.titusRuntime = titusRuntime;
this.syncedId = titusRuntime.getRegistry().createId(ROOT + "synced").withTag("informer", name);
this.watchingId = titusRuntime.getRegistry().createId(ROOT + "watching").withTag("informer", name);
this.resourceVersionId = titusRuntime.getRegistry().createId(ROOT + "resourceVersion").withTag("informer", name);
this.sizeId = titusRuntime.getRegistry().createId(ROOT + "size").withTag("informer", name);
PolledMeter.using(titusRuntime.getRegistry())
.withId(syncedId)
.monitorValue(informer, i -> i.hasSynced() ? 1 : 0);
PolledMeter.using(titusRuntime.getRegistry())
.withId(watchingId)
.monitorValue(informer, i -> i.isWatching() ? 1 : 0);
PolledMeter.using(titusRuntime.getRegistry())
.withId(resourceVersionId)
.monitorValue(informer, i -> toLong(informer.lastSyncResourceVersion()));
PolledMeter.using(titusRuntime.getRegistry())
.withId(sizeId)
.monitorValue(informer, i -> informer.getIndexer().list().size());
}
public void close() {
PolledMeter.remove(titusRuntime.getRegistry(), syncedId);
PolledMeter.remove(titusRuntime.getRegistry(), watchingId);
PolledMeter.remove(titusRuntime.getRegistry(), resourceVersionId);
PolledMeter.remove(titusRuntime.getRegistry(), sizeId);
}
private long toLong(String lastSyncResourceVersion) {
if (StringExt.isEmpty(lastSyncResourceVersion)) {
return 0;
}
try {
return Long.parseLong(lastSyncResourceVersion);
} catch (Exception e) {
return 0;
}
}
}
| 9,746 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/model/PodDeletedEvent.java | /*
* Copyright 2022 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.kubernetes.fabric8io.model;
import java.util.Objects;
import java.util.Optional;
import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.api.model.Pod;
public class PodDeletedEvent extends PodEvent{
private final boolean deletedFinalStateUnknown;
private final Optional<Node> node;
PodDeletedEvent(Pod pod, boolean deletedFinalStateUnknown, Optional<Node> node) {
super(pod);
this.deletedFinalStateUnknown = deletedFinalStateUnknown;
this.node = node;
}
public boolean isDeletedFinalStateUnknown() {
return deletedFinalStateUnknown;
}
public Optional<Node> getNode() {
return node;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
PodDeletedEvent that = (PodDeletedEvent) o;
return deletedFinalStateUnknown == that.deletedFinalStateUnknown &&
Objects.equals(node, that.node);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), deletedFinalStateUnknown, node);
}
@Override
public String toString() {
return "PodDeletedEvent{" +
"taskId='" + taskId + '\'' +
", sequenceNumber=" + sequenceNumber +
", pod=" + F8KubeObjectFormatter.formatPodEssentials(pod) +
", deletedFinalStateUnknown=" + deletedFinalStateUnknown +
", node=" + node.map(n -> n.getMetadata().getName()).orElse("<not_assigned>") +
'}';
}
}
| 9,747 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/model/F8KubeObjectFormatter.java | /*
* Copyright 2022 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.kubernetes.fabric8io.model;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodSpec;
import io.fabric8.kubernetes.api.model.PodStatus;
public class F8KubeObjectFormatter {
public static String formatPodEssentials(Pod pod) {
try {
return formatPodEssentialsInternal(pod);
} catch (Exception e) {
return "pod formatting error: " + e.getMessage();
}
}
private static String formatPodEssentialsInternal(Pod pod) {
StringBuilder builder = new StringBuilder("{");
appendMetadata(builder, pod.getMetadata());
PodSpec spec = pod.getSpec();
if (spec != null) {
builder.append(", nodeName=").append(spec.getNodeName());
}
PodStatus status = pod.getStatus();
if (status != null) {
builder.append(", phase=").append(status.getPhase());
builder.append(", reason=").append(status.getReason());
}
builder.append("}");
return builder.toString();
}
private static void appendMetadata(StringBuilder builder, ObjectMeta metadata) {
if (metadata != null) {
builder.append("name=").append(metadata.getName());
builder.append(", labels=").append(metadata.getLabels());
} else {
builder.append("name=").append("<no_metadata>");
}
}
}
| 9,748 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/model/PodUpdatedEvent.java | /*
* Copyright 2022 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.kubernetes.fabric8io.model;
import java.util.Objects;
import java.util.Optional;
import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.api.model.Pod;
public class PodUpdatedEvent extends PodEvent {
private final Pod oldPod;
private final Optional<Node> node;
PodUpdatedEvent(Pod oldPod, Pod newPod, Optional<Node> node) {
super(newPod);
this.oldPod = oldPod;
this.node = node;
}
public Pod getOldPod() {
return oldPod;
}
public Optional<Node> getNode() {
return node;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
PodUpdatedEvent that = (PodUpdatedEvent) o;
return Objects.equals(oldPod, that.oldPod) &&
Objects.equals(node, that.node);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), oldPod, node);
}
@Override
public String toString() {
return "PodUpdatedEvent{" +
"taskId='" + taskId + '\'' +
", sequenceNumber=" + sequenceNumber +
", pod=" + F8KubeObjectFormatter.formatPodEssentials(pod) +
", oldPod=" + F8KubeObjectFormatter.formatPodEssentials(oldPod) +
", node=" + node.map(n -> n.getMetadata().getName()).orElse("<not_assigned>") +
'}';
}
}
| 9,749 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/model/PodEvent.java | /*
* Copyright 2022 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.kubernetes.fabric8io.model;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.api.model.Pod;
public abstract class PodEvent {
private static final AtomicLong SEQUENCE_NUMBER = new AtomicLong();
protected final String taskId;
protected final Pod pod;
protected final long sequenceNumber;
protected PodEvent(Pod pod) {
this.taskId = pod.getMetadata().getName();
this.pod = pod;
this.sequenceNumber = SEQUENCE_NUMBER.getAndIncrement();
}
public String getTaskId() {
return taskId;
}
public Pod getPod() {
return pod;
}
public long getSequenceNumber() {
return sequenceNumber;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PodEvent podEvent = (PodEvent) o;
return sequenceNumber == podEvent.sequenceNumber && Objects.equals(taskId, podEvent.taskId) && Objects.equals(pod, podEvent.pod);
}
@Override
public int hashCode() {
return Objects.hash(taskId, pod, sequenceNumber);
}
@Override
public String toString() {
return "PodEvent{" +
"taskId='" + taskId + '\'' +
", sequenceNumber=" + sequenceNumber +
", pod=" + F8KubeObjectFormatter.formatPodEssentials(pod) +
'}';
}
public static long nextSequence() {
return SEQUENCE_NUMBER.get();
}
public static PodAddedEvent onAdd(Pod pod) {
return new PodAddedEvent(pod);
}
public static PodUpdatedEvent onUpdate(Pod oldPod, Pod newPod, Optional<Node> node) {
return new PodUpdatedEvent(oldPod, newPod, node);
}
public static PodDeletedEvent onDelete(Pod pod, boolean deletedFinalStateUnknown, Optional<Node> node) {
return new PodDeletedEvent(pod, deletedFinalStateUnknown, node);
}
/*public static PodNotFoundEvent onPodNotFound(Task task, TaskStatus finalTaskStatus) {
return new PodNotFoundEvent(task, finalTaskStatus);
}*/
}
| 9,750 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/fabric8io/model/PodAddedEvent.java | /*
* Copyright 2022 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.kubernetes.fabric8io.model;
import io.fabric8.kubernetes.api.model.Pod;
public class PodAddedEvent extends PodEvent {
PodAddedEvent(Pod pod) {
super(pod);
}
@Override
public String toString() {
return "PodAddedEvent{" +
"taskId=" + taskId +
", sequenceNumber=" + sequenceNumber +
", pod=" + F8KubeObjectFormatter.formatPodEssentials(pod) +
'}';
}
}
| 9,751 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/std/DefaultStdStdKubeApiFacade.java | /*
* Copyright 2022 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.kubernetes.std;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.Evaluators;
import com.netflix.titus.common.util.ExceptionExt;
import com.netflix.titus.common.util.guice.annotation.Deactivator;
import com.netflix.titus.runtime.connector.kubernetes.KubeApiException;
import com.netflix.titus.runtime.connector.kubernetes.KubeConnectorConfiguration;
import com.netflix.titus.runtime.connector.kubernetes.KubeUtil;
import io.kubernetes.client.common.KubernetesObject;
import io.kubernetes.client.informer.SharedIndexInformer;
import io.kubernetes.client.informer.SharedInformerFactory;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Node;
import io.kubernetes.client.openapi.models.V1NodeList;
import io.kubernetes.client.openapi.models.V1PersistentVolume;
import io.kubernetes.client.openapi.models.V1PersistentVolumeClaim;
import io.kubernetes.client.openapi.models.V1PersistentVolumeClaimList;
import io.kubernetes.client.openapi.models.V1PersistentVolumeList;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.CallGeneratorParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import static com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiClients.createSharedInformerFactory;
@Singleton
public class DefaultStdStdKubeApiFacade implements StdKubeApiFacade {
private static final Logger logger = LoggerFactory.getLogger(DefaultStdStdKubeApiFacade.class);
public static final String FAILED = "Failed";
public static final String BACKGROUND = "Background";
private static final String KUBERNETES_NAMESPACE = "default";
private final KubeConnectorConfiguration configuration;
private final ApiClient apiClient;
private final CoreV1Api coreV1Api;
private final TitusRuntime titusRuntime;
private final Object activationLock = new Object();
private volatile SharedInformerFactory sharedInformerFactory;
private volatile SharedIndexInformer<V1Node> nodeInformer;
private volatile SharedIndexInformer<V1Pod> podInformer;
private volatile SharedIndexInformer<V1PersistentVolume> persistentVolumeInformer;
private volatile SharedIndexInformer<V1PersistentVolumeClaim> persistentVolumeClaimInformer;
private StdKubeInformerMetrics<V1Node> nodeInformerMetrics;
private StdKubeInformerMetrics<V1Pod> podInformerMetrics;
private StdKubeInformerMetrics<V1PersistentVolume> persistentVolumeInformerMetrics;
private StdKubeInformerMetrics<V1PersistentVolumeClaim> persistentVolumeClaimInformerMetrics;
private volatile boolean deactivated;
@Inject
public DefaultStdStdKubeApiFacade(KubeConnectorConfiguration configuration, ApiClient apiClient, TitusRuntime titusRuntime) {
this.configuration = configuration;
this.apiClient = apiClient;
this.coreV1Api = new CoreV1Api(apiClient);
this.titusRuntime = titusRuntime;
}
@PreDestroy
public void shutdown() {
if (sharedInformerFactory != null) {
sharedInformerFactory.stopAllRegisteredInformers();
}
Evaluators.acceptNotNull(nodeInformerMetrics, StdKubeInformerMetrics::shutdown);
Evaluators.acceptNotNull(podInformerMetrics, StdKubeInformerMetrics::shutdown);
Evaluators.acceptNotNull(persistentVolumeInformerMetrics, StdKubeInformerMetrics::shutdown);
Evaluators.acceptNotNull(persistentVolumeClaimInformerMetrics, StdKubeInformerMetrics::shutdown);
}
@Deactivator
public void deactivate() {
if (!deactivated) {
synchronized (activationLock) {
shutdown();
this.deactivated = true;
}
}
}
@Override
public void deleteNode(String nodeName) throws KubeApiException {
try {
coreV1Api.deleteNode(
nodeName,
null,
null,
0,
null,
BACKGROUND,
null
);
} catch (ApiException e) {
throw new KubeApiException(e);
}
}
@Override
public void createNamespacedPod(String namespace, V1Pod pod) throws KubeApiException {
try {
coreV1Api.createNamespacedPod(namespace, pod, null, null, null);
} catch (ApiException e) {
throw new KubeApiException(e);
}
}
@Override
public Mono<V1Pod> createNamespacedPodAsync(String namespace, V1Pod pod) {
return KubeUtil.toReact(handler ->
coreV1Api.createNamespacedPodAsync(namespace, pod, null, null, null, handler)
);
}
@Override
public void deleteNamespacedPod(String namespace, String podName) throws KubeApiException {
try {
coreV1Api.deleteNamespacedPod(
podName,
namespace,
null,
null,
0,
null,
BACKGROUND,
null
);
} catch (ApiException e) {
throw new KubeApiException(e);
}
}
@Override
public void deleteNamespacedPod(String namespace, String podName, int deleteGracePeriod) throws KubeApiException {
try {
coreV1Api.deleteNamespacedPod(
podName,
namespace,
null,
null,
deleteGracePeriod,
null,
null,
null
);
} catch (ApiException e) {
throw new KubeApiException(e);
}
}
@Override
public void deleteNamespacedPersistentVolumeClaim(String namespace, String volumeClaimName) throws KubeApiException {
try {
coreV1Api.deleteNamespacedPersistentVolumeClaim(
volumeClaimName,
namespace,
null,
null,
0,
null,
null,
null
);
} catch (ApiException e) {
throw new KubeApiException(e);
}
}
@Override
public void replacePersistentVolume(V1PersistentVolume persistentVolume) throws KubeApiException {
try {
coreV1Api.replacePersistentVolume(
KubeUtil.getMetadataName(persistentVolume.getMetadata()),
persistentVolume,
null,
null,
null
);
} catch (ApiException e) {
throw new KubeApiException(e);
}
}
@Override
public void deletePersistentVolume(String volumeName) throws KubeApiException {
try {
coreV1Api.deletePersistentVolume(
volumeName,
null,
null,
0,
null,
null,
null
);
} catch (ApiException e) {
throw new KubeApiException(e);
}
}
@Override
public SharedIndexInformer<V1Node> getNodeInformer() {
activate();
return nodeInformer;
}
@Override
public SharedIndexInformer<V1Pod> getPodInformer() {
activate();
return podInformer;
}
@Override
public SharedIndexInformer<V1PersistentVolume> getPersistentVolumeInformer() {
activate();
return persistentVolumeInformer;
}
@Override
public SharedIndexInformer<V1PersistentVolumeClaim> getPersistentVolumeClaimInformer() {
activate();
return persistentVolumeClaimInformer;
}
@Override
public void createPersistentVolume(V1PersistentVolume v1PersistentVolume) throws KubeApiException {
try {
coreV1Api.createPersistentVolume(v1PersistentVolume, null, null, null);
} catch (ApiException e) {
throw new KubeApiException(e);
}
}
@Override
public void createNamespacedPersistentVolumeClaim(String namespace, V1PersistentVolumeClaim v1PersistentVolumeClaim) throws KubeApiException {
try {
coreV1Api.createNamespacedPersistentVolumeClaim(namespace, v1PersistentVolumeClaim, null, null, null);
} catch (ApiException e) {
throw new KubeApiException(e);
}
}
@Override
public long getPodInformerStaleness() {
// TODO synced is set to true on first successful execution. We need to change this logic, once we have better insight into the informer loop.
return podInformer != null && podInformer.hasSynced() ? 0 : -1;
}
@Override
public boolean isReadyForScheduling() {
return getPodInformerStaleness() == 0;
}
protected <T extends KubernetesObject> SharedIndexInformer<T> customizeInformer(String name, SharedIndexInformer<T> informer) {
return informer;
}
private void activate() {
synchronized (activationLock) {
if (deactivated) {
throw new IllegalStateException("Deactivated");
}
if (sharedInformerFactory != null) {
return;
}
try {
this.sharedInformerFactory = createSharedInformerFactory(
"kube-api-server-integrator-shared-informer-",
apiClient,
titusRuntime
);
this.nodeInformer = customizeInformer("nodeInformer", createNodeInformer(sharedInformerFactory));
this.podInformer = customizeInformer("podInformer", createPodInformer(sharedInformerFactory));
this.persistentVolumeInformer = customizeInformer("persistentVolumeInformer", createPersistentVolumeInformer(sharedInformerFactory));
this.persistentVolumeClaimInformer = customizeInformer("persistentVolumeClaimInformer", createPersistentVolumeClaimInformer(sharedInformerFactory));
this.nodeInformerMetrics = new StdKubeInformerMetrics<>("node", nodeInformer, titusRuntime);
this.podInformerMetrics = new StdKubeInformerMetrics<>("pod", podInformer, titusRuntime);
this.persistentVolumeInformerMetrics = new StdKubeInformerMetrics<>("persistentvolume", persistentVolumeInformer, titusRuntime);
this.persistentVolumeClaimInformerMetrics = new StdKubeInformerMetrics<>("persistentvolumeclaim", persistentVolumeClaimInformer, titusRuntime);
sharedInformerFactory.startAllRegisteredInformers();
logger.info("Kube node and pod informers activated");
} catch (Exception e) {
logger.error("Could not initialize Kube client shared informer", e);
if (sharedInformerFactory != null) {
ExceptionExt.silent(() -> sharedInformerFactory.stopAllRegisteredInformers());
}
sharedInformerFactory = null;
nodeInformer = null;
podInformer = null;
throw e;
}
}
}
private SharedIndexInformer<V1Node> createNodeInformer(SharedInformerFactory sharedInformerFactory) {
return sharedInformerFactory.sharedIndexInformerFor(
(CallGeneratorParams params) -> coreV1Api.listNodeCall(
null,
null,
null,
null,
null,
null,
params.resourceVersion,
null,
params.timeoutSeconds,
params.watch,
null
),
V1Node.class,
V1NodeList.class,
configuration.getKubeApiServerIntegratorRefreshIntervalMs()
);
}
private SharedIndexInformer<V1Pod> createPodInformer(SharedInformerFactory sharedInformerFactory) {
return sharedInformerFactory.sharedIndexInformerFor(
(CallGeneratorParams params) -> coreV1Api.listNamespacedPodCall(
KUBERNETES_NAMESPACE,
null,
null,
null,
null,
null,
null,
params.resourceVersion,
null,
params.timeoutSeconds,
params.watch,
null
),
V1Pod.class,
V1PodList.class,
configuration.getKubeApiServerIntegratorRefreshIntervalMs()
);
}
private SharedIndexInformer<V1PersistentVolume> createPersistentVolumeInformer(SharedInformerFactory sharedInformerFactory) {
return sharedInformerFactory.sharedIndexInformerFor(
(CallGeneratorParams params) -> coreV1Api.listPersistentVolumeCall(
null,
null,
null,
null,
null,
null,
params.resourceVersion,
null,
params.timeoutSeconds,
params.watch,
null
),
V1PersistentVolume.class,
V1PersistentVolumeList.class,
configuration.getKubeApiServerIntegratorRefreshIntervalMs()
);
}
private SharedIndexInformer<V1PersistentVolumeClaim> createPersistentVolumeClaimInformer(SharedInformerFactory sharedInformerFactory) {
return sharedInformerFactory.sharedIndexInformerFor(
(CallGeneratorParams params) -> coreV1Api.listNamespacedPersistentVolumeClaimCall(
KUBERNETES_NAMESPACE,
null,
null,
null,
null,
null,
null,
params.resourceVersion,
null,
params.timeoutSeconds,
params.watch,
null
),
V1PersistentVolumeClaim.class,
V1PersistentVolumeClaimList.class,
configuration.getKubeApiServerIntegratorRefreshIntervalMs()
);
}
}
| 9,752 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/std/StdKubeApiFacade.java | /*
* Copyright 2022 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.kubernetes.std;
import com.netflix.titus.runtime.connector.kubernetes.KubeApiException;
import io.kubernetes.client.informer.SharedIndexInformer;
import io.kubernetes.client.openapi.models.V1Node;
import io.kubernetes.client.openapi.models.V1PersistentVolume;
import io.kubernetes.client.openapi.models.V1PersistentVolumeClaim;
import io.kubernetes.client.openapi.models.V1Pod;
import reactor.core.publisher.Mono;
/**
* {@link StdKubeApiFacade} encapsulates Kube Java, except the entity model and the informer API. The latter is
* provided as a set of interfaces (unlike ApiClient or CoreV1Api), so it is easy to mock in the test code.
* @deprecated Use Fabric8IO instead.
*/
public interface StdKubeApiFacade {
// Nodes
void deleteNode(String nodeName) throws KubeApiException;
SharedIndexInformer<V1Node> getNodeInformer();
// Pods
void createNamespacedPod(String namespace, V1Pod pod) throws KubeApiException;
Mono<V1Pod> createNamespacedPodAsync(String namespace, V1Pod pod);
void deleteNamespacedPod(String namespace, String nodeName) throws KubeApiException;
void deleteNamespacedPod(String namespace, String podName, int deleteGracePeriod) throws KubeApiException;
SharedIndexInformer<V1Pod> getPodInformer();
// Persistent volumes
void createPersistentVolume(V1PersistentVolume v1PersistentVolume) throws KubeApiException;
void createNamespacedPersistentVolumeClaim(String namespace, V1PersistentVolumeClaim v1PersistentVolumeClaim) throws KubeApiException;
void deleteNamespacedPersistentVolumeClaim(String namespace, String volumeClaimName) throws KubeApiException;
void replacePersistentVolume(V1PersistentVolume persistentVolume) throws KubeApiException;
void deletePersistentVolume(String volumeName) throws KubeApiException;
SharedIndexInformer<V1PersistentVolume> getPersistentVolumeInformer();
SharedIndexInformer<V1PersistentVolumeClaim> getPersistentVolumeClaimInformer();
/**
* Provide information about how up to date the pod informer data is. If the pod informer is connected, and synced
* the staleness is 0.
*
* @return -1 if the pod informer was never synced or the data staleness time
*/
default long getPodInformerStaleness() {
return 0;
}
/**
* Returns true, if the Kubernetes integration subsystem is ready for scheduling.
*/
default boolean isReadyForScheduling() {
return true;
}
}
| 9,753 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/std/StdKubeInformerMetrics.java | /*
* Copyright 2022 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.kubernetes.std;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.titus.common.runtime.TitusRuntime;
import io.kubernetes.client.common.KubernetesObject;
import io.kubernetes.client.informer.SharedIndexInformer;
class StdKubeInformerMetrics<ApiType extends KubernetesObject> {
private static final String METRICS_ROOT = "titus.kubeClient.";
private static final String METRICS_INFORMER = METRICS_ROOT + "informer";
private static final String METRICS_INFORMER_SYNCED = METRICS_ROOT + "informerSynced";
private static final String METRICS_INFORMER_STALENESS = METRICS_ROOT + "informerStaleness";
private final Id sizeGaugeId;
private final Id syncedGaugeId;
private final Id stalenessGaugeId;
private final TitusRuntime titusRuntime;
public StdKubeInformerMetrics(String type,
SharedIndexInformer<ApiType> informer,
TitusRuntime titusRuntime) {
this.titusRuntime = titusRuntime;
this.sizeGaugeId = titusRuntime.getRegistry().createId(METRICS_INFORMER, "type", type);
this.syncedGaugeId = titusRuntime.getRegistry().createId(METRICS_INFORMER_SYNCED, "type", type);
this.stalenessGaugeId = titusRuntime.getRegistry().createId(METRICS_INFORMER_STALENESS, "type", type);
PolledMeter.using(titusRuntime.getRegistry())
.withId(sizeGaugeId)
.monitorValue(informer, i -> i.getIndexer().list().size());
PolledMeter.using(titusRuntime.getRegistry())
.withId(syncedGaugeId)
.monitorValue(informer, i -> i.hasSynced() ? 1 : 0);
PolledMeter.using(titusRuntime.getRegistry())
.withId(stalenessGaugeId)
.monitorValue(informer, i -> informer.hasSynced() ? 0 : -1);
}
void shutdown() {
PolledMeter.remove(titusRuntime.getRegistry(), sizeGaugeId);
PolledMeter.remove(titusRuntime.getRegistry(), syncedGaugeId);
PolledMeter.remove(titusRuntime.getRegistry(), stalenessGaugeId);
}
}
| 9,754 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/std/StdKubeConnectorComponent.java | /*
* Copyright 2022 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.kubernetes.std;
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.runtime.connector.kubernetes.KubeConnectorConfiguration;
import io.kubernetes.client.openapi.ApiClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class StdKubeConnectorComponent {
@Bean
public KubeConnectorConfiguration getKubeConnectorConfiguration(MyEnvironment environment) {
return Archaius2Ext.newConfiguration(KubeConnectorConfiguration.class, "titus.kubeClient", environment);
}
@Bean
public StdKubeApiFacade getKubeApiFacade(KubeConnectorConfiguration configuration, ApiClient apiClient, TitusRuntime titusRuntime) {
return new DefaultStdStdKubeApiFacade(configuration, apiClient, titusRuntime);
}
}
| 9,755 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/std/StdKubeApiClients.java | /*
* Copyright 2022 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.kubernetes.std;
import java.io.IOException;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.regex.Pattern;
import com.google.common.base.Strings;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.ExecutorsExt;
import com.netflix.titus.runtime.connector.kubernetes.okhttp.DisableCompressionInterceptor;
import com.netflix.titus.runtime.connector.kubernetes.okhttp.OkHttpMetricsInterceptor;
import io.kubernetes.client.informer.SharedInformerFactory;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.util.Config;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
/**
* @deprecated Use Fabric8IO instead.
*/
public class StdKubeApiClients {
public static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
/**
* An AWS instance id, consists of 'i-' prefix and 17 alpha-numeric characters following it, for example: i-07d1b67286b43458e.
*/
public static final Pattern INSTANCE_ID_PATTERN = Pattern.compile("i-(\\p{Alnum}){17}+");
public static ApiClient createApiClient(String metricsNamePrefix,
TitusRuntime titusRuntime,
long readTimeoutMs) {
return createApiClient(null, null, metricsNamePrefix, titusRuntime, StdKubeApiClients::mapUri, readTimeoutMs, true);
}
public static ApiClient createApiClient(String kubeApiServerUrl,
String kubeConfigPath,
String metricsNamePrefix,
TitusRuntime titusRuntime,
long readTimeoutMs,
boolean enableCompressionForKubeApiClient) {
return createApiClient(kubeApiServerUrl, kubeConfigPath, metricsNamePrefix, titusRuntime, StdKubeApiClients::mapUri, readTimeoutMs, enableCompressionForKubeApiClient);
}
public static ApiClient createApiClient(String kubeApiServerUrl,
String kubeConfigPath,
String metricsNamePrefix,
TitusRuntime titusRuntime,
Function<Request, String> uriMapper,
long readTimeoutMs,
boolean enableCompressionForKubeApiClient) {
OkHttpMetricsInterceptor metricsInterceptor = new OkHttpMetricsInterceptor(metricsNamePrefix, titusRuntime.getRegistry(),
titusRuntime.getClock(), uriMapper);
ApiClient client;
if (Strings.isNullOrEmpty(kubeApiServerUrl)) {
try {
if (Strings.isNullOrEmpty(kubeConfigPath)) {
client = Config.defaultClient();
} else {
client = Config.fromConfig(kubeConfigPath);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
client = Config.fromUrl(kubeApiServerUrl);
}
OkHttpClient.Builder newBuilder = client.getHttpClient().newBuilder();
// See: https://github.com/kubernetes-client/java/pull/960
newBuilder.protocols(Collections.singletonList(Protocol.HTTP_1_1))
.addInterceptor(metricsInterceptor)
.readTimeout(readTimeoutMs, TimeUnit.SECONDS);
// By default compression is enabled in OkHttpClient
if(!enableCompressionForKubeApiClient) {
newBuilder.addInterceptor(new DisableCompressionInterceptor());
}
client.setHttpClient(newBuilder.build());
return client;
}
public static Optional<Throwable> checkKubeConnectivity(ApiClient apiClient) {
CoreV1Api coreV1Api = new CoreV1Api(apiClient);
try {
coreV1Api.getAPIResources();
} catch (Throwable e) {
return Optional.of(e);
}
return Optional.empty();
}
public static ApiClient mustHaveKubeConnectivity(ApiClient apiClient) {
checkKubeConnectivity(apiClient).ifPresent(error -> {
throw new IllegalStateException("Kube client connectivity error", error);
});
return apiClient;
}
public static SharedInformerFactory createSharedInformerFactory(String threadNamePrefix, ApiClient apiClient, TitusRuntime titusRuntime) {
ExecutorService threadPool = ExecutorsExt.instrumentedCachedThreadPool(titusRuntime.getRegistry(), threadNamePrefix);
return new SharedInformerFactory(apiClient, threadPool);
}
static String mapUri(Request r) {
String path = '/' + String.join("/", r.url().pathSegments());
return removeAll(INSTANCE_ID_PATTERN, removeAll(UUID_PATTERN, path));
}
static String removeAll(Pattern pattern, String text) {
return pattern.matcher(text).replaceAll("");
}
}
| 9,756 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/okhttp/DisableCompressionInterceptor.java | /*
* Copyright 2022 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.kubernetes.okhttp;
import java.io.IOException;
import javax.ws.rs.core.HttpHeaders;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* Disables compression by adding the Http header.
*/
public class DisableCompressionInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request()
.newBuilder()
.addHeader(HttpHeaders.ACCEPT_ENCODING, "identity")
.build();
return chain.proceed(newRequest);
}
}
| 9,757 |
0 | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes | Create_ds/titus-control-plane/titus-common-runtime/src/main/java/com/netflix/titus/runtime/connector/kubernetes/okhttp/OkHttpMetricsInterceptor.java | /*
* Copyright 2022 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.kubernetes.okhttp;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.common.network.client.ClientMetrics;
import com.netflix.titus.common.util.time.Clock;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpMetricsInterceptor implements Interceptor {
private final String metricNamePrefix;
private final Registry registry;
private final Clock clock;
private final Function<Request, String> uriMapper;
private final ConcurrentMap<String, ClientMetrics> clientMetrics = new ConcurrentHashMap<>();
public OkHttpMetricsInterceptor(String metricNamePrefix, Registry registry, Clock clock, Function<Request, String> uriMapper) {
this.metricNamePrefix = metricNamePrefix;
this.registry = registry;
this.clock = clock;
this.uriMapper = uriMapper;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String method = request.method();
String uri = getUri(request);
ClientMetrics clientMetrics = this.clientMetrics.computeIfAbsent(uri, k -> new ClientMetrics(this.metricNamePrefix, uri, registry));
long startTimeMs = clock.wallTime();
try {
Response response = chain.proceed(request);
clientMetrics.incrementOnSuccess(method, uri, String.valueOf(response.code()));
clientMetrics.registerOnSuccessLatency(method, uri, Duration.ofMillis(clock.wallTime() - startTimeMs));
return response;
} catch (Exception e) {
clientMetrics.incrementOnError(method, uri, e);
clientMetrics.registerOnErrorLatency(method, uri, Duration.ofMillis(clock.wallTime() - startTimeMs));
throw e;
}
}
private String getUri(Request request) {
try {
return uriMapper.apply(request);
} catch (Exception ignore) {
}
return "unknown";
}
}
| 9,758 |
0 | Create_ds/titus-control-plane/titus-common-api/src/test/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/test/java/com/netflix/titus/api/model/PaginationEvaluatorTest.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.api.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import static com.netflix.titus.api.model.PaginableItems.PAGINATION_EVALUATOR;
import static org.assertj.core.api.Assertions.assertThat;
public class PaginationEvaluatorTest {
private static final Page FIRST_PAGE = Page.newBuilder().withPageSize(10).build();
@Test
public void testEmpty() {
PageResult<PaginableItem> pageResult = PAGINATION_EVALUATOR.takePage(FIRST_PAGE, Collections.emptyList());
assertThat(pageResult.getItems()).isEmpty();
assertThat(pageResult.getPagination().hasMore()).isFalse();
}
@Test
public void testEmptyWithCursor() {
Page page = FIRST_PAGE.toBuilder()
.withCursor(PAGINATION_EVALUATOR.encode(new PaginableItem("id", 1_000)))
.build();
PageResult<PaginableItem> pageResult = PAGINATION_EVALUATOR.takePage(page, Collections.emptyList());
assertThat(pageResult.getItems()).isEmpty();
assertThat(pageResult.getPagination().hasMore()).isFalse();
}
@Test
public void testPagination() {
paginateThroughAllRemainingPages(FIRST_PAGE, PaginableItems.items(100));
}
@Test
public void testPaginationWithPageSizeZero() {
PageResult<PaginableItem> pageResult = PAGINATION_EVALUATOR.takePage(Page.empty(), PaginableItems.items(2));
assertThat(pageResult.getPagination().getTotalItems()).isEqualTo(2);
assertThat(pageResult.getItems()).isEmpty();
}
@Test
public void testPaginationWithCursor() {
List<PaginableItem> items = PaginableItems.items(100);
PaginableItem removed = items.remove(50);
Page page = FIRST_PAGE.toBuilder().withCursor(PAGINATION_EVALUATOR.encode(removed)).build();
paginateThroughAllRemainingPages(page, items.subList(50, items.size()));
}
@Test(expected = PaginationException.class)
public void testPaginationWithBadPageSize() {
PAGINATION_EVALUATOR.takePage(FIRST_PAGE.toBuilder().withPageSize(-1).build(), PaginableItems.items(2));
}
@Test(expected = PaginationException.class)
public void testPaginationWithBadCursor() {
PAGINATION_EVALUATOR.takePage(FIRST_PAGE.toBuilder().withCursor("badCursor").build(), PaginableItems.items(2));
}
private List<PaginableItem> paginateThroughAllRemainingPages(Page page, List<PaginableItem> items) {
List<PaginableItem> fetched = new ArrayList<>();
boolean hasMore = true;
while (hasMore) {
PageResult<PaginableItem> pageResult = PAGINATION_EVALUATOR.takePage(page, items);
fetched.addAll(pageResult.getItems());
page = page.toBuilder().withCursor(pageResult.getPagination().getCursor()).build();
hasMore = pageResult.getPagination().hasMore();
}
verifyPaginationResult(items, fetched);
return fetched;
}
private void verifyPaginationResult(List<PaginableItem> items, List<PaginableItem> fetched) {
assertThat(fetched.size()).isEqualTo(items.size());
assertThat(PaginableItems.idsOf(fetched)).isEqualTo(PaginableItems.idsOf(items));
long minTimestamp = items.stream().mapToLong(PaginableItem::getTimestamp).min().orElse(0);
assertThat(items.get(0).getTimestamp()).isEqualTo(minTimestamp);
for (int i = 1; i < fetched.size(); i++) {
assertThat(items.get(i).getTimestamp()).isEqualTo(items.get(i - 1).getTimestamp() + PaginableItems.TIME_STEP_MS);
}
}
} | 9,759 |
0 | Create_ds/titus-control-plane/titus-common-api/src/test/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/test/java/com/netflix/titus/api/model/PaginableItems.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.api.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
class PaginableItems {
static final long TIME_STEP_MS = 100;
static final PaginationEvaluator<PaginableItem> PAGINATION_EVALUATOR = PaginationEvaluator.<PaginableItem>newBuilder()
.withIdExtractor(PaginableItem::getId)
.withTimestampExtractor(PaginableItem::getTimestamp)
.build();
static List<PaginableItem> items(int count) {
List<PaginableItem> result = new ArrayList<>(count);
long timestamp = 0;
for (int i = 0; i < count; i++) {
result.add(new PaginableItem(UUID.randomUUID().toString(), timestamp));
timestamp += TIME_STEP_MS;
}
return result;
}
static Set<String> idsOf(List<PaginableItem> items) {
return items.stream().map(PaginableItem::getId).collect(Collectors.toSet());
}
}
| 9,760 |
0 | Create_ds/titus-control-plane/titus-common-api/src/test/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/test/java/com/netflix/titus/api/model/PaginableItem.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.api.model;
import java.util.Objects;
class PaginableItem {
private final String id;
private final long timestamp;
public PaginableItem(String id, long timestamp) {
this.id = id;
this.timestamp = timestamp;
}
public String getId() {
return id;
}
public long getTimestamp() {
return timestamp;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PaginableItem that = (PaginableItem) o;
return timestamp == that.timestamp &&
Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id, timestamp);
}
@Override
public String toString() {
return "PaginableItem{" +
"id='" + id + '\'' +
", timestamp=" + timestamp +
'}';
}
}
| 9,761 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model/ClusterMemberAddress.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.api.clustermembership.model;
import java.util.Objects;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.Evaluators;
public class ClusterMemberAddress {
private final String ipAddress;
private final int portNumber;
private final String protocol;
private final boolean secure;
private final String description;
public ClusterMemberAddress(String ipAddress, int portNumber, String protocol, boolean secure, String description) {
this.ipAddress = ipAddress;
this.portNumber = portNumber;
this.protocol = protocol;
this.secure = secure;
this.description = Evaluators.getOrDefault(description, "");
}
public String getIpAddress() {
return ipAddress;
}
public int getPortNumber() {
return portNumber;
}
public String getProtocol() {
return protocol;
}
public boolean isSecure() {
return secure;
}
public String getDescription() {
return description;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClusterMemberAddress that = (ClusterMemberAddress) o;
return portNumber == that.portNumber &&
secure == that.secure &&
Objects.equals(ipAddress, that.ipAddress) &&
Objects.equals(protocol, that.protocol) &&
Objects.equals(description, that.description);
}
@Override
public int hashCode() {
return Objects.hash(ipAddress, portNumber, protocol, secure, description);
}
@Override
public String toString() {
return "ClusterMemberAddress{" +
"ipAddress='" + ipAddress + '\'' +
", portNumber=" + portNumber +
", protocol='" + protocol + '\'' +
", secure=" + secure +
", description='" + description + '\'' +
'}';
}
public Builder toBuilder() {
return newBuilder().withIpAddress(ipAddress).withPortNumber(portNumber).withProtocol(protocol).withSecure(secure).withDescription(description);
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private String ipAddress;
private int portNumber;
private String protocol;
private boolean secure;
private String description;
private Builder() {
}
public Builder withIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
return this;
}
public Builder withPortNumber(int portNumber) {
this.portNumber = portNumber;
return this;
}
public Builder withProtocol(String protocol) {
this.protocol = protocol;
return this;
}
public Builder withSecure(boolean secure) {
this.secure = secure;
return this;
}
public Builder withDescription(String description) {
this.description = description;
return this;
}
public ClusterMemberAddress build() {
Preconditions.checkNotNull(ipAddress, "IP address not set");
Preconditions.checkNotNull(protocol, "Protocol not set");
return new ClusterMemberAddress(ipAddress, portNumber, protocol, secure, description);
}
}
}
| 9,762 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model/ClusterMemberLeadership.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.api.clustermembership.model;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.Evaluators;
public class ClusterMemberLeadership {
private final String memberId;
private final ClusterMemberLeadershipState leadershipState;
private final Map<String, String> labels;
public ClusterMemberLeadership(String memberId,
ClusterMemberLeadershipState leadershipState,
Map<String, String> labels) {
this.memberId = memberId;
this.leadershipState = Evaluators.getOrDefault(leadershipState, ClusterMemberLeadershipState.Unknown);
this.labels = Evaluators.getOrDefault(labels, Collections.emptyMap());
}
public String getMemberId() {
return memberId;
}
public ClusterMemberLeadershipState getLeadershipState() {
return leadershipState;
}
public Map<String, String> getLabels() {
return labels;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClusterMemberLeadership that = (ClusterMemberLeadership) o;
return Objects.equals(memberId, that.memberId) &&
leadershipState == that.leadershipState &&
Objects.equals(labels, that.labels);
}
@Override
public int hashCode() {
return Objects.hash(memberId, leadershipState, labels);
}
@Override
public String toString() {
return "ClusterMemberLeadership{" +
"memberId='" + memberId + '\'' +
", leadershipState=" + leadershipState +
", labels=" + labels +
'}';
}
public Builder toBuilder() {
return newBuilder().withMemberId(memberId).withLeadershipState(leadershipState).withLabels(labels);
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private String memberId;
private ClusterMemberLeadershipState leadershipState;
private Map<String, String> labels;
private Builder() {
}
public Builder withMemberId(String memberId) {
this.memberId = memberId;
return this;
}
public Builder withLeadershipState(ClusterMemberLeadershipState leadershipState) {
this.leadershipState = leadershipState;
return this;
}
public Builder withLabels(Map<String, String> labels) {
this.labels = labels;
return this;
}
public ClusterMemberLeadership build() {
Preconditions.checkNotNull(memberId, "Member id not set");
return new ClusterMemberLeadership(memberId, leadershipState, labels);
}
}
}
| 9,763 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model/ClusterMembershipSnapshot.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.api.clustermembership.model;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import com.netflix.titus.common.util.CollectionsExt;
public class ClusterMembershipSnapshot {
private static final ClusterMembershipSnapshot EMPTY = new ClusterMembershipSnapshot(Collections.emptyMap(), Optional.empty(), -1);
private final Map<String, ClusterMembershipRevision<ClusterMember>> memberRevisions;
private final Optional<ClusterMembershipRevision<ClusterMemberLeadership>> leaderRevision;
private final long stalenessMs;
public ClusterMembershipSnapshot(Map<String, ClusterMembershipRevision<ClusterMember>> memberRevisions,
Optional<ClusterMembershipRevision<ClusterMemberLeadership>> leaderRevision,
long stalenessMs) {
this.memberRevisions = CollectionsExt.nonNull(memberRevisions);
this.leaderRevision = leaderRevision == null ? Optional.empty() : leaderRevision;
this.stalenessMs = stalenessMs;
}
public Map<String, ClusterMembershipRevision<ClusterMember>> getMemberRevisions() {
return memberRevisions;
}
public Optional<ClusterMembershipRevision<ClusterMemberLeadership>> getLeaderRevision() {
return leaderRevision;
}
public long getStalenessMs() {
return stalenessMs;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClusterMembershipSnapshot snapshot = (ClusterMembershipSnapshot) o;
return stalenessMs == snapshot.stalenessMs &&
Objects.equals(memberRevisions, snapshot.memberRevisions) &&
Objects.equals(leaderRevision, snapshot.leaderRevision);
}
@Override
public int hashCode() {
return Objects.hash(memberRevisions, leaderRevision, stalenessMs);
}
@Override
public String toString() {
return "ClusterMembershipSnapshot{" +
"memberRevisions=" + memberRevisions +
", leaderRevision=" + leaderRevision +
", stalenessMs=" + stalenessMs +
'}';
}
public Builder toBuilder() {
return newBuilder().withMemberRevisions(memberRevisions).withLeaderRevision(leaderRevision.orElse(null)).withStalenessMs(stalenessMs);
}
public static ClusterMembershipSnapshot empty() {
return EMPTY;
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private Map<String, ClusterMembershipRevision<ClusterMember>> memberRevisions = new HashMap<>();
private ClusterMembershipRevision<ClusterMemberLeadership> leaderRevision;
private long stalenessMs;
private Builder() {
}
@SafeVarargs
public final Builder withMemberRevisions(ClusterMembershipRevision<ClusterMember>... revisions) {
for (ClusterMembershipRevision<ClusterMember> revision : revisions) {
memberRevisions.put(revision.getCurrent().getMemberId(), revision);
}
return this;
}
public final Builder withMemberRevisions(Collection<ClusterMembershipRevision<ClusterMember>> revisions) {
for (ClusterMembershipRevision<ClusterMember> revision : revisions) {
memberRevisions.put(revision.getCurrent().getMemberId(), revision);
}
return this;
}
public Builder withMemberRevisions(Map<String, ClusterMembershipRevision<ClusterMember>> memberRevisions) {
this.memberRevisions.clear();
this.memberRevisions.putAll(memberRevisions);
return this;
}
@SafeVarargs
public final Builder withoutMemberRevisions(ClusterMembershipRevision<ClusterMember>... revisions) {
for (ClusterMembershipRevision<ClusterMember> revision : revisions) {
memberRevisions.remove(revision.getCurrent().getMemberId());
}
return this;
}
public Builder withLeaderRevision(ClusterMembershipRevision<ClusterMemberLeadership> leaderRevision) {
this.leaderRevision = leaderRevision;
return this;
}
public Builder withStalenessMs(long stalenessMs) {
this.stalenessMs = stalenessMs;
return this;
}
public ClusterMembershipSnapshot build() {
return new ClusterMembershipSnapshot(memberRevisions, Optional.ofNullable(leaderRevision), stalenessMs);
}
}
}
| 9,764 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model/ClusterMember.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.api.clustermembership.model;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.Evaluators;
public class ClusterMember {
private final String memberId;
private final boolean enabled;
private final boolean registered;
private final boolean active;
private final List<ClusterMemberAddress> clusterMemberAddresses;
private final Map<String, String> labels;
public ClusterMember(String memberId,
boolean enabled,
boolean registered,
boolean active,
List<ClusterMemberAddress> clusterMemberAddresses,
Map<String, String> labels) {
this.memberId = memberId;
this.enabled = enabled;
this.registered = registered;
this.active = active;
this.clusterMemberAddresses = Evaluators.getOrDefault(clusterMemberAddresses, Collections.emptyList());
this.labels = Evaluators.getOrDefault(labels, Collections.emptyMap());
}
public String getMemberId() {
return memberId;
}
public boolean isEnabled() {
return enabled;
}
public boolean isRegistered() {
return registered;
}
public boolean isActive() {
return active;
}
public List<ClusterMemberAddress> getClusterMemberAddresses() {
return clusterMemberAddresses;
}
public Map<String, String> getLabels() {
return labels;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClusterMember that = (ClusterMember) o;
return enabled == that.enabled &&
registered == that.registered &&
active == that.active &&
Objects.equals(memberId, that.memberId) &&
Objects.equals(clusterMemberAddresses, that.clusterMemberAddresses) &&
Objects.equals(labels, that.labels);
}
@Override
public int hashCode() {
return Objects.hash(memberId, enabled, registered, active, clusterMemberAddresses, labels);
}
@Override
public String toString() {
return "ClusterMember{" +
"memberId='" + memberId + '\'' +
", enabled=" + enabled +
", registered=" + registered +
", active=" + active +
", clusterMemberAddresses=" + clusterMemberAddresses +
", labels=" + labels +
'}';
}
public Builder toBuilder() {
return newBuilder()
.withMemberId(memberId)
.withEnabled(enabled)
.withRegistered(registered)
.withActive(active)
.withClusterMemberAddresses(clusterMemberAddresses)
.withLabels(labels);
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private String memberId;
private boolean enabled;
private boolean registered;
private boolean active;
private List<ClusterMemberAddress> clusterMemberAddress;
private Map<String, String> labels;
private Builder() {
}
public Builder withMemberId(String memberId) {
this.memberId = memberId;
return this;
}
public Builder withEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
public Builder withRegistered(boolean registered) {
this.registered = registered;
return this;
}
public Builder withActive(boolean active) {
this.active = active;
return this;
}
public Builder withClusterMemberAddresses(List<ClusterMemberAddress> clusterMemberAddress) {
this.clusterMemberAddress = clusterMemberAddress;
return this;
}
public Builder withLabels(Map<String, String> labels) {
this.labels = labels;
return this;
}
public ClusterMember build() {
Preconditions.checkNotNull(memberId, "Member id is null");
return new ClusterMember(memberId, enabled, registered, active, clusterMemberAddress, labels);
}
}
}
| 9,765 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model/ClusterMemberLeadershipState.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.api.clustermembership.model;
public enum ClusterMemberLeadershipState {
/**
* Member is not part of the leadership process.
*/
Disabled,
/**
* Member is healthy, and participates in the leader election process, but is not the leader yet.
*/
NonLeader,
/**
* Member is a current leader.
*/
Leader,
/**
* Leadership state of a member is unknown.
*/
Unknown
}
| 9,766 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model/ClusterMembershipFunctions.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.api.clustermembership.model;
import java.util.List;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.StringExt;
/**
* A collection of common functions operating on {@link ClusterMembershipRevision} and related entities.
*/
public final class ClusterMembershipFunctions {
private ClusterMembershipFunctions() {
}
public static boolean hasIpAddress(ClusterMember clusterMember, String ipAddress) {
if (StringExt.isEmpty(ipAddress)) {
return false;
}
List<ClusterMemberAddress> addresses = clusterMember.getClusterMemberAddresses();
if (CollectionsExt.isNullOrEmpty(addresses)) {
return false;
}
for (ClusterMemberAddress address : addresses) {
if (ipAddress.equals(address.getIpAddress())) {
return true;
}
}
return false;
}
public static String toStringUri(ClusterMemberAddress address) {
return address.getProtocol() + "://" + address.getIpAddress() + ':' + address.getPortNumber();
}
}
| 9,767 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model/ClusterMembershipRevision.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.api.clustermembership.model;
import java.util.Objects;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.Evaluators;
public class ClusterMembershipRevision<T> {
private final T current;
private final String code;
private final String message;
private final long revision;
private final long timestamp;
public ClusterMembershipRevision(T current,
String code,
String message,
long revision,
long timestamp) {
this.current = current;
this.code = Evaluators.getOrDefault(code, "");
this.message = Evaluators.getOrDefault(message, "");
this.revision = revision;
this.timestamp = timestamp;
}
public T getCurrent() {
return current;
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
public long getRevision() {
return revision;
}
public long getTimestamp() {
return timestamp;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClusterMembershipRevision revision1 = (ClusterMembershipRevision) o;
return revision == revision1.revision &&
timestamp == revision1.timestamp &&
Objects.equals(current, revision1.current) &&
Objects.equals(code, revision1.code) &&
Objects.equals(message, revision1.message);
}
@Override
public int hashCode() {
return Objects.hash(current, code, message, revision, timestamp);
}
@Override
public String toString() {
return "ClusterMembershipRevision{" +
"current=" + current +
", code='" + code + '\'' +
", message='" + message + '\'' +
", revision=" + revision +
", timestamp=" + timestamp +
'}';
}
public Builder<T> toBuilder() {
return ClusterMembershipRevision.<T>newBuilder().withCurrent(current).withCode(code).withMessage(message).withRevision(revision).withTimestamp(timestamp);
}
public static <T> Builder<T> newBuilder() {
return new Builder<>();
}
public static final class Builder<T> {
private T current;
private String code;
private String message;
private long timestamp;
private long revision;
private Builder() {
}
public Builder<T> withCurrent(T current) {
this.current = current;
return this;
}
public Builder<T> withCode(String code) {
this.code = code;
return this;
}
public Builder<T> withMessage(String message) {
this.message = message;
return this;
}
public Builder<T> withTimestamp(long timestamp) {
this.timestamp = timestamp;
return this;
}
public Builder<T> withRevision(long revision) {
this.revision = revision;
return this;
}
public ClusterMembershipRevision<T> build() {
Preconditions.checkNotNull(current, "Current object not set");
return new ClusterMembershipRevision<>(current, code, message, revision, timestamp);
}
}
}
| 9,768 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model/event/ClusterMembershipEvent.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.api.clustermembership.model.event;
import java.util.List;
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.ClusterMembershipRevision;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipChangeEvent.ChangeType;
public abstract class ClusterMembershipEvent {
public static ClusterMembershipSnapshotEvent snapshotEvent(
List<ClusterMembershipRevision<ClusterMember>> clusterMemberRevisions,
ClusterMembershipRevision<ClusterMemberLeadership> localLeadership,
Optional<ClusterMembershipRevision<ClusterMemberLeadership>> leader) {
return new ClusterMembershipSnapshotEvent(clusterMemberRevisions, localLeadership, leader);
}
public static ClusterMembershipChangeEvent memberAddedEvent(ClusterMembershipRevision<ClusterMember> revision) {
return new ClusterMembershipChangeEvent(ChangeType.Added, revision);
}
public static ClusterMembershipChangeEvent memberRemovedEvent(ClusterMembershipRevision<ClusterMember> revision) {
return new ClusterMembershipChangeEvent(ChangeType.Removed, revision);
}
public static ClusterMembershipChangeEvent memberUpdatedEvent(ClusterMembershipRevision<ClusterMember> revision) {
return new ClusterMembershipChangeEvent(ChangeType.Updated, revision);
}
public static LeaderElectionChangeEvent localJoinedElection(ClusterMembershipRevision<ClusterMemberLeadership> leadershipRevision) {
return new LeaderElectionChangeEvent(LeaderElectionChangeEvent.ChangeType.LocalJoined, leadershipRevision);
}
public static LeaderElectionChangeEvent localLeftElection(ClusterMembershipRevision<ClusterMemberLeadership> leadershipRevision) {
return new LeaderElectionChangeEvent(LeaderElectionChangeEvent.ChangeType.LocalLeft, leadershipRevision);
}
public static LeaderElectionChangeEvent leaderLost(ClusterMembershipRevision<ClusterMemberLeadership> leadershipRevision) {
return new LeaderElectionChangeEvent(LeaderElectionChangeEvent.ChangeType.LeaderLost, leadershipRevision);
}
public static LeaderElectionChangeEvent leaderElected(ClusterMembershipRevision<ClusterMemberLeadership> leadershipRevision) {
return new LeaderElectionChangeEvent(LeaderElectionChangeEvent.ChangeType.LeaderElected, leadershipRevision);
}
}
| 9,769 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model/event/ClusterMembershipSnapshotEvent.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.api.clustermembership.model.event;
import java.util.List;
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.ClusterMembershipRevision;
public class ClusterMembershipSnapshotEvent extends ClusterMembershipEvent {
private final List<ClusterMembershipRevision<ClusterMember>> clusterMemberRevisions;
private final ClusterMembershipRevision<ClusterMemberLeadership> localLeadership;
private final Optional<ClusterMembershipRevision<ClusterMemberLeadership>> leader;
ClusterMembershipSnapshotEvent(List<ClusterMembershipRevision<ClusterMember>> clusterMemberRevisions,
ClusterMembershipRevision<ClusterMemberLeadership> localLeadership,
Optional<ClusterMembershipRevision<ClusterMemberLeadership>> leader) {
this.clusterMemberRevisions = clusterMemberRevisions;
this.localLeadership = localLeadership;
this.leader = leader;
}
public List<ClusterMembershipRevision<ClusterMember>> getClusterMemberRevisions() {
return clusterMemberRevisions;
}
public ClusterMembershipRevision<ClusterMemberLeadership> getLocalLeadership() {
return localLeadership;
}
public Optional<ClusterMembershipRevision<ClusterMemberLeadership>> getLeader() {
return leader;
}
}
| 9,770 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model/event/ClusterMembershipChangeEvent.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.api.clustermembership.model.event;
import java.util.Objects;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
public class ClusterMembershipChangeEvent extends ClusterMembershipEvent {
public enum ChangeType {
Added,
Updated,
Removed
}
private final ChangeType changeType;
private final ClusterMembershipRevision<ClusterMember> revision;
public ClusterMembershipChangeEvent(ChangeType changeType, ClusterMembershipRevision<ClusterMember> revision) {
this.changeType = changeType;
this.revision = revision;
}
public ChangeType getChangeType() {
return changeType;
}
public ClusterMembershipRevision<ClusterMember> getRevision() {
return revision;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClusterMembershipChangeEvent that = (ClusterMembershipChangeEvent) o;
return changeType == that.changeType &&
Objects.equals(revision, that.revision);
}
@Override
public int hashCode() {
return Objects.hash(changeType, revision);
}
@Override
public String toString() {
return "ClusterMembershipChangeEvent{" +
"changeType=" + changeType +
", revision=" + revision +
'}';
}
}
| 9,771 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/model/event/LeaderElectionChangeEvent.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.api.clustermembership.model.event;
import java.util.Objects;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
public class LeaderElectionChangeEvent extends ClusterMembershipEvent {
public enum ChangeType {
/**
* Local member joined the leader election process.
*/
LocalJoined,
/**
* Local member left the leader election process.
*/
LocalLeft,
/**
* A new member is elected (local or sibling).
*/
LeaderElected,
/**
* Current leader (local or sibling) lost the leadership.
*/
LeaderLost
}
private final ChangeType changeType;
private final ClusterMembershipRevision<ClusterMemberLeadership> leadershipRevision;
LeaderElectionChangeEvent(ChangeType changeType, ClusterMembershipRevision<ClusterMemberLeadership> leadershipRevision) {
this.changeType = changeType;
this.leadershipRevision = leadershipRevision;
}
public ChangeType getChangeType() {
return changeType;
}
public ClusterMembershipRevision<ClusterMemberLeadership> getLeadershipRevision() {
return leadershipRevision;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LeaderElectionChangeEvent that = (LeaderElectionChangeEvent) o;
return changeType == that.changeType &&
Objects.equals(leadershipRevision, that.leadershipRevision);
}
@Override
public int hashCode() {
return Objects.hash(changeType, leadershipRevision);
}
@Override
public String toString() {
return "LeaderElectionChangeEvent{" +
"changeType=" + changeType +
", leadershipRevision=" + leadershipRevision +
'}';
}
}
| 9,772 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/connector/ClusterMembershipConnectorException.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.api.clustermembership.connector;
public class ClusterMembershipConnectorException extends RuntimeException {
public enum ErrorCode {
Conflict,
ClientError,
}
private final ErrorCode errorCode;
private ClusterMembershipConnectorException(ErrorCode errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public ErrorCode getErrorCode() {
return errorCode;
}
public static ClusterMembershipConnectorException clientError(String message, Throwable cause) {
return new ClusterMembershipConnectorException(
ErrorCode.ClientError,
String.format("Error during communicating with the cluster membership client: %s", message),
cause
);
}
public static ClusterMembershipConnectorException conflict(String message, Throwable cause) {
return new ClusterMembershipConnectorException(
ErrorCode.Conflict,
String.format("Request conflicts with the current sate: %s", message),
cause
);
}
}
| 9,773 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/connector/ClusterMembershipConnector.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.api.clustermembership.connector;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
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.ClusterMembershipEvent;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Connector to an external cluster membership orchestrator (Etcd, Zookeeper, Kubernetes, etc).
*/
public interface ClusterMembershipConnector {
/**
* Returns cluster member data for the local member.
*/
ClusterMembershipRevision<ClusterMember> getLocalClusterMemberRevision();
/**
* Returns all known siblings of the given cluster member.
*/
Map<String, ClusterMembershipRevision<ClusterMember>> getClusterMemberSiblings();
/**
* Returns the leadership state of the local member.
*/
ClusterMembershipRevision<ClusterMemberLeadership> getLocalLeadershipRevision();
/**
* Returns current leader or {@link Optional#empty()} if there is no leader.
*/
Optional<ClusterMembershipRevision<ClusterMemberLeadership>> findCurrentLeader();
/**
* Store {@link ClusterMember} data associated with the given instance. The result {@link Mono} completes when
* the request data are persisted in the external store.
*
* <h1>Event ordering</h1>
* Concurrent calls to this method are serialized. After the change is recorded by the connector, a corresponding
* event is first emitted by {@link #membershipChangeEvents()}, and only after the request is completed, and the
* identical revision data are emitted in response.
*
* @return cluster member revision created by this update operation
*/
Mono<ClusterMembershipRevision<ClusterMember>> register(Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> selfUpdate);
/**
* Remove the local member from the membership group. If the member is part of the leadership process the request
* is rejected.
*/
Mono<ClusterMembershipRevision<ClusterMember>> unregister(Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> selfUpdate);
/**
* Join leader election process. Only allowed for registered members.
*/
Mono<Void> joinLeadershipGroup();
/**
* Request the local member to leave the leader election process. The method completes when the leadership abort
* is completed. This means that by the time it completes, another cluster member can be elected a new leader and
* take over the traffic. It is important this this method is only called after the local node stops taking traffic,
* and synchronizes all state to external stores.
*
* <h1>Event ordering</h1>
* Follow the same rules as {@link #register(Function)} (see above).
*
* @param onlyNonLeader if set to true, the leader election process is terminated only if the local member is not an elected leader
* @return true if the local member left the leader election process
*/
Mono<Boolean> leaveLeadershipGroup(boolean onlyNonLeader);
/**
* Cluster membership change events. The event stream includes all members both local and siblings.
* Emits snapshot data on subscription followed by update events.
*/
Flux<ClusterMembershipEvent> membershipChangeEvents();
}
| 9,774 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/service/ClusterMembershipServiceException.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.api.clustermembership.service;
public class ClusterMembershipServiceException extends RuntimeException {
public enum ErrorCode {
BadSelfUpdate,
Internal,
LocalMemberOnly,
MemberNotFound,
}
private final ErrorCode errorCode;
private ClusterMembershipServiceException(ErrorCode errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public ErrorCode getErrorCode() {
return errorCode;
}
public static ClusterMembershipServiceException memberNotFound(String memberId) {
return new ClusterMembershipServiceException(
ErrorCode.MemberNotFound,
"Member not found: memberId=" + memberId,
null
);
}
public static ClusterMembershipServiceException localOnly(String targetId) {
return new ClusterMembershipServiceException(
ErrorCode.LocalMemberOnly,
"Operation limited to the local member data. Call the target member API directly: targetId=" + targetId,
null
);
}
public static ClusterMembershipServiceException internalError(Throwable cause) {
return new ClusterMembershipServiceException(
ErrorCode.Internal,
"Unexpected internal error: " + cause.getMessage(),
cause
);
}
public static ClusterMembershipServiceException selfUpdateError(Throwable cause) {
return new ClusterMembershipServiceException(
ErrorCode.BadSelfUpdate,
"Error during updating local membership data: " + cause.getMessage(),
cause
);
}
}
| 9,775 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/clustermembership/service/ClusterMembershipService.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.api.clustermembership.service;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
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.ClusterMembershipEvent;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipSnapshotEvent;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface ClusterMembershipService {
/**
* Returns cluster member data for the local member.
*/
ClusterMembershipRevision<ClusterMember> getLocalClusterMember();
/**
* Returns all known siblings of the given cluster member.
*/
Map<String, ClusterMembershipRevision<ClusterMember>> getClusterMemberSiblings();
/**
* Returns the leadership state of the local member.
*/
ClusterMembershipRevision<ClusterMemberLeadership> getLocalLeadership();
/**
* Find leader.
*/
Optional<ClusterMembershipRevision<ClusterMemberLeadership>> findLeader();
/**
* Updates {@link ClusterMember} data associated with the given instance.
*/
Mono<ClusterMembershipRevision<ClusterMember>> updateSelf(Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> memberUpdate);
/**
* Requests the member that handles this request to stop being leader. If the given member
* is not a leader, the request is ignored.
*/
Mono<Void> stopBeingLeader();
/**
* Cluster membership change events. On subscription emits first {@link ClusterMembershipSnapshotEvent} event.
*/
Flux<ClusterMembershipEvent> events();
}
| 9,776 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/health/HealthState.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.api.health;
public enum HealthState {
Healthy,
Unhealthy,
Unknown
}
| 9,777 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/health/HealthStatus.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.api.health;
import java.util.Map;
import java.util.Objects;
public class HealthStatus {
private final HealthState healthState;
private final Map<String, Object> details;
public HealthStatus(HealthState healthState, Map<String, Object> details) {
this.healthState = healthState;
this.details = details;
}
public HealthState getHealthState() {
return healthState;
}
public Map<String, Object> getDetails() {
return details;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
HealthStatus that = (HealthStatus) o;
return healthState == that.healthState &&
Objects.equals(details, that.details);
}
@Override
public int hashCode() {
return Objects.hash(healthState, details);
}
@Override
public String toString() {
return "HealthStatus{" +
"healthState=" + healthState +
", details=" + details +
'}';
}
public Builder toBuilder() {
return newBuilder().withHealthState(healthState).withDetails(details);
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private HealthState healthState;
private Map<String, Object> details;
private Builder() {
}
public Builder withHealthState(HealthState healthState) {
this.healthState = healthState;
return this;
}
public Builder withDetails(Map<String, Object> details) {
this.details = details;
return this;
}
public HealthStatus build() {
return new HealthStatus(healthState, details);
}
}
}
| 9,778 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/health/HealthIndicators.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.api.health;
import java.util.Collections;
import java.util.Map;
public final class HealthIndicators {
private static final HealthStatus HEALTH_STATUS = HealthStatus.newBuilder()
.withHealthState(HealthState.Healthy)
.withDetails(Collections.emptyMap())
.build();
private static final Map<String, HealthStatus> COMPONENTS = Collections.singletonMap("alwaysHealthy", HEALTH_STATUS);
private static final HealthIndicator ALWAYS_HEALTHY_INDICATOR = new HealthIndicator() {
@Override
public Map<String, HealthStatus> getComponents() {
return COMPONENTS;
}
@Override
public HealthStatus health() {
return HEALTH_STATUS;
}
};
private HealthIndicators() {
}
public static HealthIndicator alwaysHealthy() {
return ALWAYS_HEALTHY_INDICATOR;
}
}
| 9,779 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/health/HealthIndicator.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.api.health;
import java.util.Map;
import reactor.core.publisher.Flux;
/**
* Health API similar to Netflix https://github.com/Netflix/runtime-health. Unlike the latter it provides
* synchronous health evaluator together with event stream to listen for changes.
*/
public interface HealthIndicator {
Map<String, HealthStatus> getComponents();
HealthStatus health();
/**
* We do not need the event stream yet, but it is provided for the API completeness.
*/
default Flux<HealthStatus> healthChangeEvents() {
throw new IllegalStateException("not implemented");
}
}
| 9,780 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/common/LeaderActivationListener.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.api.common;
/**
* Leader election process callback listeners.
*/
public interface LeaderActivationListener {
/**
* Called after a node become a leader.
*/
default void activate() {
}
/**
* Called after a node stopped being a leader.
*/
default void deactivate() {
}
}
| 9,781 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/Page.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.api.model;
import java.util.Objects;
import javax.validation.constraints.Min;
import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull;
/**
* An entity representing single page of a collection.
*/
@ClassFieldsNotNull
public class Page {
private static final Page EMPTY = new Page(0, 0, "");
private static final Page UNLIMITED = new Page(0, Integer.MAX_VALUE / 2, ""); // Do not use MAX_VALUE to prevent overflow
/**
* Requested page number, starting from 0 (defaults to 0 if not specified).
*/
@Min(value = 0, message = "Page number cannot be negative")
private final int pageNumber;
/**
* Requested page size (if not specified, default size is operation specific).
*/
@Min(value = 0, message = "Page size cannot be negative")
private final int pageSize;
private final String cursor;
public Page(int pageNumber, int pageSize, String cursor) {
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.cursor = cursor;
}
public int getPageNumber() {
return pageNumber;
}
public int getPageSize() {
return pageSize;
}
public String getCursor() {
return cursor;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Page page = (Page) o;
return pageNumber == page.pageNumber &&
pageSize == page.pageSize &&
Objects.equals(cursor, page.cursor);
}
@Override
public int hashCode() {
return Objects.hash(pageNumber, pageSize, cursor);
}
@Override
public String toString() {
return "Page{" +
"pageNumber=" + pageNumber +
", pageSize=" + pageSize +
", cursor='" + cursor + '\'' +
'}';
}
public Builder toBuilder() {
return newBuilder(this);
}
public static Page empty() {
return EMPTY;
}
public static Page first(int pageSize) {
return new Page(0, pageSize, "");
}
public static Page unlimited() {
return UNLIMITED;
}
public static Builder newBuilder() {
return new Builder();
}
public static Builder newBuilder(Page source) {
return new Builder()
.withPageNumber(source.getPageNumber())
.withPageSize(source.getPageSize())
.withCursor(source.getCursor());
}
public static final class Builder {
private int pageNumber;
private int pageSize;
private String cursor = "";
private Builder() {
}
public Builder withPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
return this;
}
public Builder withPageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
public Builder withCursor(String cursor) {
this.cursor = cursor;
return this;
}
public Builder but() {
return newBuilder().withPageNumber(pageNumber).withPageSize(pageSize).withCursor(cursor);
}
public Page build() {
return new Page(pageNumber, pageSize, cursor);
}
}
}
| 9,782 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/Pagination.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.api.model;
import java.util.Objects;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull;
/**
* An entity representing pagination information returned to a client iterating over its elements.
* It includes current page that the client requested, and the total collection size.
* As not always pageCount * pageSize == itemCount, the item count is included as well.
*/
@ClassFieldsNotNull
public class Pagination {
@Valid
private final Page currentPage;
private final boolean hasMore;
@Min(value = 0, message = "'totalPages' value cannot be negative")
private final int totalPages;
@Min(value = 0, message = "'totalItems' value cannot be negative")
private final int totalItems;
private final String cursor;
/**
* Position of the cursor relative to <tt>totalItems</tt>
*/
private final int cursorPosition;
public Pagination(Page currentPage, boolean hasMore, int totalPages, int totalItems, String cursor, int cursorPosition) {
this.currentPage = currentPage;
this.hasMore = hasMore;
this.totalPages = totalPages;
this.totalItems = totalItems;
this.cursor = cursor;
this.cursorPosition = cursorPosition;
}
public Page getCurrentPage() {
return currentPage;
}
public boolean hasMore() {
return hasMore;
}
public int getTotalPages() {
return totalPages;
}
public int getTotalItems() {
return totalItems;
}
public String getCursor() {
return cursor;
}
public int getCursorPosition() {
return cursorPosition;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Pagination)) {
return false;
}
Pagination that = (Pagination) o;
return hasMore == that.hasMore &&
totalPages == that.totalPages &&
totalItems == that.totalItems &&
cursorPosition == that.cursorPosition &&
Objects.equals(currentPage, that.currentPage) &&
Objects.equals(cursor, that.cursor);
}
@Override
public int hashCode() {
return Objects.hash(currentPage, hasMore, totalPages, totalItems, cursor, cursorPosition);
}
@Override
public String toString() {
return "Pagination{" +
"currentPage=" + currentPage +
", hasMore=" + hasMore +
", totalPages=" + totalPages +
", totalItems=" + totalItems +
", cursor='" + cursor + '\'' +
", cursorPosition=" + cursorPosition +
'}';
}
public Builder toBuilder() {
return newBuilder(this);
}
public static Pagination empty(Page page) {
return new Pagination(page, false, 0, 0, "", 0);
}
public static Builder newBuilder() {
return new Builder();
}
public static Builder newBuilder(Pagination other) {
return new Builder()
.withCurrentPage(other.currentPage)
.withHasMore(other.hasMore)
.withTotalPages(other.totalPages)
.withTotalItems(other.totalItems)
.withCursor(other.cursor)
.withCursorPosition(other.cursorPosition);
}
public static final class Builder {
private Page currentPage;
private boolean hasMore;
private int totalPages;
private int totalItems;
private String cursor;
private int cursorPosition;
private Builder() {
}
public Builder withCurrentPage(Page currentPage) {
this.currentPage = currentPage;
return this;
}
public Builder withHasMore(boolean hasMore) {
this.hasMore = hasMore;
return this;
}
public Builder withTotalPages(int totalPages) {
this.totalPages = totalPages;
return this;
}
public Builder withTotalItems(int totalItems) {
this.totalItems = totalItems;
return this;
}
public Builder withCursor(String cursor) {
this.cursor = cursor;
return this;
}
public Builder withCursorPosition(int cursorPosition) {
this.cursorPosition = cursorPosition;
return this;
}
public Builder but() {
return newBuilder().withCurrentPage(currentPage).withHasMore(hasMore).withTotalPages(totalPages).withTotalItems(totalItems).withCursor(cursor).withCursorPosition(cursorPosition);
}
public Pagination build() {
return new Pagination(currentPage, hasMore, totalPages, totalItems, cursor, cursorPosition);
}
}
}
| 9,783 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/PaginationEvaluator.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.api.model;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.Evaluators;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.common.util.tuple.Pair;
public class PaginationEvaluator<T> {
private static final Pattern CURSOR_RE = Pattern.compile("(.*)@(\\d+)");
private final Function<T, String> idExtractor;
private final Function<T, Long> timestampExtractor;
private final Comparator<T> dataComparator;
public PaginationEvaluator(Function<T, String> idExtractor, Function<T, Long> timestampExtractor) {
this.idExtractor = idExtractor;
this.timestampExtractor = timestampExtractor;
this.dataComparator = (first, second) -> {
long firstTimestamp = Evaluators.getOrDefault(timestampExtractor.apply(first), 0L);
long secondTimestamp = Evaluators.getOrDefault(timestampExtractor.apply(second), 0L);
int timestampCmp = Long.compare(firstTimestamp, secondTimestamp);
if (timestampCmp != 0) {
return timestampCmp;
}
String firstId = idExtractor.apply(first);
String secondId = idExtractor.apply(second);
return firstId.compareTo(secondId);
};
}
public PageResult<T> takePage(Page page, List<T> items) {
if (page.getPageSize() < 0) {
throw PaginationException.badPageSize(page.getPageSize());
}
if (page.getPageSize() == 0) {
return takeEmptyPage(page, items);
}
List<T> itemsCopy = new ArrayList<>(items);
itemsCopy.sort(dataComparator);
if (StringExt.isEmpty(page.getCursor())) {
return takePageWithoutCursor(page, itemsCopy);
}
Pair<String, Long> decodedCursor = decode(page.getCursor());
return takePageWithCursor(page, itemsCopy, decodedCursor.getLeft(), decodedCursor.getRight());
}
private PageResult<T> takeEmptyPage(Page page, List<T> items) {
return PageResult.pageOf(
Collections.emptyList(),
Pagination.newBuilder()
.withCurrentPage(page)
.withCursor("")
.withTotalItems(items.size())
.withTotalPages(1)
.withHasMore(false)
.build()
);
}
/**
* {@link Page#getPageNumber() Number} (index) based pagination.
* <p>
* Please consider using {@link PaginationUtil#takePageWithCursor(Page, List, Comparator, PaginationUtil.CursorIndexOf, Function) cursor-based}
* pagination instead. This mode will be deprecated soon.
*/
private PageResult<T> takePageWithoutCursor(Page page, List<T> items) {
int totalItems = items.size();
if (totalItems <= 0 || page.getPageSize() <= 0) {
return PageResult.pageOf(Collections.emptyList(), new Pagination(page, false, 0, 0, "", 0));
}
int firstItem = page.getPageNumber() * page.getPageSize();
int lastItem = Math.min(totalItems, firstItem + page.getPageSize());
boolean more = totalItems > lastItem;
int totalPages = numberOfPages(page, totalItems);
List<T> pageItems = firstItem < lastItem
? items.subList(firstItem, lastItem)
: Collections.emptyList();
int cursorPosition = pageItems.isEmpty() ? 0 : lastItem - 1;
return PageResult.pageOf(pageItems, new Pagination(page, more, totalPages, totalItems, encode(pageItems.get(cursorPosition)), cursorPosition));
}
private PageResult<T> takePageWithCursor(Page page, List<T> itemsCopy, String cursorId, long cursorTimestamp) {
int offset = getOffset(itemsCopy, cursorId, cursorTimestamp);
int totalItems = itemsCopy.size();
boolean isEmptyResult = offset >= totalItems;
boolean hasMore = totalItems > (offset + page.getPageSize());
int endOffset = Math.min(totalItems, offset + page.getPageSize());
int cursorPosition = endOffset - 1;
int numberOfPages = numberOfPages(page, totalItems);
int pageNumber = Math.min(numberOfPages, offset / page.getPageSize());
Pagination pagination = new Pagination(
page.toBuilder().withPageNumber(pageNumber).build(),
hasMore,
numberOfPages,
totalItems,
totalItems == 0 ? "" : encode(itemsCopy.get(cursorPosition)),
totalItems == 0 ? 0 : cursorPosition
);
List<T> pageItems = isEmptyResult ? Collections.emptyList() : itemsCopy.subList(offset, endOffset);
return PageResult.pageOf(pageItems, pagination);
}
/**
* Offset is a position of an element after the one pointed by the cursor. If cursor does not point to any
* existing element, the offset points to the smallest element larger than cursor.
*/
private int getOffset(List<T> itemsCopy, String cursorId, long cursorTimestamp) {
if (itemsCopy.isEmpty()) {
return 0;
}
Function<T, Integer> comparator = item -> {
long itemTimestamp = Evaluators.getOrDefault(timestampExtractor.apply(item), 0L);
int timestampCmp = Long.compare(cursorTimestamp, itemTimestamp);
if (timestampCmp != 0) {
return timestampCmp;
}
String itemId = idExtractor.apply(item);
return cursorId.compareTo(itemId);
};
int pos = CollectionsExt.binarySearchLeftMost(itemsCopy, comparator);
return pos >= 0 ? (pos + 1) : -(pos + 1);
}
@VisibleForTesting
String encode(T value) {
String id = idExtractor.apply(value);
long timeStamp = Evaluators.getOrDefault(timestampExtractor.apply(value), 0L);
return Base64.getEncoder().encodeToString((id + '@' + timeStamp).getBytes());
}
private static Pair<String, Long> decode(String encoded) {
String decoded;
try {
decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
} catch (Exception e) {
throw PaginationException.badCursor(encoded);
}
Matcher matcher = CURSOR_RE.matcher(decoded);
boolean matches = matcher.matches();
if (!matches) {
throw PaginationException.badCursor(encoded, decoded);
}
String jobId = matcher.group(1);
long timestamp;
try {
timestamp = Long.parseLong(matcher.group(2));
} catch (NumberFormatException e) {
throw PaginationException.badCursor(encoded, decoded);
}
return Pair.of(jobId, timestamp);
}
private static int numberOfPages(Page page, int totalItems) {
return (totalItems + page.getPageSize() - 1) / page.getPageSize();
}
public static <T> Builder<T> newBuilder() {
return new Builder<>();
}
public static final class Builder<T> {
private Function<T, String> idExtractor;
private Function<T, Long> timestampExtractor;
private Builder() {
}
public Builder<T> withIdExtractor(Function<T, String> idExtractor) {
this.idExtractor = idExtractor;
return this;
}
public Builder<T> withTimestampExtractor(Function<T, Long> timestampExtractor) {
this.timestampExtractor = timestampExtractor;
return this;
}
public PaginationEvaluator<T> build() {
return new PaginationEvaluator<>(idExtractor, timestampExtractor);
}
}
}
| 9,784 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/IdAndTimestampKey.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.api.model;
import java.util.Objects;
import com.google.common.base.Preconditions;
public class IdAndTimestampKey<T> implements PaginableEntityKey<T> {
private final T entity;
private final String id;
private final long timestamp;
public IdAndTimestampKey(T entity, String id, long timestamp) {
Preconditions.checkNotNull(entity, "entity null");
Preconditions.checkNotNull(id, "entity id null");
this.entity = entity;
this.id = id;
this.timestamp = timestamp;
}
@Override
public T getEntity() {
return entity;
}
public String getId() {
return id;
}
public long getTimestamp() {
return timestamp;
}
@Override
public int compareTo(PaginableEntityKey<T> other) {
Preconditions.checkArgument(other instanceof IdAndTimestampKey, "Key of a different type passed to the comparator");
IdAndTimestampKey<T> otherKey = (IdAndTimestampKey<T>) other;
int cmp = Long.compare(timestamp, otherKey.timestamp);
if (cmp != 0) {
return cmp;
}
return id.compareTo(otherKey.id);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
IdAndTimestampKey<?> that = (IdAndTimestampKey<?>) o;
return timestamp == that.timestamp && Objects.equals(entity, that.entity) && Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(entity, id, timestamp);
}
@Override
public String toString() {
return "IdAndTimestampKey{" +
"id='" + id + '\'' +
", timestamp=" + timestamp +
'}';
}
}
| 9,785 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/PageResult.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.api.model;
import java.util.List;
import java.util.Objects;
public class PageResult<T> {
private final List<T> items;
private final Pagination pagination;
public PageResult(List<T> items, Pagination pagination) {
this.items = items;
this.pagination = pagination;
}
public List<T> getItems() {
return items;
}
public Pagination getPagination() {
return pagination;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PageResult<?> that = (PageResult<?>) o;
return Objects.equals(items, that.items) &&
Objects.equals(pagination, that.pagination);
}
@Override
public int hashCode() {
return Objects.hash(items, pagination);
}
@Override
public String toString() {
return "PageResult{" +
"items=" + items +
", pagination=" + pagination +
'}';
}
public static <T> PageResult<T> pageOf(List<T> items, Pagination pagination) {
return new PageResult<>(items, pagination);
}
}
| 9,786 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/PaginationException.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.api.model;
public class PaginationException extends RuntimeException {
public enum ErrorCode {
BAD_CURSOR,
BAD_PAGE_SIZE,
}
private final ErrorCode errorCode;
public PaginationException(ErrorCode errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public ErrorCode getErrorCode() {
return errorCode;
}
public static PaginationException badPageSize(int pageSize) {
return new PaginationException(ErrorCode.BAD_PAGE_SIZE, String.format("Bad page size (must be >= 0): %s", pageSize), null);
}
public static PaginationException badCursor(String cursor) {
return new PaginationException(ErrorCode.BAD_CURSOR, String.format("Bad cursor value: %s", cursor), null);
}
public static PaginationException badCursor(String encoded, String decoded) {
return new PaginationException(ErrorCode.BAD_CURSOR, String.format("Not a valid cursor value: encoded=%s, decoded=%s", encoded, decoded), null);
}
}
| 9,787 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/PaginableEntityKey.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.api.model;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
/**
* A key representation of an entity. Useful when the key is not the entity attribute and must be computed.
*/
public interface PaginableEntityKey<T> extends Comparable<PaginableEntityKey<T>> {
T getEntity();
static <T> List<T> sort(List<T> items, Function<T, PaginableEntityKey<T>> keyExtractor) {
List<PaginableEntityKey<T>> keys = new ArrayList<>();
for (T item : items) {
keys.add(keyExtractor.apply(item));
}
keys.sort(Comparable::compareTo);
List<T> sortedItems = new ArrayList<>();
for (PaginableEntityKey<T> key : keys) {
sortedItems.add(key.getEntity());
}
return sortedItems;
}
}
| 9,788 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/PaginationUtil.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.api.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.common.util.tuple.Pair;
/**
* Helper functions working with {@link Page} and {@link Pagination} objects.
*/
public final class PaginationUtil {
private PaginationUtil() {
}
/**
* Function that maps a cursor value to a position in a sorted list.
*/
public interface CursorIndexOf<T> extends BiFunction<List<T>, String, Optional<Integer>> {
}
/**
* Cursor-based pagination. When a cursor is present, the requested {@link Page#getPageNumber()} pageNumber} is
* ignored, and will be replaced in the {@link Pagination#getCurrentPage()} response} by an estimated
* <tt>pageNumber</tt> that includes the first item after the cursor.
* <p>
* If the {@link Page#getCursor() requested cursor} is empty, fallback to classic (pageNumber-based) pagination.
*/
public static <T> Pair<List<T>, Pagination> takePageWithCursor(Page page,
List<T> items,
Comparator<T> cursorComparator,
CursorIndexOf<T> cursorIndexOf,
Function<T, String> cursorFactory) {
List<T> itemsCopy = new ArrayList<>(items);
itemsCopy.sort(cursorComparator);
return takePageWithCursorInternal(page, cursorIndexOf, cursorFactory, itemsCopy);
}
public static <T> Pair<List<T>, Pagination> takePageWithCursorAndKeyExtractor(Page page,
List<T> items,
Function<T, PaginableEntityKey<T>> keyExtractor,
CursorIndexOf<T> cursorIndexOf,
Function<T, String> cursorFactory) {
List<T> itemsCopy = PaginableEntityKey.sort(items, keyExtractor);
return takePageWithCursorInternal(page, cursorIndexOf, cursorFactory, itemsCopy);
}
private static <T> Pair<List<T>, Pagination> takePageWithCursorInternal(Page page,
CursorIndexOf<T> cursorIndexOf,
Function<T, String> cursorFactory,
List<T> sortedItems) {
if (StringExt.isEmpty(page.getCursor())) {
return takePageWithoutCursor(page, sortedItems, cursorFactory);
}
int offset = cursorIndexOf.apply(sortedItems, page.getCursor())
.orElseThrow(() -> new IllegalArgumentException("Invalid cursor: " + page.getCursor())) + 1;
int totalItems = sortedItems.size();
boolean isEmptyResult = offset >= totalItems;
boolean hasMore = totalItems > (offset + page.getPageSize());
int endOffset = Math.min(totalItems, offset + page.getPageSize());
int cursorPosition = endOffset - 1;
int numberOfPages = numberOfPages(page, totalItems);
int pageNumber = Math.min(numberOfPages, offset / page.getPageSize());
Pagination pagination = new Pagination(
page.toBuilder().withPageNumber(pageNumber).build(),
hasMore,
numberOfPages,
totalItems,
totalItems == 0 ? "" : cursorFactory.apply(sortedItems.get(cursorPosition)),
totalItems == 0 ? 0 : cursorPosition
);
List<T> pageItems = isEmptyResult ? Collections.emptyList() : sortedItems.subList(offset, endOffset);
return Pair.of(pageItems, pagination);
}
/**
* {@link Page#getPageNumber() Number} (index) based pagination.
* <p>
* Please consider using {@link PaginationUtil#takePageWithCursor(Page, List, Comparator, CursorIndexOf, Function) cursor-based}
* pagination instead. This mode will be deprecated soon.
*/
public static <T> Pair<List<T>, Pagination> takePageWithoutCursor(Page page, List<T> items, Function<T, String> cursorFactory) {
int totalItems = items.size();
if (totalItems <= 0 || page.getPageSize() <= 0) {
return Pair.of(Collections.emptyList(), new Pagination(page, false, 0, 0, "", 0));
}
int firstItem = page.getPageNumber() * page.getPageSize();
int lastItem = Math.min(totalItems, firstItem + page.getPageSize());
boolean more = totalItems > lastItem;
int totalPages = numberOfPages(page, totalItems);
List<T> pageItems = firstItem < lastItem
? items.subList(firstItem, lastItem)
: Collections.emptyList();
String cursor = pageItems.isEmpty() ? "" : cursorFactory.apply(pageItems.get(pageItems.size() - 1));
int cursorPosition = pageItems.isEmpty() ? 0 : lastItem - 1;
return Pair.of(pageItems, new Pagination(page, more, totalPages, totalItems, cursor, cursorPosition));
}
public static int numberOfPages(Page page, int totalItems) {
return (totalItems + page.getPageSize() - 1) / page.getPageSize();
}
}
| 9,789 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/callmetadata/CallerType.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.api.model.callmetadata;
import com.netflix.titus.common.util.StringExt;
public enum CallerType {
Application,
Unknown,
User;
public static CallerType parseCallerType(String callerId, String callerType) {
String trimmedType = StringExt.safeTrim(callerType);
if (trimmedType.isEmpty()) {
return callerId.contains("@") ? User : Application;
}
try {
return StringExt.parseEnumIgnoreCase(trimmedType, CallerType.class);
} catch (Exception e) {
return CallerType.Unknown;
}
}
}
| 9,790 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/callmetadata/CallMetadataConstants.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.api.model.callmetadata;
public class CallMetadataConstants {
/**
* Call metadata for an undefined caller.
*/
public static final CallMetadata UNDEFINED_CALL_METADATA = CallMetadata.newBuilder().withCallerId("Unknown").withCallReason("Unknown").build();
/**
* Call metadata for replicator event stream
*/
public static final CallMetadata GRPC_REPLICATOR_CALL_METADATA = CallMetadata.newBuilder().withCallerId("ReplicatorEvent").withCallReason("Replication").build();
}
| 9,791 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/callmetadata/CallMetadata.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.api.model.callmetadata;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.StringExt;
public class CallMetadata {
/**
* @deprecated Use {@link #callers} instead.
*/
@Deprecated
private final String callerId;
private final String callReason;
/**
* @deprecated Use {@link #callers} instead.
*/
@Deprecated
private final List<String> callPath;
private final List<Caller> callers;
private final boolean debug;
public CallMetadata(String callerId,
String callReason,
List<String> callPath,
List<Caller> callers,
boolean debug) {
this.callerId = callerId;
this.callReason = callReason;
this.callPath = callPath;
this.callers = callers;
this.debug = debug;
}
@Deprecated
public String getCallerId() {
return callerId;
}
public String getCallReason() {
return callReason;
}
public List<String> getCallPath() {
return callPath;
}
public List<Caller> getCallers() {
return callers;
}
public boolean isDebug() {
return debug;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CallMetadata that = (CallMetadata) o;
return debug == that.debug &&
Objects.equals(callerId, that.callerId) &&
Objects.equals(callReason, that.callReason) &&
Objects.equals(callPath, that.callPath) &&
Objects.equals(callers, that.callers);
}
@Override
public int hashCode() {
return Objects.hash(callerId, callReason, callPath, callers, debug);
}
@Override
public String toString() {
return "CallMetadata{" +
"callerId='" + callerId + '\'' +
", callReason='" + callReason + '\'' +
", callPath=" + callPath +
", callers=" + callers +
", debug=" + debug +
'}';
}
public static Builder newBuilder() {
return new Builder();
}
public Builder toBuilder() {
return newBuilder().withCallerId(callerId).withCallReason(callReason).withCallPath(callPath).withDebug(debug);
}
public static final class Builder {
private String callerId;
private String callReason;
private List<String> callPath;
private boolean debug;
private List<Caller> callers;
private Builder() {
}
public Builder withCallerId(String callerId) {
this.callerId = callerId;
return this;
}
public Builder withCallReason(String callReason) {
this.callReason = callReason;
return this;
}
public Builder withCallPath(List<String> callPath) {
this.callPath = callPath;
return this;
}
public Builder withCallers(List<Caller> callers) {
this.callers = callers;
return this;
}
public Builder withDebug(boolean debug) {
this.debug = debug;
return this;
}
public Builder but() {
return newBuilder().withCallerId(callerId).withCallReason(callReason).withCallPath(callPath).withDebug(debug);
}
public CallMetadata build() {
this.callReason = StringExt.safeTrim(callReason);
if (!CollectionsExt.isNullOrEmpty(callers)) {
return buildNew();
}
// Legacy
Preconditions.checkNotNull(callerId, "The original caller id not");
List<Caller> callersFromLegacy = Collections.singletonList(
Caller.newBuilder()
.withId(callerId)
.withCallerType(CallerType.parseCallerType(callerId, ""))
.build()
);
return new CallMetadata(callerId, callReason, CollectionsExt.nonNull(callPath), callersFromLegacy, debug);
}
/**
* Populates deprecated fields from the callers.
*/
private CallMetadata buildNew() {
Caller originalCaller = callers.get(0);
return new CallMetadata(
originalCaller.getId(),
callReason,
callers.stream().map(Caller::getId).collect(Collectors.toList()),
callers,
debug
);
}
}
}
| 9,792 |
0 | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model | Create_ds/titus-control-plane/titus-common-api/src/main/java/com/netflix/titus/api/model/callmetadata/Caller.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.api.model.callmetadata;
import java.util.Map;
import java.util.Objects;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.CollectionsExt;
public class Caller {
private final String id;
private final CallerType callerType;
private final Map<String, String> context;
public Caller(String id, CallerType callerType, Map<String, String> context) {
this.id = id;
this.callerType = callerType;
this.context = context;
}
public String getId() {
return id;
}
public CallerType getCallerType() {
return callerType;
}
public Map<String, String> getContext() {
return context;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Caller caller = (Caller) o;
return Objects.equals(id, caller.id) &&
callerType == caller.callerType &&
Objects.equals(context, caller.context);
}
@Override
public int hashCode() {
return Objects.hash(id, callerType, context);
}
@Override
public String toString() {
return "Caller{" +
"id='" + id + '\'' +
", callerType=" + callerType +
", context=" + context +
'}';
}
public Builder toBuilder() {
return newBuilder().withId(id).withCallerType(callerType).withContext(context);
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private String id;
private CallerType callerType;
private Map<String, String> context;
private Builder() {
}
public Builder withId(String id) {
this.id = id;
return this;
}
public Builder withCallerType(CallerType callerType) {
this.callerType = callerType;
return this;
}
public Builder withContext(Map<String, String> context) {
this.context = context;
return this;
}
public Builder but() {
return newBuilder().withId(id).withCallerType(callerType).withContext(context);
}
public Caller build() {
Preconditions.checkNotNull(id, "Caller id is null");
Preconditions.checkNotNull(callerType, "Caller type is null");
return new Caller(id, callerType, CollectionsExt.nonNull(context));
}
}
}
| 9,793 |
0 | Create_ds/titus-control-plane/titus-common-client/src/test/java/com/netflix/titus/client/clustermembership | Create_ds/titus-control-plane/titus-common-client/src/test/java/com/netflix/titus/client/clustermembership/grpc/GrpcClusterMembershipLeaderNameResolverTest.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.client.clustermembership.grpc;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.List;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipSnapshot;
import com.netflix.titus.client.clustermembership.resolver.ClusterMemberResolver;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.runtime.TitusRuntimes;
import com.netflix.titus.common.util.rx.ReactorExt;
import com.netflix.titus.common.util.tuple.Either;
import com.netflix.titus.testkit.rx.TitusRxSubscriber;
import io.grpc.Attributes;
import io.grpc.EquivalentAddressGroup;
import io.grpc.NameResolver;
import io.grpc.Status;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.Flux;
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.leaderRevision;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class GrpcClusterMembershipLeaderNameResolverTest {
private static final ClusterMembershipRevision<ClusterMember> MEMBER_1 = clusterMemberRegistrationRevision(activeClusterMember("member1", "10.0.0.1"));
private static final ClusterMembershipRevision<ClusterMember> MEMBER_2 = clusterMemberRegistrationRevision(activeClusterMember("member2", "10.0.0.2"));
private static final Duration TIMEOUT = Duration.ofSeconds(5);
private final TitusRuntime titusRuntime = TitusRuntimes.internal();
private final GrpcClusterMembershipNameResolverConfiguration configuration = mock(GrpcClusterMembershipNameResolverConfiguration.class);
private final ClusterMemberResolver clusterResolver = mock(ClusterMemberResolver.class);
private GrpcClusterMembershipLeaderNameResolver nameResolver;
private volatile DirectProcessor<ClusterMembershipSnapshot> clusterEventProcessor;
private final TitusRxSubscriber<Either<List<EquivalentAddressGroup>, Status>> nameResolverSubscriber = new TitusRxSubscriber<>();
@Before
public void setUp() {
when(clusterResolver.resolve()).thenReturn(Flux.defer(() -> clusterEventProcessor = DirectProcessor.create()));
nameResolver = new GrpcClusterMembershipLeaderNameResolver(
configuration,
clusterResolver,
member -> member.getClusterMemberAddresses().get(0),
titusRuntime
);
Flux.<Either<List<EquivalentAddressGroup>, Status>>create(sink -> {
nameResolver.start(new NameResolver.Listener() {
@Override
public void onAddresses(List<EquivalentAddressGroup> servers, Attributes attributes) {
sink.next(Either.ofValue(servers));
}
@Override
public void onError(Status error) {
sink.next(Either.ofError(error));
}
});
sink.onCancel(() -> nameResolver.shutdown());
}).subscribe(nameResolverSubscriber);
}
@After
public void tearDown() {
ReactorExt.safeDispose(nameResolverSubscriber);
}
@Test
public void testLeaderSelection() throws InterruptedException {
// No members yet
clusterEventProcessor.onNext(ClusterMembershipSnapshot.empty());
expectError();
// Add member but not leader
clusterEventProcessor.onNext(ClusterMembershipSnapshot.newBuilder().withMemberRevisions(MEMBER_1).build());
expectError();
// Add another member, which is also a leader
clusterEventProcessor.onNext(ClusterMembershipSnapshot.newBuilder()
.withMemberRevisions(MEMBER_1, MEMBER_2)
.withLeaderRevision(leaderRevision(MEMBER_2))
.build());
expectLeader(MEMBER_2);
}
@Test
public void testRetryOnError() throws InterruptedException {
testRetryOnTerminatedStream(() -> clusterEventProcessor.onError(new RuntimeException("simulated error")));
}
@Test
public void testRetryWhenCompleted() throws InterruptedException {
testRetryOnTerminatedStream(() -> clusterEventProcessor.onComplete());
}
private void testRetryOnTerminatedStream(Runnable breakAction) throws InterruptedException {
clusterEventProcessor.onNext(ClusterMembershipSnapshot.empty());
assertThat(nameResolverSubscriber.takeNext(TIMEOUT)).isNotNull();
DirectProcessor<ClusterMembershipSnapshot> currentProcessor = clusterEventProcessor;
breakAction.run();
await().until(() -> clusterEventProcessor != currentProcessor);
clusterEventProcessor.onNext(ClusterMembershipSnapshot.empty());
assertThat(nameResolverSubscriber.takeNext(TIMEOUT)).isNotNull();
}
private void expectLeader(ClusterMembershipRevision<ClusterMember> leaderMember) throws InterruptedException {
Either<List<EquivalentAddressGroup>, Status> event = nameResolverSubscriber.takeNext(TIMEOUT);
assertThat(event).isNotNull();
assertThat(event.hasValue()).isTrue();
assertThat(event.getValue()).hasSize(1);
EquivalentAddressGroup addressGroup = event.getValue().get(0);
assertThat(addressGroup.getAddresses()).hasSize(1);
InetSocketAddress ipAddress = (InetSocketAddress) addressGroup.getAddresses().get(0);
assertThat(ipAddress.getHostString()).isEqualTo(leaderMember.getCurrent().getClusterMemberAddresses().get(0).getIpAddress());
}
private void expectError() throws InterruptedException {
Either<List<EquivalentAddressGroup>, Status> event = nameResolverSubscriber.takeNext(TIMEOUT);
assertThat(event).isNotNull();
assertThat(event.hasError()).isTrue();
assertThat(event.getError().getCode()).isEqualTo(Status.Code.UNAVAILABLE);
}
} | 9,794 |
0 | Create_ds/titus-control-plane/titus-common-client/src/test/java/com/netflix/titus/client/clustermembership | Create_ds/titus-control-plane/titus-common-client/src/test/java/com/netflix/titus/client/clustermembership/resolver/MultiNodeClusterMemberResolverTest.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.client.clustermembership.resolver;
import java.time.Duration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMemberAddress;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipSnapshot;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.runtime.TitusRuntimes;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.ReplayProcessor;
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.leaderRevision;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MultiNodeClusterMemberResolverTest {
private static final java.time.Duration TIMEOUT = Duration.ofSeconds(5);
private static final String TEST_SERVICE = "testService";
private static final ClusterMembershipRevision<ClusterMember> MEMBER_1 = clusterMemberRegistrationRevision(activeClusterMember("member1", "10.0.0.1"));
private static final ClusterMembershipRevision<ClusterMember> MEMBER_2 = clusterMemberRegistrationRevision(activeClusterMember("member2", "10.0.0.2"));
private static final ClusterMembershipRevision<ClusterMember> MEMBER_3 = clusterMemberRegistrationRevision(activeClusterMember("member3", "10.0.0.3"));
private final TitusRuntime titusRuntime = TitusRuntimes.internal(Duration.ofMillis(1));
private final ClusterMembershipResolverConfiguration configuration = mock(ClusterMembershipResolverConfiguration.class);
private final TestableDirectClusterMemberResolver memberResolver1 = new TestableDirectClusterMemberResolver(MEMBER_1);
private final TestableDirectClusterMemberResolver memberResolver2 = new TestableDirectClusterMemberResolver(MEMBER_2);
private final TestableDirectClusterMemberResolver memberResolver3 = new TestableDirectClusterMemberResolver(MEMBER_3);
private MultiNodeClusterMemberResolver resolver;
private final ConcurrentMap<String, ClusterMemberAddress> seedAddresses = new ConcurrentHashMap<>();
@Before
public void setUp() {
when(configuration.getMultiMemberRefreshIntervalMs()).thenReturn(10L);
addSeed(MEMBER_1);
this.resolver = new MultiNodeClusterMemberResolver(
TEST_SERVICE,
configuration,
() -> new HashSet<>(seedAddresses.values()),
address -> {
if (isSameIpAddress(address, MEMBER_1)) {
return memberResolver1;
}
if (isSameIpAddress(address, MEMBER_2)) {
return memberResolver2;
}
if (isSameIpAddress(address, MEMBER_3)) {
return memberResolver3;
}
throw new IllegalStateException("unrecognized address: " + address);
},
member -> member.getClusterMemberAddresses().get(0),
titusRuntime
);
memberResolver1.addMembers(MEMBER_1, MEMBER_2);
memberResolver2.addMembers(MEMBER_2);
memberResolver3.addMembers(MEMBER_3);
}
@Test(timeout = 30_000)
public void testInitialState() {
await().until(() -> resolver.getSnapshot().getMemberRevisions().size() == 2);
ClusterMembershipSnapshot snapshot = resolver.resolve().blockFirst(TIMEOUT);
assertThat(snapshot).isNotNull();
assertThat(snapshot.getMemberRevisions()).hasSize(2);
assertThat(snapshot.getLeaderRevision()).isEmpty();
assertThat(snapshot.getMemberRevisions().keySet()).contains("member1", "member2");
}
@Test(timeout = 30_000)
public void testNewMemberDiscovery() {
Iterator<ClusterMembershipSnapshot> eventIterator = resolver.resolve().toIterable().iterator();
eventIterator.next();
memberResolver1.addMembers(MEMBER_3);
await().until(() -> resolver.getSnapshot().getMemberRevisions().size() == 3);
ClusterMembershipSnapshot nextEvent = eventIterator.next();
assertThat(nextEvent.getMemberRevisions()).hasSize(3);
}
@Test
public void testSeedUpdate() {
Iterator<ClusterMembershipSnapshot> eventIterator = resolver.resolve().toIterable().iterator();
eventIterator.next();
addSeed(MEMBER_3);
await().until(() -> resolver.getSnapshot().getMemberRevisions().size() == 3);
ClusterMembershipSnapshot nextEvent = eventIterator.next();
assertThat(nextEvent.getMemberRevisions()).hasSize(3);
}
@Test(timeout = 30_000)
public void testMemberUpdate() {
Iterator<ClusterMembershipSnapshot> eventIterator = resolver.resolve().toIterable().iterator();
eventIterator.next();
long initialRevision = MEMBER_1.getRevision();
long nextRevision = initialRevision + 1;
memberResolver1.addMembers(MEMBER_1.toBuilder().withRevision(nextRevision).build());
ClusterMembershipSnapshot nextEvent = eventIterator.next();
assertThat(nextEvent.getMemberRevisions().get(MEMBER_1.getCurrent().getMemberId()).getRevision()).isEqualTo(nextRevision);
}
@Test(timeout = 30_000)
public void testMemberRemoval() {
Iterator<ClusterMembershipSnapshot> eventIterator = resolver.resolve().toIterable().iterator();
eventIterator.next();
memberResolver1.removeMembers(MEMBER_2.getCurrent().getMemberId());
memberResolver2.changeHealth(false);
ClusterMembershipSnapshot nextEvent = eventIterator.next();
assertThat(nextEvent.getMemberRevisions()).hasSize(1);
}
@Test(timeout = 30_000)
public void testLeaderElection() {
Iterator<ClusterMembershipSnapshot> eventIterator = resolver.resolve().toIterable().iterator();
eventIterator.next();
// Make member 1 the leader
memberResolver1.setAsLeader(MEMBER_1);
Optional<ClusterMembershipRevision<ClusterMemberLeadership>> firstLeader = eventIterator.next().getLeaderRevision();
assertThat(firstLeader).isPresent();
assertThat(firstLeader.get().getCurrent().getMemberId()).isEqualTo(MEMBER_1.getCurrent().getMemberId());
// Make member 2 the leader
memberResolver1.setAsLeader(MEMBER_2);
Optional<ClusterMembershipRevision<ClusterMemberLeadership>> secondLeader = eventIterator.next().getLeaderRevision();
assertThat(secondLeader).isPresent();
assertThat(secondLeader.get().getCurrent().getMemberId()).isEqualTo(MEMBER_2.getCurrent().getMemberId());
}
private void addSeed(ClusterMembershipRevision<ClusterMember> seedMember) {
seedAddresses.put(seedMember.getCurrent().getMemberId(), seedMember.getCurrent().getClusterMemberAddresses().get(0));
}
private boolean isSameIpAddress(ClusterMemberAddress address, ClusterMembershipRevision<ClusterMember> memberRevision) {
return address.getIpAddress().equals(memberRevision.getCurrent().getClusterMemberAddresses().get(0).getIpAddress());
}
private static class TestableDirectClusterMemberResolver implements DirectClusterMemberResolver {
private final ClusterMembershipRevision<ClusterMember> memberRevision;
private final ConcurrentMap<String, ClusterMembershipRevision<ClusterMember>> memberRevisionsById = new ConcurrentHashMap<>();
private volatile Optional<ClusterMembershipRevision<ClusterMemberLeadership>> currentLeaderOptional = Optional.empty();
private volatile boolean healthStatus = true;
private final ReplayProcessor<ClusterMembershipSnapshot> snapshotEventProcessor = ReplayProcessor.create(1);
private final FluxSink<ClusterMembershipSnapshot> snapshotFluxSink = snapshotEventProcessor.sink();
private TestableDirectClusterMemberResolver(ClusterMembershipRevision<ClusterMember> memberRevision) {
this.memberRevision = memberRevision;
}
@Override
public ClusterMemberAddress getAddress() {
return memberRevision.getCurrent().getClusterMemberAddresses().get(0);
}
@Override
public String getPrintableName() {
return memberRevision.getCurrent().getMemberId();
}
@Override
public boolean isHealthy() {
return healthStatus;
}
@Override
public void shutdown() {
}
@Override
public ClusterMembershipSnapshot getSnapshot() {
return newSnapshot();
}
private ClusterMembershipSnapshot newSnapshot() {
ClusterMembershipSnapshot.Builder builder = ClusterMembershipSnapshot.newBuilder().withMemberRevisions(memberRevisionsById.values());
currentLeaderOptional.ifPresent(builder::withLeaderRevision);
return builder.build();
}
@Override
public Flux<ClusterMembershipSnapshot> resolve() {
return snapshotEventProcessor;
}
@SafeVarargs
private final void addMembers(ClusterMembershipRevision<ClusterMember>... members) {
for (ClusterMembershipRevision<ClusterMember> member : members) {
memberRevisionsById.put(member.getCurrent().getMemberId(), member);
}
snapshotFluxSink.next(newSnapshot());
}
private void removeMembers(String... ids) {
for (String id : ids) {
memberRevisionsById.remove(id);
}
snapshotFluxSink.next(newSnapshot());
}
private void setAsLeader(ClusterMembershipRevision<ClusterMember> member) {
currentLeaderOptional = Optional.of(leaderRevision(member));
}
private void changeHealth(boolean healthStatus) {
this.healthStatus = healthStatus;
}
}
} | 9,795 |
0 | Create_ds/titus-control-plane/titus-common-client/src/test/java/com/netflix/titus/client/clustermembership | Create_ds/titus-control-plane/titus-common-client/src/test/java/com/netflix/titus/client/clustermembership/resolver/SimpleClusterMembershipClient.java | /*
* Copyright 2022 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.client.clustermembership.resolver;
import com.google.protobuf.Empty;
import com.netflix.titus.client.clustermembership.grpc.ClusterMembershipClient;
import com.netflix.titus.grpc.protogen.ClusterMembershipEvent;
import com.netflix.titus.grpc.protogen.ClusterMembershipRevision;
import com.netflix.titus.grpc.protogen.ClusterMembershipRevisions;
import com.netflix.titus.grpc.protogen.ClusterMembershipServiceGrpc;
import com.netflix.titus.grpc.protogen.ClusterMembershipServiceGrpc.ClusterMembershipServiceStub;
import com.netflix.titus.grpc.protogen.DeleteMemberLabelsRequest;
import com.netflix.titus.grpc.protogen.EnableMemberRequest;
import com.netflix.titus.grpc.protogen.MemberId;
import com.netflix.titus.grpc.protogen.UpdateMemberLabelsRequest;
import io.grpc.ManagedChannel;
import io.grpc.stub.StreamObserver;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoSink;
/**
* FIXME We need this implementation for testing as DefaultClusterMembershipClient is located in titus-common-server package.
* To resolve this issue we have to move CallMetadata classes to titus-common-client.
*/
class SimpleClusterMembershipClient implements ClusterMembershipClient {
private final ManagedChannel channel;
private final ClusterMembershipServiceStub stub;
public SimpleClusterMembershipClient(ManagedChannel channel) {
this.channel = channel;
this.stub = ClusterMembershipServiceGrpc.newStub(channel);
}
@Override
public Mono<ClusterMembershipRevisions> getMembers() {
return Mono.create(sink -> stub.getMembers(Empty.getDefaultInstance(), connectSink(sink)));
}
@Override
public Mono<ClusterMembershipRevision> getMember(MemberId request) {
return Mono.create(sink -> stub.getMember(request, connectSink(sink)));
}
@Override
public Mono<ClusterMembershipRevision> updateMemberLabels(UpdateMemberLabelsRequest request) {
return Mono.create(sink -> stub.updateMemberLabels(request, connectSink(sink)));
}
@Override
public Mono<ClusterMembershipRevision> deleteMemberLabels(DeleteMemberLabelsRequest request) {
return Mono.create(sink -> stub.deleteMemberLabels(request, connectSink(sink)));
}
@Override
public Mono<ClusterMembershipRevision> enableMember(EnableMemberRequest request) {
return Mono.create(sink -> stub.enableMember(request, connectSink(sink)));
}
@Override
public Mono<Void> stopBeingLeader() {
return Mono.<Empty>create(sink -> stub.stopBeingLeader(Empty.getDefaultInstance(), connectSink(sink)))
.ignoreElement()
.cast(Void.class);
}
@Override
public Flux<ClusterMembershipEvent> events() {
return Flux.create(sink -> {
stub.events(Empty.getDefaultInstance(), new StreamObserver<ClusterMembershipEvent>() {
@Override
public void onNext(ClusterMembershipEvent value) {
sink.next(value);
}
@Override
public void onError(Throwable t) {
sink.error(t);
}
@Override
public void onCompleted() {
sink.complete();
}
});
});
}
@Override
public void shutdown() {
channel.shutdownNow();
}
private <T> StreamObserver<T> connectSink(MonoSink<T> sink) {
return new StreamObserver<T>() {
@Override
public void onNext(T value) {
sink.success(value);
}
@Override
public void onError(Throwable t) {
sink.error(t);
}
@Override
public void onCompleted() {
sink.success();
}
};
}
}
| 9,796 |
0 | Create_ds/titus-control-plane/titus-common-client/src/test/java/com/netflix/titus/client/clustermembership | Create_ds/titus-control-plane/titus-common-client/src/test/java/com/netflix/titus/client/clustermembership/resolver/GrpcClusterMembershipServiceStub.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.client.clustermembership.resolver;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.google.protobuf.Empty;
import com.netflix.titus.grpc.protogen.ClusterMembershipEvent;
import com.netflix.titus.grpc.protogen.ClusterMembershipRevision;
import com.netflix.titus.grpc.protogen.ClusterMembershipServiceGrpc.ClusterMembershipServiceImplBase;
import io.grpc.stub.StreamObserver;
class GrpcClusterMembershipServiceStub extends ClusterMembershipServiceImplBase {
private final ConcurrentMap<String, ClusterMembershipRevision> memberRevisions = new ConcurrentHashMap<>();
private volatile StreamObserver<ClusterMembershipEvent> currentEventResponseObserver;
@Override
public void events(Empty request, StreamObserver<ClusterMembershipEvent> responseObserver) {
this.currentEventResponseObserver = responseObserver;
currentEventResponseObserver.onNext(ClusterMembershipEvent.newBuilder()
.setSnapshot(ClusterMembershipEvent.Snapshot.newBuilder()
.addAllRevisions(memberRevisions.values())
)
.build()
);
}
void addMember(ClusterMembershipRevision memberRevision) {
memberRevisions.put(memberRevision.getCurrent().getMemberId(), memberRevision);
if (currentEventResponseObserver != null) {
currentEventResponseObserver.onNext(ClusterMembershipEvent.newBuilder()
.setMemberUpdated(ClusterMembershipEvent.MemberUpdated.newBuilder()
.setRevision(memberRevision)
)
.build()
);
}
}
void removeMember(ClusterMembershipRevision memberRevision) {
memberRevisions.remove(memberRevision.getCurrent().getMemberId());
if (currentEventResponseObserver != null) {
currentEventResponseObserver.onNext(ClusterMembershipEvent.newBuilder()
.setMemberRemoved(ClusterMembershipEvent.MemberRemoved.newBuilder()
.setRevision(memberRevision)
)
.build()
);
}
}
void breakConnection() {
StreamObserver<ClusterMembershipEvent> observerToBreak = currentEventResponseObserver;
currentEventResponseObserver = null;
observerToBreak.onError(new RuntimeException("Simulated connection error"));
}
void completeEventStream() {
StreamObserver<ClusterMembershipEvent> observerToBreak = currentEventResponseObserver;
currentEventResponseObserver = null;
observerToBreak.onCompleted();
}
}
| 9,797 |
0 | Create_ds/titus-control-plane/titus-common-client/src/test/java/com/netflix/titus/client/clustermembership | Create_ds/titus-control-plane/titus-common-client/src/test/java/com/netflix/titus/client/clustermembership/resolver/SingleClusterMemberResolverTest.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.client.clustermembership.resolver;
import java.io.IOException;
import java.time.Duration;
import java.util.Iterator;
import com.netflix.titus.api.clustermembership.model.ClusterMemberAddress;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipSnapshot;
import com.netflix.titus.client.clustermembership.grpc.ClusterMembershipClient;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.runtime.TitusRuntimes;
import com.netflix.titus.common.util.ExceptionExt;
import com.netflix.titus.common.util.archaius2.Archaius2Ext;
import com.netflix.titus.common.util.closeable.CloseableReference;
import com.netflix.titus.grpc.protogen.ClusterMember;
import com.netflix.titus.grpc.protogen.ClusterMembershipRevision;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static com.jayway.awaitility.Awaitility.await;
import static org.assertj.core.api.Assertions.assertThat;
public class SingleClusterMemberResolverTest {
private static final String IP_PREFIX = "1.0.0.";
private static final ClusterMemberAddress ADDRESS = ClusterMemberAddress.newBuilder()
.withIpAddress(IP_PREFIX + "1")
.withProtocol("grpc")
.build();
private static final java.time.Duration TIMEOUT = Duration.ofSeconds(5);
private static final ClusterMembershipRevision MEMBER_1 = newMember(1);
private static final ClusterMembershipRevision MEMBER_2 = newMember(2);
private static final ClusterMembershipRevision MEMBER_3 = newMember(3);
private final TitusRuntime titusRuntime = TitusRuntimes.internal();
private final ClusterMembershipResolverConfiguration configuration = Archaius2Ext.newConfiguration(ClusterMembershipResolverConfiguration.class);
private final GrpcClusterMembershipServiceStub serviceStub = new GrpcClusterMembershipServiceStub();
private Server server;
private SingleClusterMemberResolver resolver;
@Before
public void setUp() throws IOException {
serviceStub.addMember(MEMBER_1.toBuilder()
.setCurrent(MEMBER_1.getCurrent().toBuilder()
.setLeadershipState(ClusterMember.LeadershipState.Leader)
)
.build()
);
serviceStub.addMember(MEMBER_2);
serviceStub.addMember(MEMBER_3);
setupServerAndResolver(member -> ClusterMemberVerifierResult.valid());
// Starts with a healthy connection.
await().until(() -> resolver.getPrintableName().equals(MEMBER_1.getCurrent().getMemberId()));
}
private void setupServerAndResolver(ClusterMemberVerifier clusterMemberVerifier) throws IOException {
tearDown();
String serviceName = "clusterMembershipService#" + System.currentTimeMillis();
this.server = InProcessServerBuilder.forName(serviceName)
.directExecutor()
.addService(serviceStub)
.build()
.start();
SimpleClusterMembershipClient client = new SimpleClusterMembershipClient(InProcessChannelBuilder.forName(serviceName).directExecutor().build());
this.resolver = new SingleClusterMemberResolver(
configuration,
CloseableReference.referenceOf(client, ClusterMembershipClient::shutdown),
ADDRESS,
clusterMemberVerifier,
titusRuntime
);
}
@After
public void tearDown() {
ExceptionExt.silent(resolver, SingleClusterMemberResolver::shutdown);
ExceptionExt.silent(server, Server::shutdownNow);
}
@Test(timeout = 30_000)
public void testInitialState() {
assertThat(resolver.isHealthy()).isTrue();
assertThat(resolver.getAddress()).isEqualTo(ADDRESS);
ClusterMembershipSnapshot snapshotEvent = resolver.resolve().blockFirst(TIMEOUT);
assertThat(snapshotEvent).isNotNull();
assertThat(snapshotEvent.getMemberRevisions()).hasSize(3);
assertThat(snapshotEvent.getLeaderRevision()).isNotEmpty();
}
@Test(timeout = 30_000)
public void testMemberUpdate() {
Iterator<ClusterMembershipSnapshot> eventIt = subscribeAndDiscardFirstSnapshot();
serviceStub.addMember(MEMBER_1.toBuilder()
.setMessage("Update")
.build()
);
ClusterMembershipSnapshot update = eventIt.next();
com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision<com.netflix.titus.api.clustermembership.model.ClusterMember> updated =
update.getMemberRevisions().get(MEMBER_1.getCurrent().getMemberId());
assertThat(updated.getMessage()).isEqualTo("Update");
}
@Test(timeout = 30_000)
public void testMemberRemoval() {
Iterator<ClusterMembershipSnapshot> eventIt = subscribeAndDiscardFirstSnapshot();
serviceStub.removeMember(MEMBER_2);
ClusterMembershipSnapshot update = eventIt.next();
assertThat(update.getMemberRevisions()).hasSize(2);
assertThat(update.getMemberRevisions()).doesNotContainKey(MEMBER_2.getCurrent().getMemberId());
}
@Test(timeout = 30_000)
public void testLeaderElection() {
Iterator<ClusterMembershipSnapshot> eventIt = subscribeAndDiscardFirstSnapshot();
// Elect a leader
serviceStub.addMember(MEMBER_2.toBuilder()
.setCurrent(MEMBER_2.getCurrent().toBuilder()
.setLeadershipState(ClusterMember.LeadershipState.Leader)
)
.build()
);
ClusterMembershipSnapshot leadElectedEvent = eventIt.next();
assertThat(leadElectedEvent.getLeaderRevision()).isNotEmpty();
// Loose the leader.
serviceStub.removeMember(MEMBER_2);
ClusterMembershipSnapshot leaderLostEvent = eventIt.next();
assertThat(leaderLostEvent.getLeaderRevision()).isEmpty();
}
@Test
public void testElectedLeaderSetInSnapshot() {
Iterator<ClusterMembershipSnapshot> eventIt = resolver.resolve().toIterable().iterator();
ClusterMembershipSnapshot leadElectedEvent = eventIt.next();
assertThat(leadElectedEvent.getLeaderRevision()).isNotEmpty();
}
@Test(timeout = 30_000)
public void testBrokenConnection() {
Iterator<ClusterMembershipSnapshot> eventIt = subscribeAndDiscardFirstSnapshot();
serviceStub.breakConnection();
ClusterMembershipSnapshot newSnapshot = eventIt.next();
assertThat(newSnapshot).isNotNull();
assertThat(newSnapshot.getMemberRevisions()).hasSize(3);
}
@Test(timeout = 30_000)
public void testReconnectOnStreamOnComplete() {
Iterator<ClusterMembershipSnapshot> eventIt = subscribeAndDiscardFirstSnapshot();
serviceStub.completeEventStream();
ClusterMembershipSnapshot newSnapshot = eventIt.next();
assertThat(newSnapshot).isNotNull();
assertThat(newSnapshot.getMemberRevisions()).hasSize(3);
}
@Test
public void testWrongMemberIsRejected() throws IOException {
setupServerAndResolver(member -> ClusterMemberVerifierResult.invalid("wrong member"));
await().until(() -> resolver.getRejectedMemberError().equals("wrong member"));
}
private Iterator<ClusterMembershipSnapshot> subscribeAndDiscardFirstSnapshot() {
// Subscribe and consume first snapshot
Iterator<ClusterMembershipSnapshot> eventIt = resolver.resolve().toIterable().iterator();
eventIt.next();
return eventIt;
}
private static ClusterMembershipRevision newMember(int idx) {
return ClusterMembershipRevision.newBuilder()
.setCurrent(ClusterMember.newBuilder()
.setMemberId("member" + idx)
.addAddresses(com.netflix.titus.grpc.protogen.ClusterMemberAddress.newBuilder()
.setIpAddress(IP_PREFIX + idx)
)
.setLeadershipState(ClusterMember.LeadershipState.NonLeader
)
)
.build();
}
}
| 9,798 |
0 | Create_ds/titus-control-plane/titus-common-client/src/main/java/com/netflix/titus/client | Create_ds/titus-control-plane/titus-common-client/src/main/java/com/netflix/titus/client/clustermembership/ClusterMembershipClientMetrics.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.client.clustermembership;
/**
* Common metric constants.
*/
public final class ClusterMembershipClientMetrics {
public static final String CLUSTER_MEMBERSHIP_CLIENT_METRICS_ROOT = "titus.clusterMembership.client.";
}
| 9,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.