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-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager/JobManagerDataReplicationModule.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.jobmanager;
import javax.inject.Named;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.netflix.archaius.ConfigProxyFactory;
import com.netflix.titus.api.jobmanager.service.ReadOnlyJobOperations;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.runtime.connector.jobmanager.replicator.JobDataReplicatorProvider;
import com.netflix.titus.runtime.connector.jobmanager.snapshot.JobSnapshotFactory;
public class JobManagerDataReplicationModule extends AbstractModule {
@Override
protected void configure() {
bind(JobDataReplicator.class).toProvider(JobDataReplicatorProvider.class);
bind(ReadOnlyJobOperations.class).to(CachedReadOnlyJobOperations.class);
}
@Provides
@Singleton
public JobConnectorConfiguration getJobDataReplicatorConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(JobConnectorConfiguration.class);
}
@Provides
@Singleton
public JobDataReplicatorProvider getJobDataReplicatorProvider(JobConnectorConfiguration configuration,
JobManagementClient client,
@Named(JobManagerConnectorModule.KEEP_ALIVE_ENABLED)
JobManagementClient keepAliveEnabledClient,
JobSnapshotFactory jobSnapshotFactory,
TitusRuntime titusRuntime) {
return new JobDataReplicatorProvider(
configuration,
configuration.isKeepAliveReplicatedStreamEnabled() ? keepAliveEnabledClient : client,
jobSnapshotFactory,
titusRuntime
);
}
}
| 1,200 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager/snapshot/JobSnapshotFactory.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.jobmanager.snapshot;
import java.util.Map;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.Task;
public interface JobSnapshotFactory {
JobSnapshot newSnapshot(Map<String, Job<?>> jobsById, Map<String, Map<String, Task>> tasksByJobId);
}
| 1,201 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager/snapshot/JobSnapshotFactories.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.jobmanager.snapshot;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.common.runtime.TitusRuntime;
public final class JobSnapshotFactories {
/**
* Default {@link JobSnapshotFactory} throws an exception if inconsistent state is detected.
* Use {@link #newDefault(boolean, boolean, Consumer, TitusRuntime)} to change this behavior.
*/
public static JobSnapshotFactory newDefault(TitusRuntime titusRuntime) {
return new PCollectionJobSnapshotFactory(
false,
false,
message -> {
},
titusRuntime
);
}
/**
* Returns empty snapshot built using {@link #newDefault(TitusRuntime)}.
*/
public static JobSnapshot newDefaultEmptySnapshot(TitusRuntime titusRuntime) {
return newDefault(titusRuntime).newSnapshot(Collections.emptyMap(), Collections.emptyMap());
}
public static JobSnapshotFactory newDefault(boolean autoFixInconsistencies,
boolean archiveMode,
Consumer<String> inconsistentDataListener,
TitusRuntime titusRuntime) {
return new PCollectionJobSnapshotFactory(autoFixInconsistencies, archiveMode, inconsistentDataListener, titusRuntime);
}
private static class PCollectionJobSnapshotFactory implements JobSnapshotFactory {
private final boolean autoFixInconsistencies;
private final boolean archiveMode;
private final Consumer<String> inconsistentDataListener;
private final TitusRuntime titusRuntime;
private PCollectionJobSnapshotFactory(boolean autoFixInconsistencies,
boolean archiveMode,
Consumer<String> inconsistentDataListener,
TitusRuntime titusRuntime) {
this.autoFixInconsistencies = autoFixInconsistencies;
this.archiveMode = archiveMode;
this.inconsistentDataListener = inconsistentDataListener;
this.titusRuntime = titusRuntime;
}
@Override
public JobSnapshot newSnapshot(Map<String, Job<?>> jobsById, Map<String, Map<String, Task>> tasksByJobId) {
return PCollectionJobSnapshot.newInstance(
UUID.randomUUID().toString(),
jobsById,
tasksByJobId,
autoFixInconsistencies,
archiveMode,
inconsistentDataListener,
titusRuntime
);
}
}
}
| 1,202 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager/snapshot/CachedJob.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.jobmanager.snapshot;
import java.util.Map;
import java.util.Optional;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.tuple.Pair;
import org.pcollections.PMap;
abstract class CachedJob {
protected final Job<?> job;
protected final PMap<String, Task> tasks;
protected final Pair<Job<?>, Map<String, Task>> jobTasksPair;
protected final TitusRuntime titusRuntime;
protected CachedJob(Job<?> job, PMap<String, Task> tasks, TitusRuntime titusRuntime) {
this.job = job;
this.tasks = tasks;
this.jobTasksPair = Pair.of(job, tasks);
this.titusRuntime = titusRuntime;
}
public Job<?> getJob() {
return job;
}
public PMap<String, Task> getTasks() {
return tasks;
}
public Pair<Job<?>, Map<String, Task>> getJobTasksPair() {
return jobTasksPair;
}
public abstract Optional<JobSnapshot> updateJob(PCollectionJobSnapshot snapshot, Job<?> job);
public abstract Optional<JobSnapshot> updateTask(PCollectionJobSnapshot snapshot, Task task);
public abstract Optional<JobSnapshot> removeJob(PCollectionJobSnapshot snapshot, Job<?> job);
public abstract Optional<JobSnapshot> removeTask(PCollectionJobSnapshot snapshot, Task task);
public static CachedJob newInstance(Job<?> job, PMap<String, Task> tasks, boolean archiveMode, TitusRuntime titusRuntime) {
if (JobFunctions.isServiceJob(job)) {
return CachedServiceJob.newServiceInstance(job, tasks, archiveMode, titusRuntime);
}
int size = JobFunctions.getJobDesiredSize(job);
if (size == 1) {
return CachedBatchJobWithOneTask.newBatchInstance((Job<BatchJobExt>) job, tasks, titusRuntime);
}
return CachedBatchJob.newBatchInstance((Job<BatchJobExt>) job, tasks, titusRuntime);
}
}
| 1,203 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager/snapshot/CachedServiceJob.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.jobmanager.snapshot;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
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.common.runtime.TitusRuntime;
import org.pcollections.HashTreePMap;
import org.pcollections.PMap;
/**
* In non-archive mode, {@link CachedServiceJob} stores only not-finished tasks, as we cannot distinguish
* finished/not-replaced from finished/scaled down.
*/
class CachedServiceJob extends CachedJob {
private final boolean archiveMode;
CachedServiceJob(Job<?> job, PMap<String, Task> tasks, boolean archiveMode, TitusRuntime titusRuntime) {
super(job, tasks, titusRuntime);
this.archiveMode = archiveMode;
}
@Override
public Optional<JobSnapshot> updateJob(PCollectionJobSnapshot snapshot, Job<?> updatedJob) {
if (updatedJob == job) {
return Optional.empty();
}
CachedServiceJob update = new CachedServiceJob(updatedJob, tasks, archiveMode, titusRuntime);
return Optional.ofNullable(snapshot.newSnapshot(
snapshot.cachedJobsById.plus(job.getId(), update),
snapshot.jobsById.plus(job.getId(), updatedJob),
snapshot.taskById
));
}
@Override
public Optional<JobSnapshot> updateTask(PCollectionJobSnapshot snapshot, Task updatedTask) {
String taskId = updatedTask.getId();
Task currentTaskVersion = tasks.get(taskId);
if (!archiveMode && updatedTask.getStatus().getState() == TaskState.Finished) {
if (currentTaskVersion == null) {
return Optional.empty();
}
return removeTask(snapshot, updatedTask);
}
if (currentTaskVersion == null) {
CachedServiceJob update = new CachedServiceJob(job, tasks.plus(taskId, updatedTask), archiveMode, titusRuntime);
return Optional.ofNullable(snapshot.newSnapshot(
snapshot.cachedJobsById.plus(job.getId(), update),
snapshot.jobsById,
snapshot.taskById.plus(taskId, updatedTask)
));
}
// This task collides with another one
if (updatedTask.getVersion().getTimestamp() < currentTaskVersion.getVersion().getTimestamp()) {
// It is an earlier version. Ignore it.
titusRuntime.getCodeInvariants().inconsistent(
"Received earlier version of a task: current=%s, received=%s",
currentTaskVersion.getVersion().getTimestamp(), updatedTask.getVersion().getTimestamp()
);
return Optional.empty();
}
CachedServiceJob update = new CachedServiceJob(
job,
tasks.plus(taskId, updatedTask),
archiveMode, titusRuntime
);
return Optional.ofNullable(snapshot.newSnapshot(
snapshot.cachedJobsById.plus(job.getId(), update),
snapshot.jobsById,
snapshot.taskById.plus(taskId, updatedTask)
));
}
@Override
public Optional<JobSnapshot> removeJob(PCollectionJobSnapshot snapshot, Job<?> job) {
return Optional.of(snapshot.newSnapshot(
snapshot.cachedJobsById.minus(job.getId()),
snapshot.jobsById.minus(job.getId()),
snapshot.taskById.minusAll(tasks.keySet())
));
}
@Override
public Optional<JobSnapshot> removeTask(PCollectionJobSnapshot snapshot, Task task) {
if (!tasks.containsKey(task.getId())) {
return Optional.empty();
}
CachedServiceJob update = new CachedServiceJob(job, tasks.minus(task.getId()), archiveMode, titusRuntime);
return Optional.ofNullable(snapshot.newSnapshot(
snapshot.cachedJobsById.plus(job.getId(), update),
snapshot.jobsById,
snapshot.taskById.minus(task.getId())
));
}
public static CachedJob newServiceInstance(Job<?> job, PMap<String, Task> tasks, boolean archiveMode, TitusRuntime titusRuntime) {
// Filter out finished tasks if the archive mode is not enabled.
Map<String, Task> filtered;
if (archiveMode) {
filtered = tasks;
} else {
filtered = new HashMap<>();
tasks.forEach((taskId, task) -> {
if (task.getStatus().getState() != TaskState.Finished) {
filtered.put(taskId, task);
}
});
}
return new CachedServiceJob(job, HashTreePMap.from(filtered), archiveMode, titusRuntime);
}
}
| 1,204 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager/snapshot/CachedBatchJobWithOneTask.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.jobmanager.snapshot;
import java.util.Optional;
import com.google.common.base.Preconditions;
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.ext.BatchJobExt;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.CollectionsExt;
import org.pcollections.HashTreePMap;
import org.pcollections.PMap;
/**
* Most of the batch jobs have size 1. This is an optimized implementation of {@link CachedJob} for this particular case.
*/
public class CachedBatchJobWithOneTask extends CachedJob {
private final Task task;
protected CachedBatchJobWithOneTask(Job<?> job, Task task, TitusRuntime titusRuntime) {
super(job, task == null ? HashTreePMap.empty() : HashTreePMap.singleton(task.getId(), task), titusRuntime);
this.task = task;
}
@Override
public Optional<JobSnapshot> updateJob(PCollectionJobSnapshot snapshot, Job<?> updatedJob) {
if (updatedJob == job) {
return Optional.empty();
}
CachedBatchJobWithOneTask update = new CachedBatchJobWithOneTask(updatedJob, task, titusRuntime);
return Optional.ofNullable(snapshot.newSnapshot(
snapshot.cachedJobsById.plus(job.getId(), update),
snapshot.jobsById.plus(job.getId(), updatedJob),
snapshot.taskById
));
}
@Override
public Optional<JobSnapshot> updateTask(PCollectionJobSnapshot snapshot, Task updatedTask) {
if (task == null) {
CachedBatchJobWithOneTask update = new CachedBatchJobWithOneTask(job, updatedTask, titusRuntime);
return Optional.of(snapshot.newSnapshot(
snapshot.cachedJobsById.plus(job.getId(), update),
snapshot.jobsById,
snapshot.taskById.plus(updatedTask.getId(), updatedTask)
));
}
// This task collides with another one
if (updatedTask.getVersion().getTimestamp() < task.getVersion().getTimestamp()) {
// It is an earlier version. Ignore it.
titusRuntime.getCodeInvariants().inconsistent(
"Received earlier version of a task: current=%s, received=%s",
task.getVersion().getTimestamp(), updatedTask.getVersion().getTimestamp()
);
return Optional.empty();
}
// Replace the old version.
CachedBatchJobWithOneTask update = new CachedBatchJobWithOneTask(job, updatedTask, titusRuntime);
return Optional.of(snapshot.newSnapshot(
snapshot.cachedJobsById.plus(job.getId(), update),
snapshot.jobsById,
snapshot.taskById.minus(task.getId()).plus(updatedTask.getId(), updatedTask)
));
}
@Override
public Optional<JobSnapshot> removeJob(PCollectionJobSnapshot snapshot, Job<?> job) {
return Optional.of(snapshot.newSnapshot(
snapshot.cachedJobsById.minus(job.getId()),
snapshot.jobsById.minus(job.getId()),
task == null ? snapshot.taskById : snapshot.taskById.minus(task.getId())
));
}
/**
* We never remove finished batch tasks from a job unless when they are replaced with another one. The latter
* case is handled by {@link #updateTask(PCollectionJobSnapshot, Task)}.
*/
@Override
public Optional<JobSnapshot> removeTask(PCollectionJobSnapshot snapshot, Task task) {
return Optional.empty();
}
public static CachedJob newBatchInstance(Job<BatchJobExt> job, PMap<String, Task> tasks, TitusRuntime titusRuntime) {
int size = job.getJobDescriptor().getExtensions().getSize();
Preconditions.checkState(size == 1, "Expected batch job of size 1");
Task task = null;
if (tasks.size() == 1) {
task = CollectionsExt.first(tasks.values());
} else if (tasks.size() > 1) {
// We have to find the latest version.
for (Task next : tasks.values()) {
if (task == null) {
task = next;
} else if (task.getVersion().getTimestamp() < next.getVersion().getTimestamp()) {
task = next;
}
}
}
return new CachedBatchJobWithOneTask(job, task, titusRuntime);
}
}
| 1,205 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager/snapshot/PCollectionJobSnapshot.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.jobmanager.snapshot;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import com.google.common.base.Preconditions;
import com.netflix.titus.api.jobmanager.TaskAttributes;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobState;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.tuple.Pair;
import org.pcollections.HashTreePMap;
import org.pcollections.PMap;
/**
* TODO Finished tasks are not handled correctly for batch jobs (they are in active data set until replaced).
*/
public class PCollectionJobSnapshot extends JobSnapshot {
final PMap<String, CachedJob> cachedJobsById;
final PMap<String, Job<?>> jobsById;
final PMap<String, Task> taskById;
private final boolean autoFixInconsistencies;
private final boolean archiveMode;
private final Consumer<String> inconsistentDataListener;
private final TitusRuntime titusRuntime;
private final String signature;
// Deprecated values computed lazily
private volatile List<Job<?>> allJobs;
private final Lock allJobsLock = new ReentrantLock();
private volatile List<Task> allTasks;
private final Lock allTasksLock = new ReentrantLock();
private volatile List<Pair<Job<?>, Map<String, Task>>> allJobTaskPairs;
private final Lock allJobTaskPairsLock = new ReentrantLock();
public static PCollectionJobSnapshot newInstance(String snapshotId,
Map<String, Job<?>> jobsById,
Map<String, Map<String, Task>> tasksByJobId,
boolean autoFixInconsistencies,
boolean archiveMode,
Consumer<String> inconsistentDataListener,
TitusRuntime titusRuntime) {
Map<String, Task> taskById = new HashMap<>();
tasksByJobId.forEach((jobId, tasks) -> taskById.putAll(tasks));
Map<String, CachedJob> cachedJobsById = new HashMap<>();
jobsById.forEach((jobId, job) -> {
Map<String, Task> taskMap = tasksByJobId.get(jobId);
PMap<String, Task> tasksPMap = CollectionsExt.isNullOrEmpty(taskMap) ? HashTreePMap.empty() : HashTreePMap.from(taskMap);
cachedJobsById.put(jobId, CachedJob.newInstance(job, tasksPMap, archiveMode, titusRuntime));
});
return new PCollectionJobSnapshot(
snapshotId,
HashTreePMap.from(cachedJobsById),
HashTreePMap.from(jobsById),
HashTreePMap.from(taskById),
autoFixInconsistencies,
archiveMode,
inconsistentDataListener,
titusRuntime
);
}
private PCollectionJobSnapshot(String snapshotId,
PMap<String, CachedJob> cachedJobsById,
PMap<String, Job<?>> jobsById,
PMap<String, Task> taskById,
boolean autoFixInconsistencies,
boolean archiveMode,
Consumer<String> inconsistentDataListener,
TitusRuntime titusRuntime) {
super(snapshotId);
this.cachedJobsById = cachedJobsById;
this.jobsById = jobsById;
this.taskById = taskById;
this.autoFixInconsistencies = autoFixInconsistencies;
this.archiveMode = archiveMode;
this.inconsistentDataListener = inconsistentDataListener;
this.titusRuntime = titusRuntime;
this.signature = computeSignature();
}
public Map<String, Job<?>> getJobMap() {
return jobsById;
}
public List<Job<?>> getJobs() {
if (allJobs != null) {
return allJobs;
}
allJobsLock.lock();
try {
if (allJobs != null) {
return allJobs;
}
this.allJobs = Collections.unmodifiableList(new ArrayList<>(jobsById.values()));
} finally {
allJobsLock.unlock();
}
return allJobs;
}
public Optional<Job<?>> findJob(String jobId) {
return Optional.ofNullable(jobsById.get(jobId));
}
@Override
public Map<String, Task> getTaskMap() {
return taskById;
}
public List<Task> getTasks() {
if (allTasks != null) {
return allTasks;
}
allTasksLock.lock();
try {
if (allTasks != null) {
return allTasks;
}
this.allTasks = Collections.unmodifiableList(new ArrayList<>(taskById.values()));
} finally {
allTasksLock.unlock();
}
return allTasks;
}
@Override
public Map<String, Task> getTasks(String jobId) {
CachedJob entry = cachedJobsById.get(jobId);
return entry == null ? HashTreePMap.empty() : entry.getTasks();
}
@Override
public List<Pair<Job<?>, Map<String, Task>>> getJobsAndTasks() {
if (allJobTaskPairs != null) {
return allJobTaskPairs;
}
allJobTaskPairsLock.lock();
try {
if (allJobTaskPairs != null) {
return allJobTaskPairs;
}
List<Pair<Job<?>, Map<String, Task>>> acc = new ArrayList<>();
cachedJobsById.forEach((jobId, entry) -> acc.add(entry.getJobTasksPair()));
this.allJobTaskPairs = acc;
} finally {
allJobTaskPairsLock.unlock();
}
return allJobTaskPairs;
}
public Optional<Pair<Job<?>, Task>> findTaskById(String taskId) {
Task task = taskById.get(taskId);
if (task == null) {
return Optional.empty();
}
Job<?> job = jobsById.get(task.getJobId());
Preconditions.checkState(job != null); // if this happens there is a bug
return Optional.of(Pair.of(job, task));
}
@Override
public Optional<JobSnapshot> updateJob(Job<?> job) {
Job<?> previous = jobsById.get(job.getId());
CachedJob cachedJob = cachedJobsById.get(job.getId());
// First time seen
if (previous == null) {
if (!archiveMode && job.getStatus().getState() == JobState.Finished) {
return Optional.empty();
}
return Optional.of(newSnapshot(
cachedJobsById.plus(job.getId(), CachedJob.newInstance(job, HashTreePMap.empty(), archiveMode, titusRuntime)),
jobsById.plus(job.getId(), job),
taskById
));
}
// Update
if (!archiveMode && job.getStatus().getState() == JobState.Finished) {
return cachedJob.removeJob(this, job);
}
return cachedJob.updateJob(this, job);
}
@Override
public Optional<JobSnapshot> removeArchivedJob(Job<?> job) {
CachedJob cachedJob = cachedJobsById.get(job.getId());
if (cachedJob == null) {
return Optional.empty();
}
return cachedJob.removeJob(this, job);
}
@Override
public Optional<JobSnapshot> updateTask(Task task, boolean moved) {
String jobId = task.getJobId();
CachedJob cachedJob = cachedJobsById.get(jobId);
if (cachedJob == null) { // Inconsistent data
inconsistentData("job %s not found for task %s", jobId, task.getId());
return Optional.empty();
}
if (!moved) {
return cachedJob.updateTask(this, task);
}
// Task moved so we have to remove it from the previous job
String jobIdIndexToUpdate = task.getTaskContext().get(TaskAttributes.TASK_ATTRIBUTES_MOVED_FROM_JOB);
if (jobIdIndexToUpdate == null) {
inconsistentData("moved task %s has no attribute with the original job id", task.getId());
return cachedJob.updateTask(this, task);
}
CachedJob previousCachedJob = cachedJobsById.get(jobIdIndexToUpdate);
PCollectionJobSnapshot currentSnapshot = (PCollectionJobSnapshot) previousCachedJob.removeTask(this, task).orElse(null);
return currentSnapshot == null
? cachedJob.updateTask(this, task)
: Optional.of(cachedJob.updateTask(currentSnapshot, task).orElse(currentSnapshot));
}
@Override
public Optional<JobSnapshot> removeArchivedTask(Task task) {
String jobId = task.getJobId();
CachedJob cachedJob = cachedJobsById.get(jobId);
if (cachedJob == null) { // Inconsistent data
inconsistentData("job %s not found for task %s", jobId, task.getId());
return Optional.empty();
}
return cachedJob.removeTask(this, task);
}
JobSnapshot newSnapshot(PMap<String, CachedJob> cachedJobsById,
PMap<String, Job<?>> jobsById,
PMap<String, Task> taskById) {
return new PCollectionJobSnapshot(
this.snapshotId,
cachedJobsById,
jobsById,
taskById,
autoFixInconsistencies,
archiveMode,
inconsistentDataListener,
titusRuntime
);
}
private void inconsistentData(String message, Object... args) {
String formattedMessage = String.format(message, args);
if (inconsistentDataListener != null) {
try {
inconsistentDataListener.accept(formattedMessage);
} catch (Exception ignore) {
}
}
if (!autoFixInconsistencies) {
throw new IllegalStateException(formattedMessage);
}
}
@Override
public String toSummaryString() {
return signature;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("JobSnapshot{snapshotId=").append(snapshotId).append(", jobs=");
jobsById.forEach((id, job) -> {
CachedJob entry = cachedJobsById.get(id);
int tasksCount = entry == null ? 0 : entry.getTasks().size();
sb.append(id).append('=').append(tasksCount).append(',');
});
sb.setLength(sb.length() - 1);
return sb.append('}').toString();
}
private String computeSignature() {
return "JobSnapshot{snapshotId=" + snapshotId +
", jobs=" + jobsById.size() +
", tasks=" + taskById.size() +
"}";
}
}
| 1,206 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager/snapshot/JobSnapshot.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.jobmanager.snapshot;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.runtime.connector.common.replicator.ReplicatedSnapshot;
/**
* TODO Handle moved tasks
* TODO Finished tasks are not handled correctly for batch jobs (they are in active data set until replaced).
*/
public abstract class JobSnapshot extends ReplicatedSnapshot {
protected final String snapshotId;
protected JobSnapshot(String snapshotId) {
this.snapshotId = snapshotId;
}
public String getSnapshotId() {
return snapshotId;
}
public abstract Map<String, Job<?>> getJobMap();
/**
* This value is expensive to compute on each update. {@link PCollectionJobSnapshot} computes it lazily to avoid
* the overhead. Consider using {@link #getJobMap()}.
*/
@Deprecated
public abstract List<Job<?>> getJobs();
public abstract Optional<Job<?>> findJob(String jobId);
public abstract Map<String, Task> getTaskMap();
/**
* This value is expensive to compute on each update. {@link PCollectionJobSnapshot} computes it lazily to avoid
* the overhead. Consider using {@link #getTaskMap()}.
*/
@Deprecated
public abstract List<Task> getTasks();
public abstract Map<String, Task> getTasks(String jobId);
/**
* This value is expensive to compute on each update. {@link PCollectionJobSnapshot} computes it lazily to avoid
* the overhead. Consider using other methods.
*/
@Deprecated
public abstract List<Pair<Job<?>, Map<String, Task>>> getJobsAndTasks();
public abstract Optional<Pair<Job<?>, Task>> findTaskById(String taskId);
public abstract Optional<JobSnapshot> updateJob(Job<?> job);
public abstract Optional<JobSnapshot> removeArchivedJob(Job<?> job);
public abstract Optional<JobSnapshot> updateTask(Task task, boolean moved);
public abstract Optional<JobSnapshot> removeArchivedTask(Task task);
}
| 1,207 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager/snapshot/CachedBatchJob.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.jobmanager.snapshot;
import java.util.Optional;
import com.netflix.titus.api.jobmanager.TaskAttributes;
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.ext.BatchJobExt;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.StringExt;
import org.pcollections.PMap;
import org.pcollections.PVector;
import org.pcollections.TreePVector;
class CachedBatchJob extends CachedJob {
private final PVector<Task> tasksByIndex;
CachedBatchJob(Job<?> job, PMap<String, Task> tasks, PVector<Task> tasksByIndex, TitusRuntime titusRuntime) {
super(job, tasks, titusRuntime);
this.tasksByIndex = tasksByIndex;
}
@Override
public Optional<JobSnapshot> updateJob(PCollectionJobSnapshot snapshot, Job<?> updatedJob) {
if (updatedJob == job) {
return Optional.empty();
}
CachedBatchJob update = new CachedBatchJob(updatedJob, tasks, tasksByIndex, titusRuntime);
return Optional.ofNullable(snapshot.newSnapshot(
snapshot.cachedJobsById.plus(job.getId(), update),
snapshot.jobsById.plus(job.getId(), updatedJob),
snapshot.taskById
));
}
@Override
public Optional<JobSnapshot> updateTask(PCollectionJobSnapshot snapshot, Task task) {
int index = indexOf(task, tasksByIndex.size(), titusRuntime);
if (index < 0) {
return Optional.empty();
}
Task current = tasksByIndex.get(index);
if (current == null) {
CachedBatchJob update = new CachedBatchJob(
job,
tasks.plus(task.getId(), task),
tasksByIndex.with(index, task),
titusRuntime
);
return Optional.ofNullable(snapshot.newSnapshot(
snapshot.cachedJobsById.plus(job.getId(), update),
snapshot.jobsById,
snapshot.taskById.plus(task.getId(), task)
));
}
// This task collides with another one
if (task.getVersion().getTimestamp() < current.getVersion().getTimestamp()) {
// It is an earlier version. Ignore it.
titusRuntime.getCodeInvariants().inconsistent(
"Received earlier version of a task: current=%s, received=%s",
current.getVersion().getTimestamp(), task.getVersion().getTimestamp()
);
return Optional.empty();
}
// Replace the old version.
CachedBatchJob update = new CachedBatchJob(
job,
tasks.minus(current.getId()).plus(task.getId(), task),
tasksByIndex.with(index, task),
titusRuntime
);
return Optional.of(snapshot.newSnapshot(
snapshot.cachedJobsById.plus(job.getId(), update),
snapshot.jobsById,
snapshot.taskById.minus(current.getId()).plus(task.getId(), task)
));
}
@Override
public Optional<JobSnapshot> removeJob(PCollectionJobSnapshot snapshot, Job<?> job) {
return Optional.of(snapshot.newSnapshot(
snapshot.cachedJobsById.minus(job.getId()),
snapshot.jobsById.minus(job.getId()),
snapshot.taskById.minusAll(tasks.keySet())
));
}
/**
* We never remove finished batch tasks from a job unless when they are replaced with another one. The latter
* case is handled by {@link #updateTask(PCollectionJobSnapshot, Task)}.
*/
@Override
public Optional<JobSnapshot> removeTask(PCollectionJobSnapshot snapshot, Task task) {
return Optional.empty();
}
public static CachedJob newBatchInstance(Job<BatchJobExt> job, PMap<String, Task> tasks, TitusRuntime titusRuntime) {
int size = job.getJobDescriptor().getExtensions().getSize();
PVector<Task> tasksByIndex = TreePVector.empty();
for (int i = 0; i < size; i++) {
tasksByIndex = tasksByIndex.plus(null);
}
for (Task task : tasks.values()) {
int index = indexOf(task, size, titusRuntime);
if (index >= 0) {
tasksByIndex = tasksByIndex.with(index, task);
}
}
return new CachedBatchJob(job, tasks, tasksByIndex, titusRuntime);
}
static int indexOf(Task task, int jobSize, TitusRuntime titusRuntime) {
String indexStr = task.getTaskContext().get(TaskAttributes.TASK_ATTRIBUTES_TASK_INDEX);
if (StringExt.isEmpty(indexStr)) {
titusRuntime.getCodeInvariants().inconsistent(
"Batch task without index. Dropped from cache: taskId=%s", task.getId()
);
return -1;
}
int index;
try {
index = Integer.parseInt(indexStr);
} catch (Exception e) {
titusRuntime.getCodeInvariants().inconsistent(
"Batch task with invalid index. Dropped from cache: taskId=%s, index=%s", task.getId(), indexStr
);
return -1;
}
if (index < 0 || index >= jobSize) {
titusRuntime.getCodeInvariants().inconsistent(
"Batch task with invalid index. Dropped from cache: taskId=%s, index=%s", task.getId(), indexStr
);
return -1;
}
return index;
}
}
| 1,208 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager/replicator/GrpcJobReplicatorEventStream.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.jobmanager.replicator;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobState;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.api.jobmanager.model.job.event.JobKeepAliveEvent;
import com.netflix.titus.api.jobmanager.model.job.event.JobManagerEvent;
import com.netflix.titus.api.jobmanager.model.job.event.JobUpdateEvent;
import com.netflix.titus.api.jobmanager.model.job.event.TaskUpdateEvent;
import com.netflix.titus.api.jobmanager.service.JobManagerConstants;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.ExceptionExt;
import com.netflix.titus.common.util.spectator.SpectatorExt;
import com.netflix.titus.common.util.spectator.ValueRangeCounter;
import com.netflix.titus.runtime.connector.common.replicator.AbstractReplicatorEventStream;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicatorMetrics;
import com.netflix.titus.runtime.connector.common.replicator.ReplicatorEvent;
import com.netflix.titus.runtime.connector.jobmanager.JobConnectorConfiguration;
import com.netflix.titus.runtime.connector.jobmanager.JobManagementClient;
import com.netflix.titus.runtime.connector.jobmanager.RemoteJobManagementClientWithKeepAlive;
import com.netflix.titus.runtime.connector.jobmanager.snapshot.JobSnapshot;
import com.netflix.titus.runtime.connector.jobmanager.snapshot.JobSnapshotFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.Disposable;
import reactor.core.publisher.ConnectableFlux;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
public class GrpcJobReplicatorEventStream extends AbstractReplicatorEventStream<JobSnapshot, JobManagerEvent<?>> {
private static final Logger logger = LoggerFactory.getLogger(GrpcJobReplicatorEventStream.class);
private static final String METRICS_ROOT = "titus.grpcJobReplicatorEventStream.";
private static final long[] LEVELS = new long[]{1, 10, 50, 100, 200, 500, 1_000, 2_000, 5_000, 10_000, 20_000, 60_000};
private final JobManagementClient client;
private final Map<String, String> filteringCriteria;
private final JobSnapshotFactory jobSnapshotFactory;
private final JobConnectorConfiguration configuration;
// We read this property on startup as in some places it cannot be changed dynamically.
private final boolean keepAliveEnabled;
private final ValueRangeCounter eventProcessingLatencies;
private final AtomicInteger subscriptionCounter = new AtomicInteger();
public GrpcJobReplicatorEventStream(JobManagementClient client,
JobSnapshotFactory jobSnapshotFactory,
JobConnectorConfiguration configuration,
DataReplicatorMetrics metrics,
TitusRuntime titusRuntime,
Scheduler scheduler) {
this(client, Collections.emptyMap(), jobSnapshotFactory, configuration, metrics, titusRuntime, scheduler);
}
public GrpcJobReplicatorEventStream(JobManagementClient client,
Map<String, String> filteringCriteria,
JobSnapshotFactory jobSnapshotFactory,
JobConnectorConfiguration configuration,
DataReplicatorMetrics metrics,
TitusRuntime titusRuntime,
Scheduler scheduler) {
super(client instanceof RemoteJobManagementClientWithKeepAlive, JobManagerEvent.keepAliveEvent(-1), metrics, titusRuntime, scheduler);
this.client = client;
this.filteringCriteria = filteringCriteria;
this.jobSnapshotFactory = jobSnapshotFactory;
this.configuration = configuration;
this.keepAliveEnabled = configuration.isKeepAliveReplicatedStreamEnabled();
PolledMeter.using(titusRuntime.getRegistry()).withName(METRICS_ROOT + "activeSubscriptions").monitorValue(subscriptionCounter);
this.eventProcessingLatencies = SpectatorExt.newValueRangeCounterSortable(
titusRuntime.getRegistry().createId(METRICS_ROOT + "processingLatency"),
LEVELS,
titusRuntime.getRegistry()
);
}
@Override
protected Flux<ReplicatorEvent<JobSnapshot, JobManagerEvent<?>>> newConnection() {
return Flux
.<ReplicatorEvent<JobSnapshot, JobManagerEvent<?>>>create(sink -> {
CacheUpdater cacheUpdater = new CacheUpdater(jobSnapshotFactory, keepAliveEnabled, titusRuntime);
logger.info("Connecting to the job event stream (filteringCriteria={})...", filteringCriteria);
ConnectableFlux<JobManagerEvent<?>> connectableStream = client.observeJobs(filteringCriteria).publish();
Flux<JobManagerEvent<?>> augmentedStream;
if (configuration.isConnectionTimeoutEnabled()) {
augmentedStream = Flux.merge(
connectableStream.take(1).timeout(Duration.ofMillis(configuration.getConnectionTimeoutMs())).ignoreElements()
.onErrorMap(TimeoutException.class, error ->
new TimeoutException(String.format("No event received from stream in %sms", configuration.getConnectionTimeoutMs()))
),
connectableStream
);
} else {
augmentedStream = connectableStream;
}
Disposable disposable = augmentedStream.subscribe(
jobEvent -> {
long started = titusRuntime.getClock().wallTime();
try {
cacheUpdater.onEvent(jobEvent).ifPresent(sink::next);
eventProcessingLatencies.recordLevel(titusRuntime.getClock().wallTime() - started);
} catch (Exception e) {
// Throw error to force the cache reconnect.
logger.warn("Unexpected error when handling the job change notification: {}", jobEvent, e);
ExceptionExt.silent(() -> sink.error(e));
}
},
e -> ExceptionExt.silent(() -> sink.error(e)),
() -> ExceptionExt.silent(sink::complete)
);
sink.onDispose(disposable);
connectableStream.connect();
})
.doOnSubscribe(subscription -> subscriptionCounter.incrementAndGet())
.doFinally(signal -> subscriptionCounter.decrementAndGet());
}
@VisibleForTesting
static class CacheUpdater {
private final JobSnapshotFactory jobSnapshotFactory;
private final boolean archiveMode;
private final TitusRuntime titusRuntime;
private final long startTime;
private final List<JobManagerEvent<?>> snapshotEvents = new ArrayList<>();
private final AtomicReference<JobSnapshot> lastJobSnapshotRef = new AtomicReference<>();
private final AtomicLong lastKeepAliveTimestamp;
CacheUpdater(JobSnapshotFactory jobSnapshotFactory, boolean archiveMode, TitusRuntime titusRuntime) {
this.jobSnapshotFactory = jobSnapshotFactory;
this.archiveMode = archiveMode;
this.titusRuntime = titusRuntime;
this.startTime = titusRuntime.getClock().wallTime();
this.lastKeepAliveTimestamp = new AtomicLong(startTime);
}
Optional<ReplicatorEvent<JobSnapshot, JobManagerEvent<?>>> onEvent(JobManagerEvent<?> event) {
if (logger.isDebugEnabled()) {
if (event instanceof JobUpdateEvent) {
Job job = ((JobUpdateEvent) event).getCurrent();
logger.debug("Received job update event: jobId={}, state={}, version={}", job.getId(), job.getStatus(), job.getVersion());
} else if (event instanceof TaskUpdateEvent) {
Task task = ((TaskUpdateEvent) event).getCurrent();
logger.debug("Received task update event: taskId={}, state={}, version={}", task.getId(), task.getStatus(), task.getVersion());
} else if (event.equals(JobManagerEvent.snapshotMarker())) {
logger.debug("Received snapshot marker");
} else if (event instanceof JobKeepAliveEvent) {
logger.debug("Received job keep alive event: {}", event);
} else {
logger.debug("Received unrecognized event type: {}", event);
}
}
if (lastJobSnapshotRef.get() != null) {
return processCacheUpdate(event);
}
if (event.equals(JobManagerEvent.snapshotMarker())) {
return Optional.of(buildInitialCache());
}
// Snapshot event. Collect all of them before processing.
if (event instanceof JobUpdateEvent || event instanceof TaskUpdateEvent) {
snapshotEvents.add(event);
}
return Optional.empty();
}
private ReplicatorEvent<JobSnapshot, JobManagerEvent<?>> buildInitialCache() {
Map<String, Job<?>> jobs = new HashMap<>();
Set<String> jobsToRemove = new HashSet<>();
snapshotEvents.forEach(event -> {
if (event instanceof JobUpdateEvent) {
Job<?> job = ((JobUpdateEvent) event).getCurrent();
jobs.put(job.getId(), job);
if (job.getStatus().getState() == JobState.Finished) {
// If archive mode is disabled, we always remove finished jobs immediately.
if (!archiveMode || event.isArchived()) {
jobsToRemove.add(job.getId());
}
}
}
});
// Filter out completed jobs. We could not do it sooner, as the job/task finished state could be proceeded by
// earlier events so we have to collapse all of it.
jobs.keySet().removeAll(jobsToRemove);
Map<String, Task> tasks = new HashMap<>();
Set<String> tasksToRemove = new HashSet<>();
snapshotEvents.forEach(event -> {
if (event instanceof TaskUpdateEvent) {
TaskUpdateEvent taskUpdateEvent = (TaskUpdateEvent) event;
Task task = taskUpdateEvent.getCurrent();
Job<?> taskJob = jobs.get(task.getJobId());
if (taskJob != null) {
tasks.put(task.getId(), task);
if (task.getStatus().getState() == TaskState.Finished) {
// If archive mode is disabled, we cannot make a good decision about a finished task so we have to keep it.
if (archiveMode) {
tasksToRemove.add(task.getId());
}
}
} else {
if (!jobsToRemove.contains(task.getJobId())) {
titusRuntime.getCodeInvariants().inconsistent("Job record not found: jobId=%s, taskId=%s", task.getJobId(), task.getId());
}
}
}
});
tasks.keySet().removeAll(tasksToRemove);
Map<String, Map<String, Task>> tasksByJobId = new HashMap<>();
tasks.forEach((taskId, task) -> tasksByJobId.computeIfAbsent(task.getJobId(), t -> new HashMap<>()).put(task.getId(), task));
JobSnapshot initialSnapshot = jobSnapshotFactory.newSnapshot(jobs, tasksByJobId);
// No longer needed
snapshotEvents.clear();
lastJobSnapshotRef.set(initialSnapshot);
logger.info("Job snapshot loaded: {}", initialSnapshot.toSummaryString());
// Checkpoint timestamp for the cache event, is the time just before establishing the connection.
return new ReplicatorEvent<>(initialSnapshot, JobManagerEvent.snapshotMarker(), titusRuntime.getClock().wallTime(), startTime);
}
private Optional<ReplicatorEvent<JobSnapshot, JobManagerEvent<?>>> processCacheUpdate(JobManagerEvent<?> event) {
JobSnapshot lastSnapshot = lastJobSnapshotRef.get();
if (event instanceof JobKeepAliveEvent) {
JobKeepAliveEvent keepAliveEvent = (JobKeepAliveEvent) event;
lastKeepAliveTimestamp.set(keepAliveEvent.getTimestamp());
return Optional.of(new ReplicatorEvent<>(lastSnapshot, event, titusRuntime.getClock().wallTime(), keepAliveEvent.getTimestamp()));
}
Optional<JobSnapshot> newSnapshot;
JobManagerEvent<?> coreEvent = null;
if (event instanceof JobUpdateEvent) {
JobUpdateEvent jobUpdateEvent = (JobUpdateEvent) event;
Job job = jobUpdateEvent.getCurrent();
logger.debug("Processing job snapshot update event: updatedJobId={}", job.getId());
if (archiveMode && jobUpdateEvent.isArchived()) {
newSnapshot = lastSnapshot.removeArchivedJob(job);
} else {
newSnapshot = lastSnapshot.updateJob(job);
}
coreEvent = toJobCoreEvent(job);
} else if (event instanceof TaskUpdateEvent) {
TaskUpdateEvent taskUpdateEvent = (TaskUpdateEvent) event;
Task task = taskUpdateEvent.getCurrentTask();
logger.debug("Processing job snapshot update event: updatedTaskId={}", task.getId());
Optional<Job<?>> taskJobOpt = lastSnapshot.findJob(task.getJobId());
if (taskJobOpt.isPresent()) {
Job<?> taskJob = taskJobOpt.get();
if (archiveMode && taskUpdateEvent.isArchived()) {
newSnapshot = lastSnapshot.removeArchivedTask(task);
} else {
newSnapshot = lastSnapshot.updateTask(task, taskUpdateEvent.isMovedFromAnotherJob());
}
coreEvent = toTaskCoreEvent(taskJob, task, taskUpdateEvent.isMovedFromAnotherJob());
} else {
titusRuntime.getCodeInvariants().inconsistent("Job record not found: jobId=%s, taskId=%s", task.getJobId(), task.getId());
newSnapshot = Optional.empty();
}
} else {
newSnapshot = Optional.empty();
}
if (newSnapshot.isPresent()) {
lastJobSnapshotRef.set(newSnapshot.get());
return Optional.of(new ReplicatorEvent<>(newSnapshot.get(), coreEvent, titusRuntime.getClock().wallTime(), lastKeepAliveTimestamp.get()));
}
return Optional.empty();
}
private JobManagerEvent<?> toJobCoreEvent(Job newJob) {
return lastJobSnapshotRef.get().findJob(newJob.getId())
.map(previousJob -> JobUpdateEvent.jobChange(newJob, previousJob, JobManagerConstants.GRPC_REPLICATOR_CALL_METADATA))
.orElseGet(() -> JobUpdateEvent.newJob(newJob, JobManagerConstants.GRPC_REPLICATOR_CALL_METADATA));
}
private JobManagerEvent<?> toTaskCoreEvent(Job<?> job, Task newTask, boolean moved) {
if (moved) {
return TaskUpdateEvent.newTaskFromAnotherJob(job, newTask, JobManagerConstants.GRPC_REPLICATOR_CALL_METADATA);
}
return lastJobSnapshotRef.get().findTaskById(newTask.getId())
.map(jobTaskPair -> TaskUpdateEvent.taskChange(job, newTask, jobTaskPair.getRight(), JobManagerConstants.GRPC_REPLICATOR_CALL_METADATA))
.orElseGet(() -> TaskUpdateEvent.newTask(job, newTask, JobManagerConstants.GRPC_REPLICATOR_CALL_METADATA));
}
}
}
| 1,209 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/jobmanager/replicator/JobDataReplicatorProvider.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.jobmanager.replicator;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import com.netflix.titus.api.jobmanager.model.job.event.JobManagerEvent;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.ExceptionExt;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicator;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicatorDelegate;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicatorMetrics;
import com.netflix.titus.runtime.connector.common.replicator.ReplicatorEvent;
import com.netflix.titus.runtime.connector.common.replicator.RetryableReplicatorEventStream;
import com.netflix.titus.runtime.connector.common.replicator.StreamDataReplicator;
import com.netflix.titus.runtime.connector.jobmanager.JobConnectorConfiguration;
import com.netflix.titus.runtime.connector.jobmanager.JobDataReplicator;
import com.netflix.titus.runtime.connector.jobmanager.JobManagementClient;
import com.netflix.titus.runtime.connector.jobmanager.snapshot.JobSnapshot;
import com.netflix.titus.runtime.connector.jobmanager.snapshot.JobSnapshotFactory;
import reactor.core.scheduler.Schedulers;
@Singleton
public class JobDataReplicatorProvider implements Provider<JobDataReplicator> {
private static final String JOB_REPLICATOR = "jobReplicator";
private static final String JOB_REPLICATOR_RETRYABLE_STREAM = "jobReplicatorRetryableStream";
private static final String JOB_REPLICATOR_GRPC_STREAM = "jobReplicatorGrpcStream";
private static final long JOB_BOOTSTRAP_TIMEOUT_MS = 120_000;
private final JobDataReplicatorImpl replicator;
@Inject
public JobDataReplicatorProvider(JobConnectorConfiguration configuration,
JobManagementClient client,
JobSnapshotFactory jobSnapshotFactory,
TitusRuntime titusRuntime) {
this(configuration, client, Collections.emptyMap(), jobSnapshotFactory, titusRuntime);
}
public JobDataReplicatorProvider(JobConnectorConfiguration configuration,
JobManagementClient client,
Map<String, String> filteringCriteria,
JobSnapshotFactory jobSnapshotFactory,
TitusRuntime titusRuntime) {
StreamDataReplicator<JobSnapshot, JobManagerEvent<?>> original = StreamDataReplicator.newStreamDataReplicator(
newReplicatorEventStream(configuration, client, filteringCriteria, jobSnapshotFactory, titusRuntime),
configuration.isKeepAliveReplicatedStreamEnabled(),
new JobDataReplicatorMetrics(JOB_REPLICATOR, configuration, titusRuntime),
titusRuntime
).blockFirst(Duration.ofMillis(JOB_BOOTSTRAP_TIMEOUT_MS));
this.replicator = new JobDataReplicatorImpl(original);
}
@PreDestroy
public void shutdown() {
ExceptionExt.silent(replicator::close);
}
@Override
public JobDataReplicator get() {
return replicator;
}
private static RetryableReplicatorEventStream<JobSnapshot, JobManagerEvent<?>> newReplicatorEventStream(JobConnectorConfiguration configuration,
JobManagementClient client,
Map<String, String> filteringCriteria,
JobSnapshotFactory jobSnapshotFactory,
TitusRuntime titusRuntime) {
GrpcJobReplicatorEventStream grpcEventStream = new GrpcJobReplicatorEventStream(
client,
filteringCriteria,
jobSnapshotFactory,
configuration,
new JobDataReplicatorMetrics(JOB_REPLICATOR_GRPC_STREAM, configuration, titusRuntime),
titusRuntime,
Schedulers.parallel()
);
return new RetryableReplicatorEventStream<>(
grpcEventStream,
new JobDataReplicatorMetrics(JOB_REPLICATOR_RETRYABLE_STREAM, configuration, titusRuntime),
titusRuntime,
Schedulers.parallel()
);
}
private static class JobDataReplicatorImpl extends DataReplicatorDelegate<JobSnapshot, JobManagerEvent<?>> implements JobDataReplicator {
JobDataReplicatorImpl(DataReplicator<JobSnapshot, JobManagerEvent<?>> delegate) {
super(delegate);
}
}
private static class JobDataReplicatorMetrics extends DataReplicatorMetrics<JobSnapshot, JobManagerEvent<?>> {
private JobDataReplicatorMetrics(String source, JobConnectorConfiguration configuration, TitusRuntime titusRuntime) {
super(source, configuration.isKeepAliveReplicatedStreamEnabled(), titusRuntime);
}
@Override
public void event(ReplicatorEvent<JobSnapshot, JobManagerEvent<?>> event) {
super.event(event);
setCacheCollectionSize("jobs", event.getSnapshot().getJobMap().size());
setCacheCollectionSize("tasks", event.getSnapshot().getTaskMap().size());
}
}
}
| 1,210 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common/replicator/DataReplicator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.common.replicator;
import java.io.Closeable;
import com.netflix.titus.common.util.tuple.Pair;
import reactor.core.publisher.Flux;
/**
* Data replicator from a remote service.
*/
public interface DataReplicator<SNAPSHOT extends ReplicatedSnapshot, TRIGGER> extends Closeable {
/**
* Get the latest known version of the data.
*/
SNAPSHOT getCurrent();
/**
* Equivalent to calling "clock.wallTime() - getLastCheckpointTimestamp()".
*/
long getStalenessMs();
/**
* Returns the timestamp for which all server side changes that happened before it are guaranteed to be in cache.
* The actual cache state may be more up to date, so this is an upper bound on the replication latency.
* Returns -1 if the value is not known.
*/
long getLastCheckpointTimestamp();
/**
* Equivalent to "observeLastCheckpointTimestamp().map(timestamp -> clock.wallTime() - timestamp)".
*/
Flux<Long> observeDataStalenessMs();
/**
* Emits a value when a new checkpoint marker is received.
*/
Flux<Long> observeLastCheckpointTimestamp();
/**
* Emits events that triggered snapshot updates.
*/
Flux<Pair<SNAPSHOT, TRIGGER>> events();
}
| 1,211 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common/replicator/ReplicatorEventStream.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.common.replicator;
import java.time.Duration;
import reactor.core.publisher.Flux;
/**
* An auxiliary interface used within the connector components only to deal with the remote Rx event streams.
*/
public interface ReplicatorEventStream<SNAPSHOT, TRIGGER> {
long LATENCY_REPORT_INTERVAL_MS = 1_000;
Duration LATENCY_REPORT_INTERVAL = Duration.ofMillis(1_000);
Flux<ReplicatorEvent<SNAPSHOT, TRIGGER>> connect();
}
| 1,212 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common/replicator/ReplicatedSnapshot.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.common.replicator;
public abstract class ReplicatedSnapshot {
/**
* Provides a short alternative to {@link #toString()} method for logging/debugging purposes.
*/
public abstract String toSummaryString();
}
| 1,213 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common/replicator/DataReplicatorMetrics.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.common.replicator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.time.Clock;
/**
* Recommended metrics that should be reported by {@link DataReplicator} implementations.
*/
public class DataReplicatorMetrics<SNAPSHOT, TRIGGER> {
private static final String ROOT = "titus.dataReplicator.";
private final String source;
private final boolean useCheckpointTimestamp;
private final Clock clock;
private final Registry registry;
private final AtomicLong connected = new AtomicLong();
private final Id failuresId;
private final Id stalenessId;
private final ConcurrentMap<String, AtomicLong> cacheCollectionSizes = new ConcurrentHashMap<>();
private volatile long lastUpdateTimestamp;
public DataReplicatorMetrics(String source, boolean useCheckpointTimestamp, TitusRuntime titusRuntime) {
this.source = source;
this.useCheckpointTimestamp = useCheckpointTimestamp;
this.clock = titusRuntime.getClock();
this.registry = titusRuntime.getRegistry();
// Use PolledMeter as this metric is set infrequently
PolledMeter.using(registry).withId(registry.createId(ROOT + "connected", "source", source)).monitorValue(connected);
this.failuresId = registry.createId(ROOT + "failures", "source", source);
this.stalenessId = registry.createId(ROOT + "staleness", "source", source);
PolledMeter.using(registry).withId(stalenessId).monitorValue(this, self ->
self.lastUpdateTimestamp <= 0 ? 0 : self.clock.wallTime() - self.lastUpdateTimestamp
);
}
public void shutdown() {
PolledMeter.remove(registry, stalenessId);
}
public void connected() {
lastUpdateTimestamp = clock.wallTime();
connected.set(1);
}
public void disconnected() {
connected.set(0);
lastUpdateTimestamp = -1;
}
public void disconnected(Throwable error) {
disconnected();
registry.counter(failuresId.withTags("error", error.getClass().getSimpleName())).increment();
}
public void event(ReplicatorEvent<SNAPSHOT, TRIGGER> event) {
this.lastUpdateTimestamp = useCheckpointTimestamp ? event.getLastCheckpointTimestamp() : event.getLastUpdateTime();
}
protected void setCacheCollectionSize(String name, long size) {
cacheCollectionSizes.computeIfAbsent(name, n -> PolledMeter.using(registry)
.withId(registry.createId(ROOT + "cache", "source", source, "cacheCollection", name))
.monitorValue(new AtomicLong())
).set(size);
}
}
| 1,214 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common/replicator/DataReplicatorException.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.common.replicator;
import java.util.Optional;
class DataReplicatorException extends RuntimeException {
private final Optional<ReplicatorEvent<?, ?>> lastCacheEvent;
DataReplicatorException(Optional<ReplicatorEvent<?, ?>> lastCacheEvent, Throwable cause) {
super(cause);
this.lastCacheEvent = lastCacheEvent;
}
Optional<ReplicatorEvent<?, ?>> getLastCacheEvent() {
return lastCacheEvent;
}
}
| 1,215 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common/replicator/RetryableReplicatorEventStream.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.common.replicator;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.rx.ReactorExt;
import com.netflix.titus.common.util.rx.RetryHandlerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import reactor.util.retry.Retry;
public class RetryableReplicatorEventStream<SNAPSHOT, TRIGGER> implements ReplicatorEventStream<SNAPSHOT, TRIGGER> {
private static final Logger logger = LoggerFactory.getLogger(RetryableReplicatorEventStream.class);
static final long INITIAL_RETRY_DELAY_MS = 500;
static final long MAX_RETRY_DELAY_MS = 2_000;
private final ReplicatorEventStream<SNAPSHOT, TRIGGER> delegate;
private final DataReplicatorMetrics metrics;
private final TitusRuntime titusRuntime;
private final Scheduler scheduler;
public RetryableReplicatorEventStream(ReplicatorEventStream<SNAPSHOT, TRIGGER> delegate,
DataReplicatorMetrics metrics,
TitusRuntime titusRuntime,
Scheduler scheduler) {
this.delegate = delegate;
this.metrics = metrics;
this.titusRuntime = titusRuntime;
this.scheduler = scheduler;
}
@Override
public Flux<ReplicatorEvent<SNAPSHOT, TRIGGER>> connect() {
return newRetryableConnection().transformDeferred(
ReactorExt.reEmitter(Function.identity(), Duration.ofMillis(LATENCY_REPORT_INTERVAL_MS), scheduler)
);
}
private Flux<ReplicatorEvent<SNAPSHOT, TRIGGER>> newRetryableConnection() {
Retry retryer = RetryHandlerBuilder.retryHandler()
.withTitle("RetryableReplicatorEventStream of " + delegate.getClass().getSimpleName())
.withUnlimitedRetries()
.withDelay(INITIAL_RETRY_DELAY_MS, MAX_RETRY_DELAY_MS, TimeUnit.MILLISECONDS)
.withReactorScheduler(scheduler)
.buildRetryExponentialBackoff();
return delegate.connect()
.doOnTerminate(metrics::disconnected)
.retryWhen(retryer)
.doOnNext(event -> {
metrics.connected();
metrics.event(event);
})
.doOnError(error -> {
// Because we always retry, we should never reach this point.
logger.warn("Retryable stream terminated with an error", new IllegalStateException(error)); // Record current stack trace if that happens
titusRuntime.getCodeInvariants().unexpectedError("Retryable stream terminated with an error", error.getMessage());
metrics.disconnected(error);
})
.doOnCancel(metrics::disconnected)
.doOnTerminate(metrics::disconnected);
}
}
| 1,216 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common/replicator/ReplicatorEvent.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.common.replicator;
import java.util.Objects;
public class ReplicatorEvent<SNAPSHOT, TRIGGER> {
private final SNAPSHOT snapshot;
private final TRIGGER trigger;
private final long lastUpdateTime;
private final long lastCheckpointTimestamp;
public ReplicatorEvent(SNAPSHOT snapshot, TRIGGER trigger, long lastUpdateTime) {
this(snapshot, trigger, lastUpdateTime, -1);
}
public ReplicatorEvent(SNAPSHOT snapshot, TRIGGER trigger, long lastUpdateTime, long lastCheckpointTimestamp) {
this.snapshot = snapshot;
this.trigger = trigger;
this.lastUpdateTime = lastUpdateTime;
this.lastCheckpointTimestamp = lastCheckpointTimestamp;
}
public SNAPSHOT getSnapshot() {
return snapshot;
}
public TRIGGER getTrigger() {
return trigger;
}
public long getLastUpdateTime() {
return lastUpdateTime;
}
public long getLastCheckpointTimestamp() {
return lastCheckpointTimestamp;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReplicatorEvent<?, ?> that = (ReplicatorEvent<?, ?>) o;
return lastUpdateTime == that.lastUpdateTime && lastCheckpointTimestamp == that.lastCheckpointTimestamp && Objects.equals(snapshot, that.snapshot) && Objects.equals(trigger, that.trigger);
}
@Override
public int hashCode() {
return Objects.hash(snapshot, trigger, lastUpdateTime, lastCheckpointTimestamp);
}
@Override
public String toString() {
return "ReplicatorEvent{" +
"snapshot=" + snapshot +
", trigger=" + trigger +
", lastUpdateTime=" + lastUpdateTime +
", lastCheckpointTimestamp=" + lastCheckpointTimestamp +
'}';
}
}
| 1,217 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common/replicator/StreamDataReplicator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.common.replicator;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;
/**
* {@link DataReplicator} implementation that wraps {@link ReplicatorEventStream}. The latter is provided
* as a constructor argument by extensions of this class.
*/
public class StreamDataReplicator<SNAPSHOT extends ReplicatedSnapshot, TRIGGER> implements DataReplicator<SNAPSHOT, TRIGGER> {
private static final Logger logger = LoggerFactory.getLogger(StreamDataReplicator.class);
// Staleness threshold checked during the system initialization.
private static final long STALENESS_THRESHOLD = 60_000;
private final TitusRuntime titusRuntime;
private final boolean useCheckpointTimestamp;
private final Disposable internalSubscription;
private final Sinks.Many<ReplicatorEvent<SNAPSHOT, TRIGGER>> shutdownSink = Sinks.many().multicast().directAllOrNothing();
private final Flux<ReplicatorEvent<SNAPSHOT, TRIGGER>> eventStream;
private final AtomicReference<ReplicatorEvent<SNAPSHOT, TRIGGER>> lastReplicatorEventRef;
public StreamDataReplicator(Flux<ReplicatorEvent<SNAPSHOT, TRIGGER>> eventStream,
boolean useCheckpointTimestamp,
Disposable internalSubscription,
AtomicReference<ReplicatorEvent<SNAPSHOT, TRIGGER>> lastReplicatorEventRef,
TitusRuntime titusRuntime) {
this.eventStream = eventStream.mergeWith(shutdownSink.asFlux());
this.useCheckpointTimestamp = useCheckpointTimestamp;
this.internalSubscription = internalSubscription;
this.lastReplicatorEventRef = lastReplicatorEventRef;
this.titusRuntime = titusRuntime;
}
@Override
public void close() {
shutdownSink.emitError(new IllegalStateException("Data replicator closed"), Sinks.EmitFailureHandler.FAIL_FAST);
internalSubscription.dispose();
}
@Override
public SNAPSHOT getCurrent() {
return lastReplicatorEventRef.get().getSnapshot();
}
@Override
public long getStalenessMs() {
return titusRuntime.getClock().wallTime() - getLastCheckpointTimestamp();
}
@Override
public long getLastCheckpointTimestamp() {
if (useCheckpointTimestamp) {
return lastReplicatorEventRef.get().getLastCheckpointTimestamp();
}
// When we do not have the checkpoint, we take the timestamp of the last event that we received.
return lastReplicatorEventRef.get().getLastUpdateTime();
}
@Override
public Flux<Long> observeDataStalenessMs() {
return observeLastCheckpointTimestamp().map(timestamp -> titusRuntime.getClock().wallTime() - timestamp);
}
/**
* Emits a value whenever a checkpoint value is updated. The checkpoint timestamp that is emitted is
* read from {@link #lastReplicatorEventRef}, not from the event stream. It is done like that in case the
* event is delivered before the {@link #lastReplicatorEventRef} is updated. Otherwise the caller to
* {@link #getCurrent()} might read an earlier version of a snapshot and associate it with a later checkpoint value.
*/
@Override
public Flux<Long> observeLastCheckpointTimestamp() {
return eventStream.map(next -> getLastCheckpointTimestamp());
}
@Override
public Flux<Pair<SNAPSHOT, TRIGGER>> events() {
return eventStream.map(event -> Pair.of(event.getSnapshot(), event.getTrigger()));
}
public static <SNAPSHOT extends ReplicatedSnapshot, TRIGGER> StreamDataReplicator<SNAPSHOT, TRIGGER>
newStreamDataReplicator(ReplicatorEvent<SNAPSHOT, TRIGGER> initialEvent,
ReplicatorEventStream<SNAPSHOT, TRIGGER> replicatorEventStream,
boolean useCheckpointTimestamp,
DataReplicatorMetrics metrics,
TitusRuntime titusRuntime) {
AtomicReference<ReplicatorEvent<SNAPSHOT, TRIGGER>> lastReplicatorEventRef = new AtomicReference<>(initialEvent);
Flux<ReplicatorEvent<SNAPSHOT, TRIGGER>> eventStream = replicatorEventStream.connect().publish().autoConnect(1);
Disposable internalSubscription = newMonitoringSubscription(metrics, lastReplicatorEventRef, eventStream);
return new StreamDataReplicator<>(eventStream, useCheckpointTimestamp, internalSubscription, lastReplicatorEventRef, titusRuntime);
}
public static <SNAPSHOT extends ReplicatedSnapshot, TRIGGER> Flux<StreamDataReplicator<SNAPSHOT, TRIGGER>>
newStreamDataReplicator(ReplicatorEventStream<SNAPSHOT, TRIGGER> replicatorEventStream,
boolean useCheckpointTimestamp,
DataReplicatorMetrics metrics,
TitusRuntime titusRuntime) {
return Flux.defer(() -> {
AtomicReference<ReplicatorEvent<SNAPSHOT, TRIGGER>> lastReplicatorEventRef = new AtomicReference<>();
AtomicReference<Disposable> publisherDisposable = new AtomicReference<>();
Flux<ReplicatorEvent<SNAPSHOT, TRIGGER>> eventStream = replicatorEventStream.connect().
publish()
.autoConnect(2, publisherDisposable::set);
newMonitoringSubscription(metrics, lastReplicatorEventRef, eventStream);
return eventStream.filter(e -> isFresh(e, titusRuntime)).take(1).map(e -> {
return new StreamDataReplicator<>(eventStream, useCheckpointTimestamp, publisherDisposable.get(), lastReplicatorEventRef, titusRuntime);
}
);
});
}
private static <SNAPSHOT extends ReplicatedSnapshot, TRIGGER> Disposable
newMonitoringSubscription(DataReplicatorMetrics metrics,
AtomicReference<ReplicatorEvent<SNAPSHOT, TRIGGER>> lastReplicatorEventRef,
Flux<ReplicatorEvent<SNAPSHOT, TRIGGER>> eventStream) {
return eventStream
.doOnSubscribe(s -> metrics.connected())
.doOnCancel(metrics::disconnected)
.subscribe(
next -> {
logger.debug("Snapshot update: {}", next.getSnapshot().toSummaryString());
lastReplicatorEventRef.set(next);
metrics.event(next);
},
e -> {
if (e instanceof CancellationException) {
logger.info("Data replication stream subscription cancelled");
} else {
logger.error("Unexpected error in the replicator event stream", e);
}
metrics.disconnected(e);
},
() -> {
logger.info("Replicator event stream completed");
metrics.disconnected();
}
);
}
private static boolean isFresh(ReplicatorEvent event, TitusRuntime titusRuntime) {
long now = titusRuntime.getClock().wallTime();
return event.getLastUpdateTime() + STALENESS_THRESHOLD >= now;
}
}
| 1,218 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common/replicator/DataReplicatorDelegate.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.common.replicator;
import java.io.IOException;
import com.netflix.titus.common.util.tuple.Pair;
import reactor.core.publisher.Flux;
public class DataReplicatorDelegate<SNAPSHOT extends ReplicatedSnapshot, TRIGGER> implements DataReplicator<SNAPSHOT, TRIGGER> {
private DataReplicator<SNAPSHOT, TRIGGER> delegate;
public DataReplicatorDelegate(DataReplicator<SNAPSHOT, TRIGGER> delegate) {
this.delegate = delegate;
}
@Override
public void close() throws IOException {
delegate.close();
}
@Override
public SNAPSHOT getCurrent() {
return delegate.getCurrent();
}
@Override
public long getStalenessMs() {
return delegate.getStalenessMs();
}
@Override
public long getLastCheckpointTimestamp() {
return delegate.getLastCheckpointTimestamp();
}
@Override
public Flux<Long> observeDataStalenessMs() {
return delegate.observeDataStalenessMs();
}
@Override
public Flux<Long> observeLastCheckpointTimestamp() {
return delegate.observeLastCheckpointTimestamp();
}
@Override
public Flux<Pair<SNAPSHOT, TRIGGER>> events() {
return delegate.events();
}
}
| 1,219 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/common/replicator/AbstractReplicatorEventStream.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.common.replicator;
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.Flux;
import reactor.core.scheduler.Scheduler;
public abstract class AbstractReplicatorEventStream<SNAPSHOT, TRIGGER> implements ReplicatorEventStream<SNAPSHOT, TRIGGER> {
private static final Logger logger = LoggerFactory.getLogger(AbstractReplicatorEventStream.class);
private final boolean serverSideKeepAlive;
private final TRIGGER keepAliveEvent;
protected final DataReplicatorMetrics metrics;
protected final TitusRuntime titusRuntime;
protected final Scheduler scheduler;
protected AbstractReplicatorEventStream(boolean serverSideKeepAlive,
TRIGGER keepAliveEvent,
DataReplicatorMetrics metrics,
TitusRuntime titusRuntime,
Scheduler scheduler) {
this.serverSideKeepAlive = serverSideKeepAlive;
this.keepAliveEvent = keepAliveEvent;
this.metrics = metrics;
this.titusRuntime = titusRuntime;
this.scheduler = scheduler;
}
@Override
public Flux<ReplicatorEvent<SNAPSHOT, TRIGGER>> connect() {
Flux<ReplicatorEvent<SNAPSHOT, TRIGGER>> replicatorEvent = newConnection();
if (!serverSideKeepAlive) {
replicatorEvent = replicatorEvent.transformDeferred(ReactorExt.reEmitter(
// If there are no events in the stream, we will periodically the emit keep alive event
// with the updated cache update timestamp, so it does not look stale.
cacheEvent -> new ReplicatorEvent<>(cacheEvent.getSnapshot(), keepAliveEvent, titusRuntime.getClock().wallTime()),
LATENCY_REPORT_INTERVAL,
scheduler
));
}
return replicatorEvent
.doOnNext(event -> {
metrics.connected();
metrics.event(event);
})
.doOnCancel(metrics::disconnected)
.doOnError(error -> {
logger.warn("[{}] Connection to the event stream terminated with an error: {}", getClass().getSimpleName(), error.getMessage());
logger.debug("[{}] More details: {}", getClass().getSimpleName(), error.getMessage(), error);
metrics.disconnected(error);
})
.doOnComplete(metrics::disconnected);
}
protected abstract Flux<ReplicatorEvent<SNAPSHOT, TRIGGER>> newConnection();
}
| 1,220 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/CachedReadOnlyTaskRelocationService.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.relocation;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.titus.api.relocation.model.TaskRelocationPlan;
import com.netflix.titus.api.relocation.model.event.TaskRelocationEvent;
import com.netflix.titus.api.relocation.service.ReadOnlyTaskRelocationService;
import reactor.core.publisher.Flux;
@Singleton
public class CachedReadOnlyTaskRelocationService implements ReadOnlyTaskRelocationService {
private final RelocationDataReplicator replicator;
@Inject
public CachedReadOnlyTaskRelocationService(RelocationDataReplicator replicator) {
this.replicator = replicator;
}
@Override
public Map<String, TaskRelocationPlan> getPlannedRelocations() {
return replicator.getCurrent().getPlans();
}
@Override
public Flux<TaskRelocationEvent> events() {
throw new IllegalStateException("method not implemented yet");
}
}
| 1,221 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/RelocationClientConnectorModule.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.relocation;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provides;
import com.google.inject.name.Names;
import com.netflix.archaius.ConfigProxyFactory;
import com.netflix.titus.common.util.grpc.reactor.GrpcToReactorClientFactory;
import com.netflix.titus.grpc.protogen.TaskRelocationServiceGrpc;
import com.netflix.titus.runtime.connector.relocation.noop.NoOpRelocationServiceClient;
import io.grpc.Channel;
public class RelocationClientConnectorModule extends AbstractModule {
public static final String RELOCATION_CLIENT = "relocationClient";
@Override
protected void configure() {
}
@Provides
@Singleton
public RelocationConnectorConfiguration getRelocationConnectorConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(RelocationConnectorConfiguration.class);
}
@Provides
@Singleton
public RelocationServiceClient getRelocationServiceClient(RelocationConnectorConfiguration configuration,
Injector injector,
GrpcToReactorClientFactory factory) {
if (configuration.isEnabled()) {
Channel channel = injector.getInstance(Key.get(Channel.class, Names.named(RELOCATION_CLIENT)));
ReactorRelocationServiceStub stub = factory.apply(
TaskRelocationServiceGrpc.newStub(channel),
ReactorRelocationServiceStub.class,
TaskRelocationServiceGrpc.getServiceDescriptor()
);
return new RemoteRelocationServiceClient(stub);
}
return new NoOpRelocationServiceClient();
}
}
| 1,222 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/ReactorRelocationServiceStub.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.relocation;
import com.netflix.titus.grpc.protogen.RelocationEvent;
import com.netflix.titus.grpc.protogen.TaskRelocationPlans;
import com.netflix.titus.grpc.protogen.TaskRelocationQuery;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Task relocation GRPC client with Spring/Reactor API.
*/
public interface ReactorRelocationServiceStub {
Mono<TaskRelocationPlans> getCurrentTaskRelocationPlans(TaskRelocationQuery query);
Flux<RelocationEvent> observeRelocationEvents(TaskRelocationQuery query);
}
| 1,223 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/TaskRelocationSnapshot.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.relocation;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.netflix.titus.api.relocation.model.TaskRelocationPlan;
import com.netflix.titus.common.util.Evaluators;
import com.netflix.titus.runtime.connector.common.replicator.ReplicatedSnapshot;
public class TaskRelocationSnapshot extends ReplicatedSnapshot {
private static final TaskRelocationSnapshot EMPTY = newBuilder().build();
private final String snapshotId;
private final Map<String, TaskRelocationPlan> plans;
private final String summaryString;
public TaskRelocationSnapshot(String snapshotId, Map<String, TaskRelocationPlan> plans) {
this.snapshotId = snapshotId;
this.plans = Collections.unmodifiableMap(plans);
this.summaryString = computeSignature();
}
public static TaskRelocationSnapshot empty() {
return EMPTY;
}
public Map<String, TaskRelocationPlan> getPlans() {
return plans;
}
@Override
public String toSummaryString() {
return summaryString;
}
@Override
public String toString() {
return "TaskRelocationSnapshot{" +
"plans=" + plans +
'}';
}
private String computeSignature() {
return "TaskRelocationSnapshot{snapshotId=" + snapshotId +
", plans=" + plans.size() +
"}";
}
public Builder toBuilder() {
return newBuilder().withPlans(plans);
}
public static Builder newBuilder() {
return new Builder(UUID.randomUUID().toString());
}
public static final class Builder {
private final String snapshotId;
private Map<String, TaskRelocationPlan> plans;
private Builder(String snapshotId) {
this.snapshotId = snapshotId;
}
public Builder withPlans(Map<String, TaskRelocationPlan> plans) {
this.plans = new HashMap<>(plans);
return this;
}
public Builder addPlan(TaskRelocationPlan plan) {
if (plans == null) {
this.plans = new HashMap<>();
}
plans.put(plan.getTaskId(), plan);
return this;
}
public Builder removePlan(String taskId) {
if (plans != null) {
plans.remove(taskId);
}
return this;
}
public TaskRelocationSnapshot build() {
return new TaskRelocationSnapshot(snapshotId, Evaluators.getOrDefault(plans, Collections.emptyMap()));
}
}
}
| 1,224 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/RelocationConnectorConfiguration.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.relocation;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
@Configuration(prefix = "titus.connector.relocationService")
public interface RelocationConnectorConfiguration {
/**
* Relocation is an optional service. If this property is set to false, a real client is replaced with
* {@link com.netflix.titus.runtime.connector.relocation.noop.NoOpRelocationServiceClient}.
*/
@DefaultValue("true")
boolean isEnabled();
}
| 1,225 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/RelocationServiceClient.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.relocation;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import com.netflix.titus.api.relocation.model.TaskRelocationPlan;
import com.netflix.titus.api.relocation.model.event.TaskRelocationEvent;
import com.netflix.titus.grpc.protogen.TaskRelocationQuery;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface RelocationServiceClient {
Mono<Optional<TaskRelocationPlan>> findTaskRelocationPlan(String taskId);
Mono<List<TaskRelocationPlan>> findTaskRelocationPlans(Set<String> taskIds);
Flux<TaskRelocationEvent> events(TaskRelocationQuery query);
}
| 1,226 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/RelocationDataReplicator.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.relocation;
import com.netflix.titus.api.relocation.model.event.TaskRelocationEvent;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicator;
public interface RelocationDataReplicator extends DataReplicator<TaskRelocationSnapshot, TaskRelocationEvent> {
}
| 1,227 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/RemoteRelocationServiceClient.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.relocation;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.titus.api.relocation.model.TaskRelocationPlan;
import com.netflix.titus.api.relocation.model.event.TaskRelocationEvent;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.grpc.protogen.Page;
import com.netflix.titus.grpc.protogen.TaskRelocationQuery;
import com.netflix.titus.runtime.relocation.endpoint.RelocationGrpcModelConverters;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.netflix.titus.runtime.relocation.endpoint.RelocationGrpcModelConverters.toCoreTaskRelocationPlan;
/**
* {@link RelocationServiceClient} implementation that translates all invocation into underlying GRPC calls.
*/
@Singleton
public class RemoteRelocationServiceClient implements RelocationServiceClient {
private static final Page ONE_ITEM_PAGE = Page.newBuilder().setPageSize(1).build();
private final ReactorRelocationServiceStub transportRelocationClient;
@Inject
public RemoteRelocationServiceClient(ReactorRelocationServiceStub transportRelocationClient) {
this.transportRelocationClient = transportRelocationClient;
}
@Override
public Mono<Optional<TaskRelocationPlan>> findTaskRelocationPlan(String taskId) {
return transportRelocationClient.getCurrentTaskRelocationPlans(TaskRelocationQuery.newBuilder()
.setPage(ONE_ITEM_PAGE)
.putFilteringCriteria("taskIds", taskId)
.build()
).flatMap(plans -> {
if (plans.getPlansList().isEmpty()) {
return Mono.just(Optional.empty());
}
// Sanity check
if (plans.getPlansList().size() > 1) {
return Mono.error(new IllegalStateException("Received multiple relocation plans for the same task id: " + taskId));
}
return Mono.just(Optional.of(toCoreTaskRelocationPlan(plans.getPlansList().get(0))));
});
}
@Override
public Mono<List<TaskRelocationPlan>> findTaskRelocationPlans(Set<String> taskIds) {
return transportRelocationClient.getCurrentTaskRelocationPlans(TaskRelocationQuery.newBuilder()
.setPage(ONE_ITEM_PAGE)
.putFilteringCriteria("taskIds", StringExt.concatenate(taskIds, ","))
.build()
).flatMap(plans -> {
List<TaskRelocationPlan> coreList = plans.getPlansList().stream()
.map(RelocationGrpcModelConverters::toCoreTaskRelocationPlan)
.collect(Collectors.toList());
return Mono.just(coreList);
});
}
@Override
public Flux<TaskRelocationEvent> events(TaskRelocationQuery query) {
return transportRelocationClient.observeRelocationEvents(query)
.map(grpcEvent -> RelocationGrpcModelConverters.toCoreRelocationEvent(grpcEvent))
.filter(Optional::isPresent)
.map(Optional::get);
}
}
| 1,228 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/RelocationDataReplicationModule.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.relocation;
import com.google.inject.AbstractModule;
import com.netflix.titus.api.relocation.service.ReadOnlyTaskRelocationService;
import com.netflix.titus.runtime.connector.relocation.replicator.RelocationDataReplicatorProvider;
public class RelocationDataReplicationModule extends AbstractModule {
@Override
protected void configure() {
bind(RelocationDataReplicator.class).toProvider(RelocationDataReplicatorProvider.class);
bind(ReadOnlyTaskRelocationService.class).to(CachedReadOnlyTaskRelocationService.class);
}
}
| 1,229 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/noop/NoOpRelocationServiceClient.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.relocation.noop;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import com.netflix.titus.api.relocation.model.TaskRelocationPlan;
import com.netflix.titus.api.relocation.model.event.TaskRelocationEvent;
import com.netflix.titus.grpc.protogen.TaskRelocationQuery;
import com.netflix.titus.runtime.connector.relocation.RelocationServiceClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class NoOpRelocationServiceClient implements RelocationServiceClient {
@Override
public Mono<Optional<TaskRelocationPlan>> findTaskRelocationPlan(String taskId) {
return Mono.error(new IllegalArgumentException("Not found"));
}
@Override
public Mono<List<TaskRelocationPlan>> findTaskRelocationPlans(Set<String> taskIds) {
return Mono.just(Collections.emptyList());
}
@Override
public Flux<TaskRelocationEvent> events(TaskRelocationQuery query) {
return Flux.never();
}
}
| 1,230 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/replicator/RelocationDataReplicatorProvider.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.relocation.replicator;
import java.util.UUID;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import com.netflix.titus.api.relocation.model.event.TaskRelocationEvent;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.ExceptionExt;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicator;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicatorDelegate;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicatorMetrics;
import com.netflix.titus.runtime.connector.common.replicator.ReplicatorEvent;
import com.netflix.titus.runtime.connector.common.replicator.RetryableReplicatorEventStream;
import com.netflix.titus.runtime.connector.common.replicator.StreamDataReplicator;
import com.netflix.titus.runtime.connector.relocation.RelocationDataReplicator;
import com.netflix.titus.runtime.connector.relocation.RelocationServiceClient;
import com.netflix.titus.runtime.connector.relocation.TaskRelocationSnapshot;
import reactor.core.scheduler.Schedulers;
/**
* {@link RelocationDataReplicator} cache unlike other caches is initialized lazily, and start empty.
*/
@Singleton
public class RelocationDataReplicatorProvider implements Provider<RelocationDataReplicator> {
private static final String RELOCATION_REPLICATOR = "relocationReplicator";
private static final String RELOCATION_REPLICATOR_RETRYABLE_STREAM = "relocationReplicatorRetryableStream";
private static final String RELOCATION_REPLICATOR_GRPC_STREAM = "relocationReplicatorGrpcStream";
/**
* As we start with an empty cache, there is no event associated with the initial version of the snapshot.
* Instead we use this constant value.
*/
private static final TaskRelocationEvent STARTUP_EVENT = TaskRelocationEvent.taskRelocationPlanRemoved(UUID.randomUUID().toString());
private final RelocationDataReplicatorImpl replicator;
@Inject
public RelocationDataReplicatorProvider(RelocationServiceClient client, TitusRuntime titusRuntime) {
StreamDataReplicator<TaskRelocationSnapshot, TaskRelocationEvent> original = StreamDataReplicator.newStreamDataReplicator(
new ReplicatorEvent<>(TaskRelocationSnapshot.empty(), STARTUP_EVENT, 0L),
newReplicatorEventStream(client, titusRuntime),
false,
new RelocationDataReplicatorMetrics(RELOCATION_REPLICATOR, titusRuntime),
titusRuntime
);
this.replicator = new RelocationDataReplicatorImpl(original);
}
@PreDestroy
public void shutdown() {
ExceptionExt.silent(replicator::close);
}
@Override
public RelocationDataReplicatorImpl get() {
return replicator;
}
private static RetryableReplicatorEventStream<TaskRelocationSnapshot, TaskRelocationEvent> newReplicatorEventStream(RelocationServiceClient client, TitusRuntime titusRuntime) {
GrpcRelocationReplicatorEventStream grpcEventStream = new GrpcRelocationReplicatorEventStream(
client,
new DataReplicatorMetrics<>(RELOCATION_REPLICATOR_GRPC_STREAM, false, titusRuntime),
titusRuntime,
Schedulers.parallel()
);
return new RetryableReplicatorEventStream<>(
grpcEventStream,
new DataReplicatorMetrics<>(RELOCATION_REPLICATOR_RETRYABLE_STREAM, false, titusRuntime),
titusRuntime,
Schedulers.parallel()
);
}
private static class RelocationDataReplicatorImpl extends DataReplicatorDelegate<TaskRelocationSnapshot, TaskRelocationEvent> implements RelocationDataReplicator {
RelocationDataReplicatorImpl(DataReplicator<TaskRelocationSnapshot, TaskRelocationEvent> delegate) {
super(delegate);
}
}
private static class RelocationDataReplicatorMetrics extends DataReplicatorMetrics<TaskRelocationSnapshot, TaskRelocationEvent> {
private RelocationDataReplicatorMetrics(String source, TitusRuntime titusRuntime) {
super(source, false, titusRuntime);
}
@Override
public void event(ReplicatorEvent<TaskRelocationSnapshot, TaskRelocationEvent> event) {
super.event(event);
setCacheCollectionSize("plans", event.getSnapshot().getPlans().size());
}
}
}
| 1,231 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/relocation/replicator/GrpcRelocationReplicatorEventStream.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.relocation.replicator;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.titus.api.relocation.model.event.TaskRelocationEvent;
import com.netflix.titus.api.relocation.model.event.TaskRelocationPlanRemovedEvent;
import com.netflix.titus.api.relocation.model.event.TaskRelocationPlanUpdateEvent;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.grpc.protogen.TaskRelocationQuery;
import com.netflix.titus.runtime.connector.common.replicator.AbstractReplicatorEventStream;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicatorMetrics;
import com.netflix.titus.runtime.connector.common.replicator.ReplicatorEvent;
import com.netflix.titus.runtime.connector.relocation.RelocationServiceClient;
import com.netflix.titus.runtime.connector.relocation.TaskRelocationSnapshot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
public class GrpcRelocationReplicatorEventStream extends AbstractReplicatorEventStream<TaskRelocationSnapshot, TaskRelocationEvent> {
private static final Logger logger = LoggerFactory.getLogger(GrpcRelocationReplicatorEventStream.class);
private final RelocationServiceClient client;
public GrpcRelocationReplicatorEventStream(RelocationServiceClient client,
DataReplicatorMetrics metrics,
TitusRuntime titusRuntime,
Scheduler scheduler) {
super(false, TaskRelocationEvent.newKeepAliveEvent(), metrics, titusRuntime, scheduler);
this.client = client;
}
@Override
protected Flux<ReplicatorEvent<TaskRelocationSnapshot, TaskRelocationEvent>> newConnection() {
return Flux.defer(() -> {
CacheUpdater cacheUpdater = new CacheUpdater();
logger.info("Connecting to the task relocation event stream...");
return client.events(TaskRelocationQuery.getDefaultInstance()).flatMap(cacheUpdater::onEvent);
});
}
private class CacheUpdater {
private final List<TaskRelocationEvent> snapshotEvents = new ArrayList<>();
private final AtomicReference<TaskRelocationSnapshot> lastSnapshotRef = new AtomicReference<>();
public Flux<ReplicatorEvent<TaskRelocationSnapshot, TaskRelocationEvent>> onEvent(TaskRelocationEvent event) {
try {
if (lastSnapshotRef.get() != null) {
return processSnapshotUpdate(event);
}
if (event.equals(TaskRelocationEvent.newSnapshotEndEvent())) {
return buildInitialCache();
}
snapshotEvents.add(event);
} catch (Exception e) {
logger.warn("Unexpected error when handling the relocation event: {}", event, e);
return Flux.error(e); // Return error to force the cache reconnect.
}
return Flux.empty();
}
private Flux<ReplicatorEvent<TaskRelocationSnapshot, TaskRelocationEvent>> buildInitialCache() {
TaskRelocationSnapshot.Builder builder = TaskRelocationSnapshot.newBuilder();
snapshotEvents.forEach(event -> applyToBuilder(builder, event));
TaskRelocationSnapshot snapshot = builder.build();
// No longer needed
snapshotEvents.clear();
logger.info("Relocation snapshot loaded: {}", snapshot.toSummaryString());
lastSnapshotRef.set(snapshot);
return Flux.just(new ReplicatorEvent<>(snapshot, TaskRelocationEvent.newSnapshotEndEvent(), titusRuntime.getClock().wallTime()));
}
private Flux<ReplicatorEvent<TaskRelocationSnapshot, TaskRelocationEvent>> processSnapshotUpdate(TaskRelocationEvent event) {
logger.debug("Processing task relocation event: {}", event);
TaskRelocationSnapshot.Builder builder = lastSnapshotRef.get().toBuilder();
applyToBuilder(builder, event);
TaskRelocationSnapshot newSnapshot = builder.build();
lastSnapshotRef.set(newSnapshot);
return Flux.just(new ReplicatorEvent<>(newSnapshot, event, titusRuntime.getClock().wallTime()));
}
private void applyToBuilder(TaskRelocationSnapshot.Builder builder, TaskRelocationEvent event) {
if (event instanceof TaskRelocationPlanUpdateEvent) {
builder.addPlan(((TaskRelocationPlanUpdateEvent) event).getPlan());
} else if (event instanceof TaskRelocationPlanRemovedEvent) {
builder.removePlan(((TaskRelocationPlanRemovedEvent) event).getTaskId());
}
}
}
}
| 1,232 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/EvictionDataReplicator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.eviction;
import com.netflix.titus.api.eviction.model.event.EvictionEvent;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicator;
public interface EvictionDataReplicator extends DataReplicator<EvictionDataSnapshot, EvictionEvent> {
}
| 1,233 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/EvictionServiceClient.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.eviction;
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;
import reactor.core.publisher.Mono;
public interface EvictionServiceClient {
Mono<EvictionQuota> getEvictionQuota(Reference reference);
Mono<Void> terminateTask(String taskId, String reason);
Flux<EvictionEvent> observeEvents(boolean includeSnapshot);
}
| 1,234 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/EvictionConnectorComponent.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.eviction;
import javax.inject.Named;
import com.netflix.titus.grpc.protogen.EvictionServiceGrpc;
import com.netflix.titus.common.util.grpc.reactor.GrpcToReactorClientFactory;
import io.grpc.Channel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EvictionConnectorComponent {
public static final String EVICTION_CHANNEL = "evictionChannel";
@Bean
public ReactorEvictionServiceStub getReactorEvictionServiceStub(GrpcToReactorClientFactory factory,
@Named(EVICTION_CHANNEL) Channel channel) {
return factory.apply(EvictionServiceGrpc.newStub(channel), ReactorEvictionServiceStub.class, EvictionServiceGrpc.getServiceDescriptor());
}
@Bean
public EvictionServiceClient getEvictionServiceClient(ReactorEvictionServiceStub stub) {
return new RemoteEvictionServiceClient(stub);
}
}
| 1,235 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/EvictionConnectorModule.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.eviction;
import javax.inject.Named;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.netflix.titus.common.util.grpc.reactor.GrpcToReactorClientFactory;
import com.netflix.titus.grpc.protogen.EvictionServiceGrpc;
import io.grpc.Channel;
public class EvictionConnectorModule extends AbstractModule {
public static final String MANAGED_CHANNEL_NAME = "ManagedChannel";
@Override
protected void configure() {
bind(EvictionServiceClient.class).to(RemoteEvictionServiceClient.class);
}
@Provides
@Singleton
public ReactorEvictionServiceStub getReactorEvictionServiceStub(GrpcToReactorClientFactory factory,
@Named(MANAGED_CHANNEL_NAME) Channel channel) {
return factory.apply(EvictionServiceGrpc.newStub(channel), ReactorEvictionServiceStub.class, EvictionServiceGrpc.getServiceDescriptor());
}
}
| 1,236 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/ReactorEvictionServiceStub.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.eviction;
import com.netflix.titus.grpc.protogen.EvictionQuota;
import com.netflix.titus.grpc.protogen.EvictionServiceEvent;
import com.netflix.titus.grpc.protogen.ObserverEventRequest;
import com.netflix.titus.grpc.protogen.Reference;
import com.netflix.titus.grpc.protogen.TaskTerminateRequest;
import com.netflix.titus.grpc.protogen.TaskTerminateResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface ReactorEvictionServiceStub {
Mono<EvictionQuota> getEvictionQuota(Reference request);
Mono<TaskTerminateResponse> terminateTask(TaskTerminateRequest request);
Flux<EvictionServiceEvent> observeEvents(ObserverEventRequest request);
}
| 1,237 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/CachedReadOnlyEvictionOperations.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.eviction;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.titus.api.eviction.model.EvictionQuota;
import com.netflix.titus.api.eviction.model.event.EvictionEvent;
import com.netflix.titus.api.eviction.service.ReadOnlyEvictionOperations;
import com.netflix.titus.api.model.reference.Reference;
import reactor.core.publisher.Flux;
@Singleton
public class CachedReadOnlyEvictionOperations implements ReadOnlyEvictionOperations {
private final EvictionDataReplicator replicator;
@Inject
public CachedReadOnlyEvictionOperations(EvictionDataReplicator replicator) {
this.replicator = replicator;
}
@Override
public EvictionQuota getEvictionQuota(Reference reference) {
return replicator.getCurrent().getEvictionQuota(reference);
}
@Override
public Optional<EvictionQuota> findEvictionQuota(Reference reference) {
return replicator.getCurrent().findEvictionQuota(reference);
}
@Override
public Flux<EvictionEvent> events(boolean includeSnapshot) {
throw new IllegalStateException("method not implemented yet");
}
}
| 1,238 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/EvictionRejectionReasons.java | package com.netflix.titus.runtime.connector.eviction;
public enum EvictionRejectionReasons {
LIMIT_EXCEEDED("System eviction quota limit exceeded"),
SYSTEM_WINDOW_CLOSED("Outside system time window");
private String reasonMessage;
EvictionRejectionReasons(String reasonMessage) {
this.reasonMessage = reasonMessage;
}
public String getReasonMessage() {
return reasonMessage;
}
}
| 1,239 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/RemoteEvictionServiceClient.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.eviction;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.titus.api.eviction.model.EvictionQuota;
import com.netflix.titus.api.eviction.model.event.EvictionEvent;
import com.netflix.titus.api.eviction.service.EvictionException;
import com.netflix.titus.api.model.reference.Reference;
import com.netflix.titus.grpc.protogen.ObserverEventRequest;
import com.netflix.titus.grpc.protogen.TaskTerminateRequest;
import com.netflix.titus.runtime.eviction.endpoint.grpc.GrpcEvictionModelConverters;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Singleton
public class RemoteEvictionServiceClient implements EvictionServiceClient {
private final ReactorEvictionServiceStub stub;
@Inject
public RemoteEvictionServiceClient(ReactorEvictionServiceStub stub) {
this.stub = stub;
}
@Override
public Mono<EvictionQuota> getEvictionQuota(Reference reference) {
return stub.getEvictionQuota(GrpcEvictionModelConverters.toGrpcReference(reference)).map(GrpcEvictionModelConverters::toCoreEvictionQuota);
}
@Override
public Mono<Void> terminateTask(String taskId, String reason) {
return stub.terminateTask(TaskTerminateRequest.newBuilder()
.setTaskId(taskId)
.setReason(reason)
.build()
).flatMap(response -> {
if (response.getAllowed()) {
return Mono.empty();
}
return Mono.error(EvictionException.deconstruct(response.getReasonCode(), response.getReasonMessage()));
});
}
@Override
public Flux<EvictionEvent> observeEvents(boolean includeSnapshot) {
return stub.observeEvents(ObserverEventRequest.newBuilder()
.setIncludeSnapshot(includeSnapshot)
.build()
).map(GrpcEvictionModelConverters::toCoreEvent);
}
}
| 1,240 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/EvictionDataSnapshot.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.eviction;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import com.netflix.titus.api.eviction.model.EvictionQuota;
import com.netflix.titus.api.eviction.service.EvictionException;
import com.netflix.titus.api.eviction.service.ReadOnlyEvictionOperations;
import com.netflix.titus.api.model.Level;
import com.netflix.titus.api.model.Tier;
import com.netflix.titus.api.model.reference.Reference;
import com.netflix.titus.api.model.reference.TierReference;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.runtime.connector.common.replicator.ReplicatedSnapshot;
import static com.netflix.titus.common.util.CollectionsExt.copyAndAdd;
/**
* TODO Removed job cleanup (not critical, as forced reconnects and the snapshot rebuild will do the work).
*/
public class EvictionDataSnapshot extends ReplicatedSnapshot {
private static final EvictionDataSnapshot EMPTY = new EvictionDataSnapshot(
"empty",
EvictionQuota.systemQuota(0, "Empty"),
Collections.emptyMap(),
Collections.emptyMap(),
Collections.emptyMap()
);
private final String snapshotId;
private final EvictionQuota systemEvictionQuota;
private final Map<Tier, EvictionQuota> tierEvictionQuotas;
private final Map<String, EvictionQuota> capacityGroupEvictionQuotas;
private final Map<String, EvictionQuota> jobEvictionQuotas;
private final String signature;
public EvictionDataSnapshot(String snapshotId,
EvictionQuota systemEvictionQuota,
Map<Tier, EvictionQuota> tierEvictionQuotas,
Map<String, EvictionQuota> capacityGroupEvictionQuotas,
Map<String, EvictionQuota> jobEvictionQuotas) {
this.snapshotId = snapshotId;
this.systemEvictionQuota = systemEvictionQuota;
this.tierEvictionQuotas = tierEvictionQuotas;
this.capacityGroupEvictionQuotas = capacityGroupEvictionQuotas;
this.jobEvictionQuotas = jobEvictionQuotas;
this.signature = computeSignature();
}
public String getSnapshotId() {
return snapshotId;
}
public EvictionQuota getSystemEvictionQuota() {
return systemEvictionQuota;
}
public Map<String, EvictionQuota> getQuotas(Level level) {
switch (level) {
case CapacityGroup:
return capacityGroupEvictionQuotas;
case Job:
return jobEvictionQuotas;
case System:
case Tier:
default:
return Collections.emptyMap();
}
}
public EvictionQuota getEvictionQuota(Reference reference) {
switch (reference.getLevel()) {
case System:
return systemEvictionQuota;
case Tier:
return tierEvictionQuotas.get(Tier.valueOf(reference.getName()));
case CapacityGroup:
return capacityGroupEvictionQuotas.computeIfAbsent(reference.getName(), c -> EvictionQuota.newBuilder()
.withReference(Reference.capacityGroup(c))
.withQuota(ReadOnlyEvictionOperations.VERY_HIGH_QUOTA)
.withMessage("Not supported yet")
.build()
);
case Job:
EvictionQuota jobEvictionQuota = jobEvictionQuotas.get(reference.getName());
if (jobEvictionQuota == null) {
throw EvictionException.noQuotaFound(reference);
}
return jobEvictionQuota;
case Task:
throw new IllegalStateException("not implemented yet");
}
throw new IllegalStateException("Unknown reference type: " + reference.getLevel());
}
public Optional<EvictionQuota> findEvictionQuota(Reference reference) {
switch (reference.getLevel()) {
case System:
case Tier:
case CapacityGroup:
return Optional.of(getEvictionQuota(reference));
case Job:
return Optional.ofNullable(jobEvictionQuotas.get(reference.getName()));
case Task:
throw new IllegalStateException("not implemented yet");
}
throw new IllegalStateException("Unknown reference type: " + reference.getLevel());
}
public Optional<EvictionDataSnapshot> updateEvictionQuota(EvictionQuota quota) {
switch (quota.getReference().getLevel()) {
case System:
return Optional.of(new EvictionDataSnapshot(
snapshotId,
quota,
this.tierEvictionQuotas,
this.capacityGroupEvictionQuotas,
jobEvictionQuotas
));
case Tier:
return Optional.of(new EvictionDataSnapshot(
snapshotId,
this.systemEvictionQuota,
copyAndAdd(this.tierEvictionQuotas, ((TierReference) quota.getReference()).getTier(), quota),
this.capacityGroupEvictionQuotas,
jobEvictionQuotas
));
case CapacityGroup:
return Optional.of(new EvictionDataSnapshot(
snapshotId,
this.systemEvictionQuota,
this.tierEvictionQuotas,
copyAndAdd(this.capacityGroupEvictionQuotas, quota.getReference().getName(), quota),
jobEvictionQuotas
));
case Job:
return Optional.of(new EvictionDataSnapshot(
snapshotId,
this.systemEvictionQuota,
this.tierEvictionQuotas,
this.capacityGroupEvictionQuotas,
CollectionsExt.copyAndAdd(jobEvictionQuotas, quota.getReference().getName(), quota)
));
}
return Optional.empty();
}
@Override
public String toSummaryString() {
return signature;
}
@Override
public String toString() {
return "EvictionDataSnapshot{" +
"snapshotId='" + snapshotId + '\'' +
", systemEvictionQuota=" + systemEvictionQuota +
", tierEvictionQuotas=" + tierEvictionQuotas +
", capacityGroupEvictionQuotas=" + capacityGroupEvictionQuotas +
", jobEvictionQuotas=" + jobEvictionQuotas +
'}';
}
private String computeSignature() {
return "EvictionDataSnapshot{snapshotId=" + snapshotId +
", systemEvictionQuota=" + systemEvictionQuota.getQuota() +
", capacityGroupEvictionQuotas=" + capacityGroupEvictionQuotas.size() +
", jobEvictionQuotas=" + jobEvictionQuotas.size() +
"}";
}
public static EvictionDataSnapshot empty() {
return EMPTY;
}
}
| 1,241 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/EvictionConfiguration.java | package com.netflix.titus.runtime.connector.eviction;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Configuration(prefix = "titus.eviction")
public interface EvictionConfiguration {
/**
* Pattern identifying application names that will be exempt from system disruption budget constraints
*/
@DefaultValue("titusOps")
String getAppsExemptFromSystemDisruptionWindow();
}
| 1,242 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/EvictionDataReplicationComponent.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.eviction;
import com.netflix.titus.api.eviction.service.ReadOnlyEvictionOperations;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.runtime.connector.eviction.replicator.EvictionDataReplicatorProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EvictionDataReplicationComponent {
@Bean
public EvictionDataReplicator getEvictionDataReplicator(EvictionServiceClient client, TitusRuntime titusRuntime) {
return new EvictionDataReplicatorProvider(client, titusRuntime).get();
}
@Bean
public ReadOnlyEvictionOperations getReadOnlyEvictionOperations(EvictionDataReplicator replicator) {
return new CachedReadOnlyEvictionOperations(replicator);
}
}
| 1,243 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/replicator/GrpcEvictionReplicatorEventStream.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.eviction.replicator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.titus.api.eviction.model.EvictionQuota;
import com.netflix.titus.api.eviction.model.event.EvictionEvent;
import com.netflix.titus.api.eviction.model.event.EvictionKeepAliveEvent;
import com.netflix.titus.api.eviction.model.event.EvictionQuotaEvent;
import com.netflix.titus.api.eviction.model.event.EvictionSnapshotEndEvent;
import com.netflix.titus.api.eviction.service.ReadOnlyEvictionOperations;
import com.netflix.titus.api.model.Tier;
import com.netflix.titus.api.model.reference.TierReference;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.runtime.connector.common.replicator.AbstractReplicatorEventStream;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicatorMetrics;
import com.netflix.titus.runtime.connector.common.replicator.ReplicatorEvent;
import com.netflix.titus.runtime.connector.eviction.EvictionDataSnapshot;
import com.netflix.titus.runtime.connector.eviction.EvictionServiceClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import static com.google.common.base.Preconditions.checkNotNull;
public class GrpcEvictionReplicatorEventStream extends AbstractReplicatorEventStream<EvictionDataSnapshot, EvictionEvent> {
private static final Logger logger = LoggerFactory.getLogger(GrpcEvictionReplicatorEventStream.class);
private final EvictionServiceClient client;
public GrpcEvictionReplicatorEventStream(EvictionServiceClient client,
DataReplicatorMetrics metrics,
TitusRuntime titusRuntime,
Scheduler scheduler) {
super(false, EvictionKeepAliveEvent.getInstance(), metrics, titusRuntime, scheduler);
this.client = client;
}
@Override
protected Flux<ReplicatorEvent<EvictionDataSnapshot, EvictionEvent>> newConnection() {
return Flux.defer(() -> {
CacheUpdater cacheUpdater = new CacheUpdater();
logger.info("Connecting to the eviction event stream...");
return client.observeEvents(true).flatMap(cacheUpdater::onEvent);
});
}
private class CacheUpdater {
private final List<EvictionEvent> snapshotEvents = new ArrayList<>();
private final AtomicReference<EvictionDataSnapshot> lastSnapshotRef = new AtomicReference<>();
private Flux<ReplicatorEvent<EvictionDataSnapshot, EvictionEvent>> onEvent(EvictionEvent event) {
try {
if (lastSnapshotRef.get() != null) {
return processSnapshotUpdate(event);
}
if (event instanceof EvictionSnapshotEndEvent) {
return buildInitialCache();
}
snapshotEvents.add(event);
} catch (Exception e) {
logger.warn("Unexpected error when handling the agent change notification: {}", event, e);
return Flux.error(e); // Return error to force the cache reconnect.
}
return Flux.empty();
}
private Flux<ReplicatorEvent<EvictionDataSnapshot, EvictionEvent>> buildInitialCache() {
EvictionQuota systemEvictionQuota = null;
Map<Tier, EvictionQuota> tierEvictionQuotas = new HashMap<>();
Map<String, EvictionQuota> capacityGroupEvictionQuotas = new HashMap<>();
Map<String, EvictionQuota> jobEvictionQuotas = new HashMap<>();
for (EvictionEvent event : snapshotEvents) {
if (event instanceof EvictionQuotaEvent) {
EvictionQuota quota = ((EvictionQuotaEvent) event).getQuota();
switch (quota.getReference().getLevel()) {
case System:
systemEvictionQuota = quota;
break;
case Tier:
tierEvictionQuotas.put(((TierReference) quota.getReference()).getTier(), quota);
break;
case CapacityGroup:
capacityGroupEvictionQuotas.put(quota.getReference().getName(), quota);
break;
case Job:
jobEvictionQuotas.put(quota.getReference().getName(), quota);
break;
}
}
}
// Clear so the garbage collector can reclaim the memory (we no longer need this data).
snapshotEvents.clear();
checkNotNull(systemEvictionQuota, "System eviction quota missing");
tierEvictionQuotas.computeIfAbsent(Tier.Flex, tier -> EvictionQuota.tierQuota(tier, ReadOnlyEvictionOperations.VERY_HIGH_QUOTA, "Not supported yet"));
tierEvictionQuotas.computeIfAbsent(Tier.Critical, tier -> EvictionQuota.tierQuota(tier, ReadOnlyEvictionOperations.VERY_HIGH_QUOTA, "Not supported yet"));
EvictionDataSnapshot initialSnapshot = new EvictionDataSnapshot(
UUID.randomUUID().toString(),
systemEvictionQuota,
tierEvictionQuotas,
capacityGroupEvictionQuotas,
jobEvictionQuotas
);
lastSnapshotRef.set(initialSnapshot);
logger.info("Eviction snapshot loaded: {}", initialSnapshot.toSummaryString());
return Flux.just(new ReplicatorEvent<>(initialSnapshot, EvictionSnapshotEndEvent.getInstance(), titusRuntime.getClock().wallTime()));
}
private Flux<ReplicatorEvent<EvictionDataSnapshot, EvictionEvent>> processSnapshotUpdate(EvictionEvent event) {
logger.debug("Processing eviction snapshot update event: {}", event);
EvictionDataSnapshot snapshot = lastSnapshotRef.get();
Optional<EvictionDataSnapshot> newSnapshot = Optional.empty();
if (event instanceof EvictionQuotaEvent) {
newSnapshot = snapshot.updateEvictionQuota(((EvictionQuotaEvent) event).getQuota());
} // Ignore all other events, as they are not relevant for snapshot
if (newSnapshot.isPresent()) {
lastSnapshotRef.set(newSnapshot.get());
return Flux.just(new ReplicatorEvent<>(newSnapshot.get(), event, titusRuntime.getClock().wallTime()));
}
return Flux.empty();
}
}
}
| 1,244 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/connector/eviction/replicator/EvictionDataReplicatorProvider.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.runtime.connector.eviction.replicator;
import java.time.Duration;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import com.netflix.titus.api.eviction.model.event.EvictionEvent;
import com.netflix.titus.api.model.Level;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.ExceptionExt;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicator;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicatorDelegate;
import com.netflix.titus.runtime.connector.common.replicator.DataReplicatorMetrics;
import com.netflix.titus.runtime.connector.common.replicator.ReplicatorEvent;
import com.netflix.titus.runtime.connector.common.replicator.RetryableReplicatorEventStream;
import com.netflix.titus.runtime.connector.common.replicator.StreamDataReplicator;
import com.netflix.titus.runtime.connector.eviction.EvictionDataReplicator;
import com.netflix.titus.runtime.connector.eviction.EvictionDataSnapshot;
import com.netflix.titus.runtime.connector.eviction.EvictionServiceClient;
import reactor.core.scheduler.Schedulers;
@Singleton
public class EvictionDataReplicatorProvider implements Provider<EvictionDataReplicator> {
private static final String EVICTION_REPLICATOR = "evictionReplicator";
private static final String EVICTION_REPLICATOR_RETRYABLE_STREAM = "evictionReplicatorRetryableStream";
private static final String EVICTION_REPLICATOR_GRPC_STREAM = "evictionReplicatorGrpcStream";
private static final long EVICTION_BOOTSTRAP_TIMEOUT_MS = 120_000;
private final EvictionDataReplicatorImpl replicator;
@Inject
public EvictionDataReplicatorProvider(EvictionServiceClient client, TitusRuntime titusRuntime) {
StreamDataReplicator<EvictionDataSnapshot, EvictionEvent> original = StreamDataReplicator.newStreamDataReplicator(
newReplicatorEventStream(client, titusRuntime),
false,
new EvictionDataReplicatorMetrics(EVICTION_REPLICATOR, titusRuntime),
titusRuntime
).blockFirst(Duration.ofMillis(EVICTION_BOOTSTRAP_TIMEOUT_MS));
this.replicator = new EvictionDataReplicatorImpl(original);
}
@PreDestroy
public void shutdown() {
ExceptionExt.silent(replicator::close);
}
@Override
public EvictionDataReplicator get() {
return replicator;
}
private static RetryableReplicatorEventStream<EvictionDataSnapshot, EvictionEvent> newReplicatorEventStream(EvictionServiceClient client, TitusRuntime titusRuntime) {
GrpcEvictionReplicatorEventStream grpcEventStream = new GrpcEvictionReplicatorEventStream(
client,
new EvictionDataReplicatorMetrics(EVICTION_REPLICATOR_GRPC_STREAM, titusRuntime),
titusRuntime,
Schedulers.parallel()
);
return new RetryableReplicatorEventStream<>(
grpcEventStream,
new EvictionDataReplicatorMetrics(EVICTION_REPLICATOR_RETRYABLE_STREAM, titusRuntime),
titusRuntime,
Schedulers.parallel()
);
}
private static class EvictionDataReplicatorImpl extends DataReplicatorDelegate<EvictionDataSnapshot, EvictionEvent> implements EvictionDataReplicator {
EvictionDataReplicatorImpl(DataReplicator<EvictionDataSnapshot, EvictionEvent> delegate) {
super(delegate);
}
}
private static class EvictionDataReplicatorMetrics extends DataReplicatorMetrics<EvictionDataSnapshot, EvictionEvent> {
private EvictionDataReplicatorMetrics(String source, TitusRuntime titusRuntime) {
super(source, false, titusRuntime);
}
@Override
public void event(ReplicatorEvent<EvictionDataSnapshot, EvictionEvent> event) {
super.event(event);
setCacheCollectionSize("capacityGroups", event.getSnapshot().getQuotas(Level.CapacityGroup).size());
setCacheCollectionSize("jobs", event.getSnapshot().getQuotas(Level.Job).size());
}
}
}
| 1,245 |
0 | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/eviction/endpoint | Create_ds/titus-control-plane/titus-client/src/main/java/com/netflix/titus/runtime/eviction/endpoint/grpc/GrpcEvictionModelConverters.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.eviction.endpoint.grpc;
import java.time.Duration;
import java.util.Optional;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.netflix.titus.api.eviction.model.event.EvictionEvent;
import com.netflix.titus.api.eviction.model.event.EvictionQuotaEvent;
import com.netflix.titus.api.eviction.model.event.EvictionSnapshotEndEvent;
import com.netflix.titus.api.eviction.model.event.TaskTerminationEvent;
import com.netflix.titus.api.eviction.service.EvictionException;
import com.netflix.titus.api.model.Tier;
import com.netflix.titus.api.model.reference.TierReference;
import com.netflix.titus.grpc.protogen.EvictionQuota;
import com.netflix.titus.grpc.protogen.EvictionServiceEvent;
import com.netflix.titus.grpc.protogen.Reference;
public final class GrpcEvictionModelConverters {
private static final LoadingCache<com.netflix.titus.api.model.reference.Reference, Reference> CORE_TO_GRPC_REFERENCE_CACHE = Caffeine.newBuilder()
.expireAfterWrite(Duration.ofHours(1))
.build(coreReference -> {
switch (coreReference.getLevel()) {
case System:
return Reference.newBuilder().setSystem(Reference.System.getDefaultInstance()).build();
case Tier:
return Reference.newBuilder().setTier(toGrpcTier(((TierReference) coreReference).getTier())).build();
case CapacityGroup:
return Reference.newBuilder().setCapacityGroup(coreReference.getName()).build();
case Job:
case Task:
default:
}
throw new IllegalArgumentException("not implemented yet");
});
private GrpcEvictionModelConverters() {
}
public static com.netflix.titus.api.model.reference.Reference toCoreReference(Reference grpcEntity) {
switch (grpcEntity.getReferenceCase()) {
case SYSTEM:
return com.netflix.titus.api.model.reference.Reference.system();
case TIER:
return com.netflix.titus.api.model.reference.Reference.tier(toCoreTier(grpcEntity.getTier()));
case CAPACITYGROUP:
return com.netflix.titus.api.model.reference.Reference.capacityGroup(grpcEntity.getCapacityGroup());
case JOBID:
return com.netflix.titus.api.model.reference.Reference.job(grpcEntity.getJobId());
case TASKID:
return com.netflix.titus.api.model.reference.Reference.task(grpcEntity.getTaskId());
case REFERENCE_NOT_SET:
}
throw new IllegalArgumentException("No mapping for: " + grpcEntity);
}
public static Reference toGrpcReference(com.netflix.titus.api.model.reference.Reference coreReference) {
switch (coreReference.getLevel()) {
case System:
case Tier:
case CapacityGroup:
return CORE_TO_GRPC_REFERENCE_CACHE.get(coreReference);
case Job:
return Reference.newBuilder().setJobId(coreReference.getName()).build();
case Task:
return Reference.newBuilder().setTaskId(coreReference.getName()).build();
}
throw new IllegalArgumentException("No GRPC mapping for: " + coreReference);
}
public static com.netflix.titus.api.eviction.model.EvictionQuota toCoreEvictionQuota(EvictionQuota grpcEntity) {
return com.netflix.titus.api.eviction.model.EvictionQuota.newBuilder()
.withReference(toCoreReference(grpcEntity.getTarget()))
.withQuota(grpcEntity.getQuota())
.withMessage(grpcEntity.getMessage())
.build();
}
public static EvictionQuota toGrpcEvictionQuota(com.netflix.titus.api.eviction.model.EvictionQuota evictionQuota) {
return EvictionQuota.newBuilder()
.setTarget(toGrpcReference(evictionQuota.getReference()))
.setQuota((int) evictionQuota.getQuota())
.setMessage(evictionQuota.getMessage())
.build();
}
public static EvictionEvent toCoreEvent(EvictionServiceEvent grpcEvent) {
switch (grpcEvent.getEventCase()) {
case SNAPSHOTEND:
return EvictionEvent.newSnapshotEndEvent();
case EVICTIONQUOTAEVENT:
return EvictionEvent.newQuotaEvent(toCoreEvictionQuota(grpcEvent.getEvictionQuotaEvent().getQuota()));
case TASKTERMINATIONEVENT:
EvictionServiceEvent.TaskTerminationEvent taskTermination = grpcEvent.getTaskTerminationEvent();
if (taskTermination.getApproved()) {
return EvictionEvent.newSuccessfulTaskTerminationEvent(taskTermination.getTaskId(), taskTermination.getReason());
}
return EvictionEvent.newFailedTaskTerminationEvent(
taskTermination.getTaskId(),
taskTermination.getReason(),
EvictionException.deconstruct(taskTermination.getRestrictionCode(), taskTermination.getRestrictionMessage())
);
case EVENT_NOT_SET:
}
throw new IllegalArgumentException("No mapping for: " + grpcEvent);
}
public static Optional<EvictionServiceEvent> toGrpcEvent(EvictionEvent coreEvent) {
if (coreEvent instanceof EvictionSnapshotEndEvent) {
EvictionServiceEvent grpcEvent = EvictionServiceEvent.newBuilder()
.setSnapshotEnd(EvictionServiceEvent.SnapshotEnd.getDefaultInstance())
.build();
return Optional.of(grpcEvent);
}
if (coreEvent instanceof EvictionQuotaEvent) {
EvictionQuotaEvent actualEvent = (EvictionQuotaEvent) coreEvent;
EvictionServiceEvent grpcEvent = EvictionServiceEvent.newBuilder()
.setEvictionQuotaEvent(EvictionServiceEvent.EvictionQuotaEvent.newBuilder()
.setQuota(toGrpcEvictionQuota(actualEvent.getQuota()))
.build()
)
.build();
return Optional.of(grpcEvent);
}
if (coreEvent instanceof TaskTerminationEvent) {
TaskTerminationEvent actualEvent = (TaskTerminationEvent) coreEvent;
EvictionServiceEvent.TaskTerminationEvent.Builder eventBuilder = EvictionServiceEvent.TaskTerminationEvent.newBuilder()
.setTaskId(actualEvent.getTaskId())
.setApproved(actualEvent.isApproved());
if (!actualEvent.isApproved()) {
Throwable error = actualEvent.getError().get();
if (error instanceof EvictionException) {
EvictionException evictionException = (EvictionException) error;
eventBuilder.setRestrictionCode("" + evictionException.getErrorCode());
} else {
eventBuilder.setRestrictionCode("" + EvictionException.ErrorCode.Unknown);
}
eventBuilder.setRestrictionMessage(error.getMessage());
}
EvictionServiceEvent grpcEvent = EvictionServiceEvent.newBuilder().setTaskTerminationEvent(eventBuilder.build()).build();
return Optional.of(grpcEvent);
}
return Optional.empty();
}
public static Tier toCoreTier(com.netflix.titus.grpc.protogen.Tier grpcTier) {
switch (grpcTier) {
case Flex:
return Tier.Flex;
case Critical:
return Tier.Critical;
}
return Tier.Flex; // Default to flex
}
public static com.netflix.titus.grpc.protogen.Tier toGrpcTier(Tier tier) {
switch (tier) {
case Critical:
return com.netflix.titus.grpc.protogen.Tier.Critical;
case Flex:
return com.netflix.titus.grpc.protogen.Tier.Flex;
}
throw new IllegalArgumentException("Unrecognized Tier value: " + tier);
}
}
| 1,246 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/activation/LeaderActivationCoordinatorTest.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.clustermembership.activation;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.titus.api.common.LeaderActivationListener;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.runtime.TitusRuntimes;
import com.netflix.titus.common.util.Evaluators;
import com.netflix.titus.common.util.archaius2.Archaius2Ext;
import com.netflix.titus.runtime.clustermembership.endpoint.grpc.ClusterMembershipServiceStub;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Flux;
import static com.jayway.awaitility.Awaitility.await;
public class LeaderActivationCoordinatorTest {
private final TitusRuntime titusRuntime = TitusRuntimes.internal();
private final LeaderActivationConfiguration configuration = Archaius2Ext.newConfiguration(
LeaderActivationConfiguration.class,
"leaderCheckIntervalMs", "1"
);
private final ClusterMembershipServiceStub membershipServiceStub = new ClusterMembershipServiceStub();
private final TestableService testableService = new TestableService();
private final AtomicReference<Throwable> errorCallback = new AtomicReference<>();
private LeaderActivationCoordinator coordinator;
@Before
public void setUp() {
this.coordinator = new LeaderActivationCoordinator(
configuration,
Collections.singletonList(testableService),
errorCallback::set,
membershipServiceStub,
titusRuntime
);
}
@After
public void tearDown() {
Evaluators.acceptNotNull(coordinator, LeaderActivationCoordinator::shutdown);
}
@Test(timeout = 30_000)
public void testActivation() {
await().until(() -> testableService.activationCount.get() > 0);
membershipServiceStub.stopBeingLeader().block();
await().until(() -> testableService.deactivationCount.get() > 0);
}
private class TestableService implements LeaderActivationListener {
private final AtomicInteger activationCount = new AtomicInteger();
private final AtomicInteger deactivationCount = new AtomicInteger();
@Override
public void activate() {
// Make sure we can block in the activation process.
Flux.interval(Duration.ofMillis(1)).take(1).blockFirst();
activationCount.getAndIncrement();
}
@Override
public void deactivate() {
deactivationCount.getAndIncrement();
}
}
} | 1,247 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/endpoint/grpc/GrpcLeaderServerInterceptorTest.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.clustermembership.endpoint.grpc;
import com.netflix.titus.grpc.protogen.ClusterMembershipServiceGrpc;
import com.netflix.titus.testing.SampleServiceGrpc;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServiceDescriptor;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class GrpcLeaderServerInterceptorTest {
private static final Metadata METADATA = new Metadata();
private final ServerCallHandler serverCallHandler = mock(ServerCallHandler.class);
@Test
public void testClusterMembershipMethodIsAllowed() {
testIsCallAllowed(
GrpcLeaderServerInterceptor.clusterMembershipAllowed(() -> false),
newServerCall(getMethod(ClusterMembershipServiceGrpc.getServiceDescriptor(), "GetMembers"))
);
}
@Test
public void testBusinessMethodIsNotAllowed() {
testIsNotCallAllowed(
GrpcLeaderServerInterceptor.clusterMembershipAllowed(() -> false),
newServerCall(getMethod(SampleServiceGrpc.getServiceDescriptor(), "GetOneValue"))
);
}
@Test
public void testActiveLeaderIsAlwaysAllowed() {
testIsCallAllowed(
GrpcLeaderServerInterceptor.clusterMembershipAllowed(() -> true),
newServerCall(getMethod(ClusterMembershipServiceGrpc.getServiceDescriptor(), "GetMembers"))
);
testIsCallAllowed(
GrpcLeaderServerInterceptor.clusterMembershipAllowed(() -> true),
newServerCall(getMethod(SampleServiceGrpc.getServiceDescriptor(), "GetOneValue"))
);
}
private ServerCall newServerCall(MethodDescriptor<Object, Object> methodDescriptor) {
ServerCall<Object, Object> serverCall = mock(ServerCall.class);
when(serverCall.getMethodDescriptor()).thenReturn(methodDescriptor);
return serverCall;
}
private void testIsCallAllowed(GrpcLeaderServerInterceptor interceptor, ServerCall serverCall) {
interceptor.interceptCall(serverCall, METADATA, serverCallHandler);
verify(serverCallHandler, times(1)).startCall(serverCall, METADATA);
}
private void testIsNotCallAllowed(GrpcLeaderServerInterceptor interceptor, ServerCall serverCall) {
interceptor.interceptCall(serverCall, METADATA, serverCallHandler);
verify(serverCallHandler, times(0)).startCall(serverCall, METADATA);
verify(serverCall, times(1)).close(any(), any());
}
private MethodDescriptor getMethod(ServiceDescriptor serviceDescriptor, String methodName) {
MethodDescriptor<?, ?> methodDescriptor = serviceDescriptor.getMethods().stream()
.filter(m -> m.getFullMethodName().contains(methodName))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Method not found: " + methodName));
// Rebuild to get a different version
return methodDescriptor.toBuilder().build();
}
} | 1,248 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/endpoint/grpc/ClusterMembershipServiceStub.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.clustermembership.endpoint.grpc;
import java.util.Collections;
import java.util.HashMap;
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.ClusterMemberLeadershipState;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipSnapshotEvent;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipService;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.rx.ReactorExt;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import static com.netflix.titus.testkit.model.clustermembership.ClusterMemberGenerator.activeClusterMember;
import static com.netflix.titus.testkit.model.clustermembership.ClusterMemberGenerator.clusterMemberRegistrationRevision;
public class ClusterMembershipServiceStub implements ClusterMembershipService {
static final String LOCAL_MEMBER_ID = "local";
static final ClusterMembershipRevision<ClusterMemberLeadership> INITIAL_LOCAL_LEADERSHIP =
com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder()
.withCurrent(ClusterMemberLeadership.newBuilder()
.withMemberId(LOCAL_MEMBER_ID)
.withLeadershipState(ClusterMemberLeadershipState.Leader)
.build()
)
.build();
static final ClusterMembershipRevision<ClusterMember> LOCAL_MEMBER = clusterMemberRegistrationRevision(activeClusterMember(LOCAL_MEMBER_ID));
static final ClusterMembershipRevision<ClusterMember> SIBLING_1 = clusterMemberRegistrationRevision(activeClusterMember("sibling1"));
static final ClusterMembershipRevision<ClusterMember> SIBLING_2 = clusterMemberRegistrationRevision(activeClusterMember("sibling2"));
private volatile ClusterMembershipRevision<ClusterMember> localMember;
private volatile ClusterMembershipRevision<ClusterMemberLeadership> localLeadership;
private volatile Map<String, ClusterMembershipRevision<ClusterMember>> siblings;
private volatile ClusterMembershipRevision<ClusterMemberLeadership> siblingElection;
private final Sinks.Many<ClusterMembershipEvent> eventProcessor = Sinks.many().multicast().directAllOrNothing();
public ClusterMembershipServiceStub() {
this.localMember = LOCAL_MEMBER;
this.localLeadership = INITIAL_LOCAL_LEADERSHIP;
this.siblings = new HashMap<>();
siblings.put("sibling1", SIBLING_1);
siblings.put("sibling2", SIBLING_2);
}
@Override
public ClusterMembershipRevision<ClusterMember> getLocalClusterMember() {
return localMember;
}
@Override
public Map<String, ClusterMembershipRevision<ClusterMember>> getClusterMemberSiblings() {
return siblings;
}
@Override
public ClusterMembershipRevision<ClusterMemberLeadership> getLocalLeadership() {
return localLeadership;
}
@Override
public Optional<ClusterMembershipRevision<ClusterMemberLeadership>> findLeader() {
if (localLeadership.getCurrent().getLeadershipState() == ClusterMemberLeadershipState.Leader) {
return Optional.of(localLeadership);
}
if (siblingElection != null && siblingElection.getCurrent().getLeadershipState() == ClusterMemberLeadershipState.Leader) {
return Optional.of(siblingElection);
}
return Optional.empty();
}
@Override
public Mono<ClusterMembershipRevision<ClusterMember>> updateSelf(Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> memberUpdate) {
return Mono.fromCallable(() -> {
this.localMember = memberUpdate.apply(localMember.getCurrent());
eventProcessor.tryEmitNext(ClusterMembershipEvent.memberUpdatedEvent(localMember));
return localMember;
});
}
@Override
public Mono<Void> stopBeingLeader() {
return Mono.fromRunnable(() -> {
if (localLeadership.getCurrent().getLeadershipState() != ClusterMemberLeadershipState.Leader) {
return;
}
// Move local to non-leader
this.localLeadership = ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder()
.withCurrent(localLeadership.getCurrent().toBuilder().withLeadershipState(ClusterMemberLeadershipState.NonLeader).build())
.build();
eventProcessor.tryEmitNext(ClusterMembershipEvent.leaderLost(localLeadership));
// Elect new leader
ClusterMembershipRevision<ClusterMember> sibling = CollectionsExt.first(siblings.values());
this.siblingElection = ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder()
.withCurrent(ClusterMemberLeadership.newBuilder()
.withMemberId(sibling.getCurrent().getMemberId())
.withLeadershipState(ClusterMemberLeadershipState.Leader)
.build()
)
.build();
eventProcessor.tryEmitNext(ClusterMembershipEvent.leaderElected(siblingElection));
});
}
@Override
public Flux<ClusterMembershipEvent> events() {
return eventProcessor.asFlux().transformDeferred(ReactorExt.head(() -> {
ClusterMembershipSnapshotEvent snapshot = ClusterMembershipEvent.snapshotEvent(
CollectionsExt.copyAndAddToList(siblings.values(), localMember),
localLeadership,
Optional.of(localLeadership)
);
return Collections.singletonList(snapshot);
}));
}
}
| 1,249 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/endpoint/grpc/ClusterMembershipServerResource.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.clustermembership.endpoint.grpc;
import java.time.Duration;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipService;
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.archaius2.Archaius2Ext;
import com.netflix.titus.runtime.clustermembership.DefaultClusterMembershipClient;
import com.netflix.titus.runtime.connector.GrpcRequestConfiguration;
import com.netflix.titus.runtime.endpoint.common.grpc.CommonGrpcEndpointConfiguration;
import com.netflix.titus.runtime.endpoint.common.grpc.TitusGrpcServer;
import com.netflix.titus.runtime.endpoint.common.grpc.assistant.DefaultGrpcClientCallAssistantFactory;
import com.netflix.titus.runtime.endpoint.common.grpc.assistant.DefaultGrpcServerCallAssistant;
import com.netflix.titus.runtime.endpoint.common.grpc.assistant.GrpcCallAssistantConfiguration;
import com.netflix.titus.runtime.endpoint.metadata.AnonymousCallMetadataResolver;
import com.netflix.titus.runtime.endpoint.resolver.NoOpHostCallerIdResolver;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.junit.rules.ExternalResource;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ClusterMembershipServerResource extends ExternalResource {
private final TitusRuntime titusRuntime = TitusRuntimes.internal();
private final CommonGrpcEndpointConfiguration grpcEndpointConfiguration = mock(CommonGrpcEndpointConfiguration.class);
private final GrpcRequestConfiguration grpcRequestConfiguration = Archaius2Ext.newConfiguration(GrpcRequestConfiguration.class);
private final ClusterMembershipService service;
private TitusGrpcServer server;
private ManagedChannel channel;
private ClusterMembershipClient client;
public ClusterMembershipServerResource(ClusterMembershipService service) {
this.service = service;
}
@Override
protected void before() {
when(grpcEndpointConfiguration.getPort()).thenReturn(0);
DefaultGrpcServerCallAssistant grpcServerCallAssistant = new DefaultGrpcServerCallAssistant(AnonymousCallMetadataResolver.getInstance(), NoOpHostCallerIdResolver.getInstance());
server = TitusGrpcServer.newBuilder(0, titusRuntime)
.withServerConfigurer(builder ->
builder.addService(new GrpcClusterMembershipService(service, grpcServerCallAssistant, titusRuntime))
)
.withExceptionMapper(ClusterMembershipGrpcExceptionMapper.getInstance())
.withShutdownTime(Duration.ZERO)
.build();
server.start();
this.channel = ManagedChannelBuilder.forAddress("localhost", server.getPort())
.usePlaintext()
.build();
GrpcCallAssistantConfiguration configuration = Archaius2Ext.newConfiguration(GrpcCallAssistantConfiguration.class);
DefaultGrpcClientCallAssistantFactory grpcClientCallAssistantFactory = new DefaultGrpcClientCallAssistantFactory(
configuration, AnonymousCallMetadataResolver.getInstance()
);
this.client = new DefaultClusterMembershipClient(grpcClientCallAssistantFactory, channel);
}
@Override
protected void after() {
if (server != null) {
server.shutdown();
channel.shutdownNow();
}
}
public ClusterMembershipClient getClient() {
return client;
}
public ClusterMembershipService getService() {
return service;
}
}
| 1,250 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/endpoint/grpc/ClusterMembershipGrpcServerTest.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.clustermembership.endpoint.grpc;
import java.time.Duration;
import java.util.function.Consumer;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipService;
import com.netflix.titus.client.clustermembership.grpc.ClusterMembershipClient;
import com.netflix.titus.grpc.protogen.ClusterMember;
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.DeleteMemberLabelsRequest;
import com.netflix.titus.grpc.protogen.EnableMemberRequest;
import com.netflix.titus.grpc.protogen.MemberId;
import com.netflix.titus.grpc.protogen.UpdateMemberLabelsRequest;
import com.netflix.titus.testkit.rx.TitusRxSubscriber;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ClusterMembershipGrpcServerTest {
private static final Duration TIMEOUT = Duration.ofSeconds(30);
private final ClusterMembershipService service = new ClusterMembershipServiceStub();
@Rule
public final ClusterMembershipServerResource serverResource = new ClusterMembershipServerResource(service);
private final TitusRxSubscriber<ClusterMembershipEvent> eventSubscriber = new TitusRxSubscriber<>();
private ClusterMembershipClient client;
@Before
public void setUp() {
this.client = serverResource.getClient();
client.events().subscribe(eventSubscriber);
}
@Test(timeout = 30_000)
public void testGetMember() {
ClusterMembershipRevision result = client.getMember(MemberId.newBuilder().setId("local").build()).block();
assertThat(result).isNotNull();
assertThat(result.getCurrent().getMemberId()).isEqualTo(ClusterMembershipServiceStub.LOCAL_MEMBER.getCurrent().getMemberId());
}
@Test(timeout = 30_000)
public void testGetMembers() {
ClusterMembershipRevisions result = client.getMembers().block();
assertThat(result).isNotNull();
assertThat(result.getRevisionsCount()).isEqualTo(3);
}
@Test(timeout = 30_000)
public void testUpdateAndRemoveLabel() throws InterruptedException {
checkSnapshotEvent();
// Add label
ClusterMembershipRevision addResult = client.updateMemberLabels(UpdateMemberLabelsRequest.newBuilder()
.setMemberId(ClusterMembershipServiceStub.LOCAL_MEMBER_ID)
.putLabels("keyA", "valueA")
.build()
).block();
assertThat(addResult).isNotNull();
assertThat(addResult.getCurrent().getLabelsMap()).containsEntry("keyA", "valueA");
expectMemberUpdateEvent(update -> assertThat(update.getLabelsMap()).containsEntry("keyA", "valueA"));
// Remove label
ClusterMembershipRevision removeResult = client.deleteMemberLabels(DeleteMemberLabelsRequest.newBuilder()
.setMemberId(ClusterMembershipServiceStub.LOCAL_MEMBER_ID)
.addKeys("keyA")
.build()
).block();
assertThat(removeResult).isNotNull();
assertThat(removeResult.getCurrent().getLabelsMap()).doesNotContainKeys("keyA");
expectMemberUpdateEvent(update -> assertThat(update.getLabelsMap()).doesNotContainKeys("keyA"));
}
@Test
public void testEnableLocalMember() throws InterruptedException {
checkSnapshotEvent();
// Started enabled, so disable first
ClusterMembershipRevision disabledResult = client.enableMember(
EnableMemberRequest.newBuilder().setMemberId(ClusterMembershipServiceStub.LOCAL_MEMBER_ID).setEnabled(false).build()
).block();
assertThat(disabledResult.getCurrent().getEnabled()).isFalse();
expectMemberUpdateEvent(update -> assertThat(update.getEnabled()).isFalse());
// Now enable again
ClusterMembershipRevision enabledResult = client.enableMember(
EnableMemberRequest.newBuilder().setMemberId(ClusterMembershipServiceStub.LOCAL_MEMBER_ID).setEnabled(true).build()
).block();
assertThat(enabledResult.getCurrent().getEnabled()).isTrue();
expectMemberUpdateEvent(update -> assertThat(update.getEnabled()).isTrue());
}
@Test
public void testLeaderFailover() throws InterruptedException {
checkSnapshotEvent();
client.stopBeingLeader().block();
expectMemberUpdateEvent(local -> {
assertThat(local.getMemberId()).isEqualTo(ClusterMembershipServiceStub.LOCAL_MEMBER_ID);
assertThat(local.getLeadershipState()).isEqualTo(ClusterMember.LeadershipState.NonLeader);
});
expectMemberUpdateEvent(sibling -> {
assertThat(sibling.getMemberId()).startsWith("sibling");
assertThat(sibling.getLeadershipState()).isEqualTo(ClusterMember.LeadershipState.Leader);
});
}
private void checkSnapshotEvent() throws InterruptedException {
ClusterMembershipEvent event = eventSubscriber.takeNext(TIMEOUT);
assertThat(event.getEventCase()).isEqualTo(ClusterMembershipEvent.EventCase.SNAPSHOT);
}
private void expectMemberUpdateEvent(Consumer<ClusterMember> assertion) throws InterruptedException {
ClusterMembershipEvent event = eventSubscriber.takeNext(TIMEOUT);
assertThat(event.getEventCase()).isEqualTo(ClusterMembershipEvent.EventCase.MEMBERUPDATED);
assertion.accept(event.getMemberUpdated().getRevision().getCurrent());
}
} | 1,251 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/service/ClusterMembershipTransactionLoggerTest.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.clustermembership.service;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent;
import org.junit.Test;
import static com.netflix.titus.testkit.model.clustermembership.ClusterMemberGenerator.activeClusterMember;
import static com.netflix.titus.testkit.model.clustermembership.ClusterMemberGenerator.clusterMemberRegistrationRevision;
import static org.assertj.core.api.Assertions.assertThat;
public class ClusterMembershipTransactionLoggerTest {
@Test
public void testMemberChangeEventLogging() {
ClusterMembershipRevision<ClusterMember> revision = clusterMemberRegistrationRevision(activeClusterMember("local"));
String value = ClusterMembershipTransactionLogger.doFormat(ClusterMembershipEvent.memberAddedEvent(revision));
assertThat(value).isEqualTo("eventType=[membership] memberId=local active=true registered=true enabled=true memberRevision=0 leadershipState=n/a leadershipRevision=n/a");
}
@Test
public void testLeadershipChangeEventLogging() {
ClusterMembershipRevision<ClusterMemberLeadership> revision = ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder()
.withCurrent(ClusterMemberLeadership.newBuilder()
.withMemberId("local")
.withLeadershipState(ClusterMemberLeadershipState.Leader)
.build()
)
.build();
String value = ClusterMembershipTransactionLogger.doFormat(ClusterMembershipEvent.leaderElected(revision));
assertThat(value).isEqualTo("eventType=[leadership] memberId=local active=n/a registered=n/a enabled=n/a memberRevision=n/a leadershipState=Leader leadershipRevision=0");
}
} | 1,252 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/service/ClusterMembershipConnectorStub.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.clustermembership.service;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import com.netflix.titus.api.clustermembership.connector.ClusterMembershipConnector;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipSnapshotEvent;
import com.netflix.titus.common.util.rx.ReactorExt;
import com.netflix.titus.testkit.model.clustermembership.ClusterMemberGenerator;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
class ClusterMembershipConnectorStub implements ClusterMembershipConnector {
private static final String LOCAL_MEMBER_ID = "localMember";
private volatile ClusterMembershipRevision<ClusterMember> localMemberRevision;
private volatile ClusterMembershipRevision<ClusterMemberLeadership> localLeadershipRevision;
private final Sinks.Many<ClusterMembershipEvent> eventProcessor = Sinks.many().multicast().directAllOrNothing();
ClusterMembershipConnectorStub() {
this.localMemberRevision = ClusterMembershipRevision.<ClusterMember>newBuilder()
.withCurrent(ClusterMemberGenerator.activeClusterMember(LOCAL_MEMBER_ID).toBuilder()
.withRegistered(true)
.build()
)
.build();
this.localLeadershipRevision = ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder()
.withCurrent(ClusterMemberLeadership.newBuilder()
.withMemberId(LOCAL_MEMBER_ID)
.withLeadershipState(ClusterMemberLeadershipState.Disabled)
.build()
)
.build();
}
@Override
public ClusterMembershipRevision<ClusterMember> getLocalClusterMemberRevision() {
return localMemberRevision;
}
@Override
public Map<String, ClusterMembershipRevision<ClusterMember>> getClusterMemberSiblings() {
throw new IllegalStateException("not implemented yet");
}
@Override
public ClusterMembershipRevision<ClusterMemberLeadership> getLocalLeadershipRevision() {
return localLeadershipRevision;
}
@Override
public Optional<ClusterMembershipRevision<ClusterMemberLeadership>> findCurrentLeader() {
return localLeadershipRevision.getCurrent().getLeadershipState() == ClusterMemberLeadershipState.Leader
? Optional.of(localLeadershipRevision)
: Optional.empty();
}
@Override
public Mono<ClusterMembershipRevision<ClusterMember>> register(Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> selfUpdate) {
return Mono.fromCallable(() -> {
this.localMemberRevision = selfUpdate.apply(localMemberRevision.getCurrent());
emitEvent(ClusterMembershipEvent.memberUpdatedEvent(localMemberRevision));
return localMemberRevision;
});
}
@Override
public Mono<ClusterMembershipRevision<ClusterMember>> unregister(Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> selfUpdate) {
throw new IllegalStateException("not implemented yet");
}
@Override
public Mono<Void> joinLeadershipGroup() {
return Mono.defer(() -> {
ClusterMemberLeadershipState state = localLeadershipRevision.getCurrent().getLeadershipState();
if (state == ClusterMemberLeadershipState.Disabled) {
this.localLeadershipRevision = newLocalLeadershipState(ClusterMemberLeadershipState.NonLeader);
}
emitEvent(ClusterMembershipEvent.localJoinedElection(localLeadershipRevision));
return Mono.empty();
});
}
@Override
public Mono<Boolean> leaveLeadershipGroup(boolean onlyNonLeader) {
return Mono.defer(() -> {
ClusterMemberLeadershipState state = localLeadershipRevision.getCurrent().getLeadershipState();
if (state == ClusterMemberLeadershipState.Disabled) {
return Mono.just(true);
}
if (onlyNonLeader && state == ClusterMemberLeadershipState.Leader) {
return Mono.just(false);
}
this.localLeadershipRevision = newLocalLeadershipState(ClusterMemberLeadershipState.Disabled);
emitEvent(ClusterMembershipEvent.localLeftElection(localLeadershipRevision));
return Mono.just(true);
});
}
@Override
public Flux<ClusterMembershipEvent> membershipChangeEvents() {
return eventProcessor.asFlux().transformDeferred(ReactorExt.head(() -> {
ClusterMembershipSnapshotEvent snapshot = ClusterMembershipEvent.snapshotEvent(Collections.emptyList(), localLeadershipRevision, Optional.empty());
return Collections.singletonList(snapshot);
}));
}
void becomeLeader() {
this.localLeadershipRevision = newLocalLeadershipState(ClusterMemberLeadershipState.Leader);
emitEvent(ClusterMembershipEvent.localJoinedElection(localLeadershipRevision));
}
private ClusterMembershipRevision<ClusterMemberLeadership> newLocalLeadershipState(ClusterMemberLeadershipState state) {
return localLeadershipRevision.toBuilder()
.withCurrent(localLeadershipRevision.getCurrent().toBuilder()
.withLeadershipState(state)
.build()
)
.build();
}
private void emitEvent(ClusterMembershipEvent event) {
synchronized (eventProcessor) {
eventProcessor.tryEmitNext(event);
}
}
}
| 1,253 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/clustermembership/service/DefaultClusterMembershipServiceTest.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.clustermembership.service;
import java.time.Duration;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipChangeEvent;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipSnapshotEvent;
import com.netflix.titus.api.clustermembership.model.event.LeaderElectionChangeEvent;
import com.netflix.titus.api.health.HealthIndicator;
import com.netflix.titus.api.health.HealthState;
import com.netflix.titus.api.health.HealthStatus;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.runtime.TitusRuntimes;
import com.netflix.titus.testkit.rx.TitusRxSubscriber;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DefaultClusterMembershipServiceTest {
private static final Duration TIMEOUT = Duration.ofSeconds(5);
private static final boolean ACTIVE = true;
private static final boolean INACTIVE = false;
private static final HealthStatus HEALTHY = HealthStatus.newBuilder().withHealthState(HealthState.Healthy).build();
private static final HealthStatus UNHEALTHY = HealthStatus.newBuilder().withHealthState(HealthState.Unhealthy).build();
private final TitusRuntime titusRuntime = TitusRuntimes.internal();
private final ClusterMembershipServiceConfiguration configuration = mock(ClusterMembershipServiceConfiguration.class);
private final HealthIndicator healthIndicator = mock(HealthIndicator.class);
private ClusterMembershipConnectorStub connector = new ClusterMembershipConnectorStub();
private final TitusRxSubscriber<ClusterMembershipEvent> eventSubscriber = new TitusRxSubscriber<>();
private DefaultClusterMembershipService service;
@Before
public void setUp() throws InterruptedException {
when(configuration.getHealthCheckEvaluationIntervalMs()).thenReturn(1L);
when(configuration.getHealthCheckEvaluationTimeoutMs()).thenReturn(1_000L);
when(configuration.isLeaderElectionEnabled()).thenReturn(true);
when(healthIndicator.health()).thenReturn(HEALTHY);
service = new DefaultClusterMembershipService(configuration, connector, healthIndicator, titusRuntime);
service.events().subscribe(eventSubscriber);
// Get to the stable state in the event stream
ClusterMembershipSnapshotEvent snapshotEvent = (ClusterMembershipSnapshotEvent) eventSubscriber.takeNext();
if (snapshotEvent.getLocalLeadership().getCurrent().getLeadershipState() != ClusterMemberLeadershipState.NonLeader) {
// Starts Disabled but healthy, so leadership state should change to NoLeader.
expectLocalLeadershipTransition(ClusterMemberLeadershipState.NonLeader, ACTIVE);
}
}
@After
public void tearDown() {
if (service != null) {
service.shutdown();
}
}
@Test(timeout = 30_000)
public void testLeaderElectionWithHealthcheck() throws InterruptedException {
// Now make it unhealthy
when(healthIndicator.health()).thenReturn(UNHEALTHY);
expectLocalLeadershipTransition(ClusterMemberLeadershipState.Disabled, INACTIVE);
// Now make healthy again
when(healthIndicator.health()).thenReturn(HEALTHY);
expectLocalLeadershipTransition(ClusterMemberLeadershipState.NonLeader, ACTIVE);
// Become leader
connector.becomeLeader();
expectLocalLeadershipTransition(ClusterMemberLeadershipState.Leader);
}
@Test(timeout = 30_000)
public void testLeaderElectionWithConfigurationOverrides() throws InterruptedException {
// Disable via configuration
when(configuration.isLeaderElectionEnabled()).thenReturn(false);
expectLocalLeadershipTransition(ClusterMemberLeadershipState.Disabled, INACTIVE);
}
private void expectLocalLeadershipTransition(ClusterMemberLeadershipState state) throws InterruptedException {
LeaderElectionChangeEvent leadershipEvent = (LeaderElectionChangeEvent) eventSubscriber.takeNext(TIMEOUT);
assertThat(leadershipEvent).isNotNull();
assertThat(leadershipEvent.getLeadershipRevision().getCurrent().getLeadershipState()).isEqualTo(state);
assertThat(service.getLocalLeadership().getCurrent().getLeadershipState()).isEqualTo(state);
}
private void expectLocalLeadershipTransition(ClusterMemberLeadershipState state, boolean active) throws InterruptedException {
expectLocalLeadershipTransition(state);
ClusterMembershipChangeEvent membershipChangeEvent = (ClusterMembershipChangeEvent) eventSubscriber.takeNext(TIMEOUT);
assertThat(membershipChangeEvent).isNotNull();
assertThat(membershipChangeEvent.getRevision().getCurrent().isActive()).isEqualTo(active);
}
} | 1,254 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/endpoint/metadata | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/endpoint/metadata/spring/SpringCallMetadataInterceptorTest.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.metadata.spring;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.api.model.callmetadata.CallerType;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataHeaders;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import static com.netflix.titus.runtime.endpoint.metadata.spring.SpringCallMetadataInterceptor.DEBUG_QUERY_PARAM;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* It is safe to run tests concurrently as the default security context strategy uses thread local variable.
*/
public class SpringCallMetadataInterceptorTest {
private static final String MY_ORIGINAL_CALLER = "myOriginalCaller";
private static final String MY_DIRECT_CALLER = "myDirectCaller";
private static final String MY_PASSWORD = "myPassword";
private static final String MY_REASON = "myReason";
private final SpringCallMetadataInterceptor interceptor = new SpringCallMetadataInterceptor();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final HttpServletResponse response = mock(HttpServletResponse.class);
@Before
public void setUp() {
SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(MY_DIRECT_CALLER, MY_PASSWORD));
when(request.getHeader(CallMetadataHeaders.CALL_REASON_HEADER)).thenReturn(MY_REASON);
}
@Test
public void testDirectCaller() throws Exception {
interceptor.preHandle(request, response, new Object());
CallMetadata callMetadata = expectCallMetadataAuthentication();
assertThat(callMetadata.getCallers()).hasSize(1);
assertThat(callMetadata.getCallers().get(0).getId()).isEqualTo(MY_DIRECT_CALLER);
assertThat(callMetadata.getCallers().get(0).getCallerType()).isEqualTo(CallerType.Unknown);
}
@Test
public void testOriginalCallerId() throws Exception {
when(request.getHeader(CallMetadataHeaders.CALLER_ID_HEADER)).thenReturn(MY_ORIGINAL_CALLER);
interceptor.preHandle(request, response, new Object());
CallMetadata callMetadata = expectCallMetadataAuthentication();
assertThat(callMetadata.getCallers()).hasSize(2);
assertThat(callMetadata.getCallers().get(0).getId()).isEqualTo(MY_ORIGINAL_CALLER);
assertThat(callMetadata.getCallers().get(1).getId()).isEqualTo(MY_DIRECT_CALLER);
assertThat(callMetadata.getCallers().get(1).getCallerType()).isEqualTo(CallerType.Application);
}
@Test
public void testDebugViaHeaderFalse() throws Exception {
// Not set
expectDebug(false);
}
@Test
public void testDebugViaHeaderTrue() throws Exception {
// Via header
when(request.getHeader(CallMetadataHeaders.DEBUG_HEADER)).thenReturn("true");
expectDebug(true);
}
@Test
public void testDebugViaQueryParam() throws Exception {
// Via query parameter
when(request.getHeader(CallMetadataHeaders.DEBUG_HEADER)).thenReturn(null);
when(request.getParameter(DEBUG_QUERY_PARAM)).thenReturn("true");
expectDebug(true);
}
@Test
public void testDebugViaHeaderAndQueryParamó() throws Exception {
// Both, but query parameter has higher priority
when(request.getHeader(CallMetadataHeaders.DEBUG_HEADER)).thenReturn("false");
when(request.getParameter(DEBUG_QUERY_PARAM)).thenReturn("true");
expectDebug(true);
}
private void expectDebug(boolean expectedDebug) throws Exception {
interceptor.preHandle(request, response, new Object());
CallMetadata callMetadata = expectCallMetadataAuthentication();
assertThat(callMetadata.isDebug()).isEqualTo(expectedDebug);
}
private com.netflix.titus.api.model.callmetadata.CallMetadata expectCallMetadataAuthentication() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
assertThat(authentication).isNotNull();
assertThat(authentication).isInstanceOf(CallMetadataAuthentication.class);
CallMetadataAuthentication callMetadataAuthentication = (CallMetadataAuthentication) authentication;
CallMetadata callMetadata = callMetadataAuthentication.getCallMetadata();
assertThat(callMetadata).isNotNull();
assertThat(callMetadata.getCallReason()).isEqualTo(MY_REASON);
return callMetadata;
}
} | 1,255 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/endpoint/rest/ErrorResponsesTest.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.rest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import javax.servlet.http.HttpServletRequest;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.fasterxml.jackson.databind.exc.PropertyBindingException;
import org.junit.Test;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
*
*/
public class ErrorResponsesTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
public void testBuildOfHttpRequest() {
HttpServletRequest httpRequest = mock(HttpServletRequest.class);
when(httpRequest.getServletPath()).thenReturn("/servletPath");
when(httpRequest.getPathInfo()).thenReturn("/pathInfo");
when(httpRequest.getHeaderNames()).thenReturn(enumerationOf("Content-Type"));
Map<String, Object> mappedRequest = ErrorResponses.buildHttpRequestContext(httpRequest);
assertThat(mappedRequest.get("relativeURI"), is(equalTo("/servletPath/pathInfo")));
}
@Test
public void testBuildOfServerContext() {
Map<String, Object> serverContext = ErrorResponses.buildServerContext();
assertThat(serverContext.isEmpty(), is(false));
}
@Test
public void testBuildOfGenericException() {
List<ErrorResponses.StackTraceRepresentation> mappedError;
try {
throw new IOException("simulated I/O error");
} catch (IOException e) {
mappedError = ErrorResponses.buildExceptionContext(e);
}
assertThat(mappedError, is(hasSize(1)));
}
@Test
public void testBuildOfJacksonWithInvalidType() throws Exception {
String badDocument = "{\"value\":\"notANumber\"}";
List<ErrorResponses.StackTraceRepresentation> mappedError = null;
try {
mapper.readValue(badDocument, MyService.class);
fail("Expected parsing exception");
} catch (InvalidFormatException e) {
mappedError = ErrorResponses.buildExceptionContext(e);
}
Map<String, Object> details = mappedError.get(0).getDetails();
assertThat(details, is(notNullValue()));
assertThat(details.get("pathReference"), is(equalTo(this.getClass().getName() + "$MyService[\"value\"]")));
assertThat(details.get("targetType"), is(equalTo("int")));
assertThat((String) details.get("errorLocation"), containsString("line: 1"));
assertThat(details.get("document"), is(equalTo("{\"value\":\"notANumber\"}")));
}
@Test
public void testBuildOfJacksonWithInvalidPropertyName() throws Exception {
String badDocument = "{\"myType\":\"myServiceType\"}";
List<ErrorResponses.StackTraceRepresentation> mappedError = null;
try {
mapper.readValue(badDocument, MyService.class);
fail("Expected parsing exception");
} catch (PropertyBindingException e) {
mappedError = ErrorResponses.buildExceptionContext(e);
}
ErrorResponses.StackTraceRepresentation stackTrace = mappedError.get(0);
assertThat(stackTrace.getDetails(), is(notNullValue()));
assertThat(stackTrace.getDetails().get("property"), is(equalTo("myType")));
}
@Test
public void testBuildOfThreadContext() throws Exception {
ErrorResponse errorResponse = ErrorResponse.newError(500).debug(true).threadContext().build();
List<String> threadContext = (List<String>) errorResponse.getErrorContext().get(ErrorResponse.THREAD_CONTEXT);
assertThat(threadContext.get(0), containsString(ErrorResponsesTest.class.getName()));
}
private Enumeration<String> enumerationOf(String header) {
return new Enumeration<String>() {
private boolean sent;
@Override
public boolean hasMoreElements() {
return sent;
}
@Override
public String nextElement() {
if (sent) {
throw new NoSuchElementException();
}
sent = true;
return header;
}
};
}
static class MyService {
private int value;
@JsonCreator()
MyService(@JsonProperty("value") int value) {
this.value = value;
}
}
}
| 1,256 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/endpoint/rest/TitusProtobufHttpMessageConverterTest.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.rest;
import com.google.protobuf.util.JsonFormat;
import com.netflix.titus.common.util.jackson.CommonObjectMappers;
import com.netflix.titus.testing.SampleGrpcService.SampleComplexMessage;
import com.netflix.titus.testing.SampleGrpcService.SampleComplexMessage.SampleInternalMessage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest()
@ContextConfiguration(classes = {SampleSpringResource.class, CommonExceptionHandlers.class, TitusProtobufHttpMessageConverter.class})
public class TitusProtobufHttpMessageConverterTest {
private static final SampleComplexMessage SAMPLE_BASE = SampleComplexMessage.newBuilder()
.putMapValue("keyA", "valueA")
.setInternalMessage(SampleInternalMessage.newBuilder()
.setIntervalValue("internaValue123")
.build()
)
.build();
@Autowired
private MockMvc mockMvc;
@Test
public void testSerializer() throws Exception {
doPost(SAMPLE_BASE);
SampleComplexMessage result = doGet("/test");
assertThat(result).isEqualTo(SAMPLE_BASE);
}
/**
* This is something protobuf {@link JsonFormat} does not do, but Jackson does, and some existing clients
* depend on it.
*/
@Test
public void testEmptyMapsAreSerialized() throws Exception {
doPost(SampleComplexMessage.getDefaultInstance());
String result = doGetString("/test");
assertThat(result).contains("mapValue");
}
@Test
public void testErrors() throws Exception {
// None debug mode
ErrorResponse error = doGetError("/test/error");
assertThat(error.getStatusCode()).isEqualTo(500);
assertThat(error.getErrorContext()).isNull();
// Debug mode
ErrorResponse errorWithContext = doGetError("/test/error?debug=true");
assertThat(errorWithContext.getStatusCode()).isEqualTo(500);
assertThat(errorWithContext.getErrorContext()).hasSize(3);
}
private String doGetString(String baseUri) throws Exception {
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(baseUri);
MvcResult mvcResult = mockMvc.perform(requestBuilder)
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
return mvcResult.getResponse().getContentAsString();
}
private SampleComplexMessage doGet(String baseUri) throws Exception {
SampleComplexMessage.Builder resultBuilder = SampleComplexMessage.newBuilder();
JsonFormat.parser().merge(doGetString(baseUri), resultBuilder);
return resultBuilder.build();
}
private ErrorResponse doGetError(String baseUri) throws Exception {
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(baseUri);
MvcResult mvcResult = mockMvc.perform(requestBuilder)
.andDo(print())
.andExpect(status().isInternalServerError())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
return CommonObjectMappers.protobufMapper().readValue(mvcResult.getResponse().getContentAsString(), ErrorResponse.class);
}
private void doPost(SampleComplexMessage sample) throws Exception {
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/test")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(JsonFormat.printer().print(sample));
mockMvc.perform(requestBuilder)
.andDo(print())
.andExpect(status().isCreated())
.andReturn();
}
} | 1,257 |
0 | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-server/src/test/java/com/netflix/titus/runtime/endpoint/rest/SampleSpringResource.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.rest;
import com.google.common.base.Preconditions;
import com.netflix.titus.testing.SampleGrpcService.SampleComplexMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "/test", produces = "application/json")
public class SampleSpringResource {
private volatile SampleComplexMessage lastValue;
@GetMapping
public SampleComplexMessage getLast() {
return Preconditions.checkNotNull(lastValue);
}
@GetMapping(path = "/error")
public SampleComplexMessage getError() {
throw new IllegalStateException("simulated error");
}
@PostMapping
public ResponseEntity<Void> postLast(@RequestBody SampleComplexMessage body) {
lastValue = body;
return ResponseEntity.status(HttpStatus.CREATED).build();
}
}
| 1,258 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/DefaultClusterMembershipClient.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.clustermembership;
import com.google.protobuf.Empty;
import com.netflix.titus.client.clustermembership.grpc.ClusterMembershipClient;
import com.netflix.titus.common.util.ExceptionExt;
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 com.netflix.titus.runtime.endpoint.common.grpc.assistant.GrpcClientCallAssistant;
import com.netflix.titus.runtime.endpoint.common.grpc.assistant.GrpcClientCallAssistantFactory;
import io.grpc.ManagedChannel;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class DefaultClusterMembershipClient implements ClusterMembershipClient {
private final GrpcClientCallAssistant<ClusterMembershipServiceStub> assistant;
private final ManagedChannel managedChannel;
public DefaultClusterMembershipClient(GrpcClientCallAssistantFactory assistantFactory,
ManagedChannel managedChannel) {
this.managedChannel = managedChannel;
this.assistant = assistantFactory.create(ClusterMembershipServiceGrpc.newStub(managedChannel));
}
@Override
public Mono<ClusterMembershipRevisions> getMembers() {
return assistant.asMono((stub, responseStream) -> stub.getMembers(Empty.getDefaultInstance(), responseStream));
}
@Override
public Mono<ClusterMembershipRevision> getMember(MemberId request) {
return assistant.asMono((stub, responseStream) -> stub.getMember(request, responseStream));
}
@Override
public Mono<ClusterMembershipRevision> updateMemberLabels(UpdateMemberLabelsRequest request) {
return assistant.asMono((stub, responseStream) -> stub.updateMemberLabels(request, responseStream));
}
@Override
public Mono<ClusterMembershipRevision> deleteMemberLabels(DeleteMemberLabelsRequest request) {
return assistant.asMono((stub, responseStream) -> stub.deleteMemberLabels(request, responseStream));
}
@Override
public Mono<ClusterMembershipRevision> enableMember(EnableMemberRequest request) {
return assistant.asMono((stub, responseStream) -> stub.enableMember(request, responseStream));
}
@Override
public Mono<Void> stopBeingLeader() {
return assistant.asMonoEmpty((stub, responseStream) -> stub.stopBeingLeader(Empty.getDefaultInstance(), responseStream));
}
@Override
public Flux<ClusterMembershipEvent> events() {
return assistant.asFlux((stub, responseStream) -> stub.events(Empty.getDefaultInstance(), responseStream));
}
@Override
public void shutdown() {
ExceptionExt.silent(managedChannel::shutdownNow);
}
}
| 1,259 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/activation/LeaderActivationConfiguration.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.clustermembership.activation;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
@Configuration(prefix = "titus.leaderActivation.controller")
public interface LeaderActivationConfiguration {
@DefaultValue("false")
boolean isSystemExitOnLeadershipLost();
@DefaultValue("500")
long getLeaderCheckIntervalMs();
@DefaultValue("180000")
long getLeaderActivationTimeout();
}
| 1,260 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/activation/LeaderActivationComponent.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.clustermembership.activation;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.archaius2.Archaius2Ext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class LeaderActivationComponent {
@Bean
public LeaderActivationConfiguration getLeaderActivationConfiguration(TitusRuntime titusRuntime) {
return Archaius2Ext.newConfiguration(LeaderActivationConfiguration.class, titusRuntime.getMyEnvironment());
}
}
| 1,261 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/activation/LeaderActivationStatus.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.clustermembership.activation;
public interface LeaderActivationStatus {
boolean isActivatedLeader();
}
| 1,262 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/activation/LeaderActivationCoordinators.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.clustermembership.activation;
import java.util.List;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipService;
import com.netflix.titus.api.common.LeaderActivationListener;
import com.netflix.titus.common.runtime.SystemAbortEvent;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.SystemExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class LeaderActivationCoordinators {
private static final Logger logger = LoggerFactory.getLogger(LeaderActivationCoordinators.class);
private LeaderActivationCoordinators() {
}
public static LeaderActivationCoordinator coordinatorWithLoggingCallback(LeaderActivationConfiguration configuration,
List<LeaderActivationListener> services,
ClusterMembershipService membershipService,
TitusRuntime titusRuntime) {
return new LeaderActivationCoordinator(
configuration,
services,
error -> logger.info(error.getMessage()),
membershipService,
titusRuntime
);
}
public static LeaderActivationCoordinator coordinatorWithSystemExitCallback(LeaderActivationConfiguration configuration,
List<LeaderActivationListener> services,
ClusterMembershipService membershipService,
TitusRuntime titusRuntime) {
return new LeaderActivationCoordinator(
configuration,
services,
e -> {
titusRuntime.beforeAbort(SystemAbortEvent.newBuilder()
.withFailureId("activationError")
.withFailureType(SystemAbortEvent.FailureType.Nonrecoverable)
.withReason(e.getMessage())
.withTimestamp(titusRuntime.getClock().wallTime())
.build()
);
SystemExt.forcedProcessExit(-1);
},
membershipService,
titusRuntime
);
}
}
| 1,263 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/activation/LeaderActivationCoordinator.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.clustermembership.activation;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import javax.annotation.PreDestroy;
import com.google.common.base.Stopwatch;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipService;
import com.netflix.titus.api.common.LeaderActivationListener;
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.CollectionsExt;
import com.netflix.titus.common.util.DateTimeExt;
import com.netflix.titus.common.util.retry.Retryers;
import com.netflix.titus.common.util.rx.ReactorExt;
import com.netflix.titus.common.util.spectator.SpectatorExt;
import com.netflix.titus.common.util.time.Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
/**
* Coordinates the activation and deactivation processes for an elected leader.
*/
public class LeaderActivationCoordinator implements LeaderActivationStatus {
private static final Logger logger = LoggerFactory.getLogger(LeaderActivationCoordinator.class);
private static final String NAME = LeaderActivationListener.class.getSimpleName();
private static final String LABEL_ROOT = "titus.leaderActivationCoordinator.";
private static final String LABEL_STATE = LABEL_ROOT + "state";
private static final String LABEL_TRANSITION_TIME = LABEL_ROOT + "transitionTime";
private static final String METRIC_ROOT = "titus.clusterMembership.activation.";
private static final ScheduleDescriptor SCHEDULE_DESCRIPTOR = ScheduleDescriptor.newBuilder()
.withName(NAME)
.withDescription("Leader activation/deactivation coordinator")
.withInitialDelay(Duration.ZERO)
.withInterval(Duration.ofMillis(200))
.withTimeout(Duration.ofSeconds(60))
.withRetryerSupplier(Retryers::never)
.withOnErrorHandler((action, error) -> logger.error("Unexpected error", error))
.build();
public enum State {
Awaiting,
ElectedLeader,
Deactivated
}
private final LeaderActivationConfiguration configuration;
private final List<LeaderActivationListener> services;
private final Consumer<Throwable> deactivationCallback;
private final ClusterMembershipService membershipService;
private final String localMemberId;
private final AtomicReference<State> stateRef = new AtomicReference<>(State.Awaiting);
private volatile List<LeaderActivationListener> activatedServices = Collections.emptyList();
private volatile long activationTimestamp = -1;
private final Scheduler scheduler;
private final ScheduleReference scheduleRef;
private final Clock clock;
private final Registry registry;
private final SpectatorExt.FsmMetrics<State> stateMetricFsm;
private final Id inActiveStateTimeId;
/**
* @param services list of services to activate in the desired activation order
*/
public LeaderActivationCoordinator(LeaderActivationConfiguration configuration,
List<LeaderActivationListener> services,
Consumer<Throwable> deactivationCallback,
ClusterMembershipService membershipService,
TitusRuntime titusRuntime) {
this.configuration = configuration;
this.services = services;
this.deactivationCallback = deactivationCallback;
this.membershipService = membershipService;
this.localMemberId = membershipService.getLocalClusterMember().getCurrent().getMemberId();
this.clock = titusRuntime.getClock();
this.registry = titusRuntime.getRegistry();
this.stateMetricFsm = SpectatorExt.fsmMetrics(
registry.createId(METRIC_ROOT + "state"),
s -> s == State.Deactivated,
State.Awaiting,
registry
);
this.inActiveStateTimeId = registry.createId(METRIC_ROOT + "inActiveStateTime");
PolledMeter.using(registry).withId(inActiveStateTimeId).monitorValue(this, self ->
(self.stateRef.get() == State.ElectedLeader && activationTimestamp > 0) ? self.clock.wallTime() - self.activationTimestamp : 0
);
// We create the thread here, as the default one is NonBlocking, and we allow React blocking subscriptions in
// the activation phase.
this.scheduler = Schedulers.newSingle(r -> {
Thread thread = new Thread(r, "LeaderActivationCoordinator");
thread.setDaemon(true);
return thread;
});
this.scheduleRef = titusRuntime.getLocalScheduler().scheduleMono(
SCHEDULE_DESCRIPTOR.toBuilder()
.withInterval(Duration.ofMillis(configuration.getLeaderCheckIntervalMs()))
.withTimeout(Duration.ofMillis(configuration.getLeaderActivationTimeout()))
.build(),
context -> refresh(),
scheduler
);
}
@Override
public boolean isActivatedLeader() {
return isLocalLeader() && activatedServices.size() == services.size();
}
private Mono<Void> refresh() {
return Mono.defer(() -> {
try {
if (isLocalLeader()) {
activate();
} else {
if (stateRef.get() != State.Awaiting) {
try {
deactivate();
} finally {
deactivationCallback.accept(new RuntimeException("Lost leadership"));
}
}
}
return recordState();
} catch (Exception e) {
return Mono.error(new IllegalStateException("Unexpected leader election coordinator error: " + e.getMessage(), e));
}
});
}
@PreDestroy
public void shutdown() {
activationTimestamp = -1;
PolledMeter.remove(registry, inActiveStateTimeId);
scheduleRef.cancel();
// Give it some time to finish pending work if any.
long start = clock.wallTime();
while (!scheduleRef.isClosed() && !clock.isPast(start + configuration.getLeaderActivationTimeout())) {
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
break;
}
}
scheduler.dispose();
try {
deactivate();
} catch (Exception e) {
deactivationCallback.accept(new RuntimeException(NAME + " component shutdown"));
}
recordState().subscribe(ReactorExt.silentSubscriber());
}
private void activate() {
if (!stateRef.compareAndSet(State.Awaiting, State.ElectedLeader)) {
logger.debug("Activation process has been already attempted. Component is in: state={}", stateRef.get());
return;
}
logger.info("Starting the leader activation process (activating {} services)...", services.size());
Stopwatch allStart = Stopwatch.createStarted();
List<LeaderActivationListener> activated = new ArrayList<>();
for (LeaderActivationListener service : services) {
String serviceName = service.getClass().getSimpleName();
logger.info("Activating service {}...", serviceName);
Stopwatch serviceStart = Stopwatch.createStarted();
try {
service.activate();
activated.add(service);
logger.info("Service {} started in {}", serviceName, serviceStart.elapsed(TimeUnit.MILLISECONDS));
} catch (Exception e) {
logger.error("Service activation failure. Rolling back", e);
this.activatedServices = activated;
try {
deactivate();
} finally {
deactivationCallback.accept(e);
}
return;
}
}
this.activatedServices = activated;
this.activationTimestamp = clock.wallTime();
logger.info("Activation process finished in: {}", DateTimeExt.toTimeUnitString(allStart.elapsed(TimeUnit.MILLISECONDS)));
}
private void deactivate() {
this.activationTimestamp = -1;
State current = stateRef.getAndSet(State.Deactivated);
if (current == State.Awaiting) {
logger.info("Deactivating non-leader member");
return;
}
if (current == State.Deactivated) {
logger.debug("Already deactivated");
return;
}
logger.info("Stopping the elected leader (deactivating {} services)...", activatedServices.size());
Stopwatch allStart = Stopwatch.createStarted();
List<LeaderActivationListener> deactivationList = new ArrayList<>(activatedServices);
Collections.reverse(deactivationList);
activatedServices.clear();
for (LeaderActivationListener service : deactivationList) {
String serviceName = service.getClass().getSimpleName();
logger.info("Deactivating service {}...", serviceName);
Stopwatch serviceStart = Stopwatch.createStarted();
try {
service.deactivate();
logger.info("Service {} stopped in {}", serviceName, serviceStart.elapsed(TimeUnit.MILLISECONDS));
} catch (Exception e) {
logger.error("Failed to deactivate service: {}", serviceName);
}
}
logger.info("Deactivation process finished in: {}", DateTimeExt.toTimeUnitString(allStart.elapsed(TimeUnit.MILLISECONDS)));
}
private Mono<Void> recordState() {
stateMetricFsm.transition(stateRef.get());
String recordedState = membershipService.getLocalClusterMember().getCurrent().getLabels().get(LABEL_STATE);
if (stateRef.get().name().equals(recordedState)) {
return Mono.empty();
}
return membershipService.updateSelf(current -> {
Map<String, String> labels = CollectionsExt.asMap(
LABEL_STATE, stateRef.get().name(),
LABEL_TRANSITION_TIME, DateTimeExt.toLocalDateTimeString(clock.wallTime())
);
return ClusterMembershipRevision.<ClusterMember>newBuilder()
.withCurrent(current.toBuilder()
.withLabels(CollectionsExt.merge(current.getLabels(), labels))
.build()
)
.build();
}
).ignoreElement().cast(Void.class).onErrorResume(error -> {
logger.info("Failed to append {} labels", NAME, error);
return Mono.empty();
});
}
private boolean isLocalLeader() {
return membershipService.findLeader()
.map(leader -> leader.getCurrent().getMemberId().equals(localMemberId))
.orElse(false);
}
}
| 1,264 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint/grpc/ClusterMembershipGrpcEndpointComponent.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.clustermembership.endpoint.grpc;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipService;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.runtime.endpoint.common.grpc.assistant.GrpcServerCallAssistant;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ClusterMembershipGrpcEndpointComponent {
@Bean
public GrpcClusterMembershipService getGrpcClusterMembershipService(ClusterMembershipService service,
GrpcServerCallAssistant assistant,
TitusRuntime titusRuntime) {
return new GrpcClusterMembershipService(service, assistant, titusRuntime);
}
}
| 1,265 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint/grpc/GrpcLeaderServerInterceptor.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.clustermembership.endpoint.grpc;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import com.netflix.titus.grpc.protogen.ClusterMembershipServiceGrpc;
import com.netflix.titus.runtime.clustermembership.activation.LeaderActivationStatus;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.ServiceDescriptor;
import io.grpc.Status;
/**
* Interceptor that rejects incoming GRPC requests if the current node is not a leader.
*/
public class GrpcLeaderServerInterceptor implements ServerInterceptor {
private final LeaderActivationStatus leaderActivationStatus;
private final Set<MethodDescriptor<?, ?>> notProtectedMethods;
public GrpcLeaderServerInterceptor(LeaderActivationStatus leaderActivationStatus,
List<ServiceDescriptor> notProtectedServices) {
this.leaderActivationStatus = leaderActivationStatus;
this.notProtectedMethods = notProtectedServices.stream()
.flatMap(s -> s.getMethods().stream())
.collect(Collectors.toCollection(() -> new TreeSet<>(new MethodDescriptorComparator())));
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
MethodDescriptor<ReqT, RespT> methodDescriptor = call.getMethodDescriptor();
if (notProtectedMethods.contains(methodDescriptor)) {
return next.startCall(call, headers);
}
if (leaderActivationStatus.isActivatedLeader()) {
return next.startCall(call, headers);
} else {
call.close(Status.UNAVAILABLE.withDescription("Not a leader or not ready yet."), new Metadata());
return new ServerCall.Listener<ReqT>() {
};
}
}
public static GrpcLeaderServerInterceptor clusterMembershipAllowed(LeaderActivationStatus leaderActivationStatus) {
return new GrpcLeaderServerInterceptor(leaderActivationStatus, Collections.singletonList(ClusterMembershipServiceGrpc.getServiceDescriptor()));
}
private static class MethodDescriptorComparator implements Comparator<MethodDescriptor<?, ?>> {
@Override
public int compare(MethodDescriptor<?, ?> m1, MethodDescriptor<?, ?> m2) {
return m1.getFullMethodName().compareTo(m2.getFullMethodName());
}
}
}
| 1,266 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint/grpc/MemberDataMixer.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.clustermembership.endpoint.grpc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipChangeEvent;
import com.netflix.titus.api.clustermembership.model.event.LeaderElectionChangeEvent;
import com.netflix.titus.grpc.protogen.ClusterMembershipEvent;
import static com.netflix.titus.client.clustermembership.grpc.ClusterMembershipGrpcConverters.toGrpcClusterMembershipRevision;
/**
* At the connector and service level we keep membership data and the leader election process separate. However
* when exposing the data outside, we want to merge this into a single data model. This class deals with the complexity
* of doing that.
*/
class MemberDataMixer {
static final String NO_LEADER_ID = "";
private final Map<String, ClusterMembershipRevision<ClusterMember>> memberRevisions;
private String leaderId;
MemberDataMixer(List<ClusterMembershipRevision<ClusterMember>> memberRevisions,
Optional<ClusterMembershipRevision<ClusterMemberLeadership>> currentLeaderOptional) {
this.memberRevisions = memberRevisions.stream().collect(Collectors.toMap(r -> r.getCurrent().getMemberId(), r -> r));
this.leaderId = currentLeaderOptional.map(l -> l.getCurrent().getMemberId()).orElse(NO_LEADER_ID);
}
List<ClusterMembershipEvent> process(com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent coreEvent) {
if (coreEvent instanceof ClusterMembershipChangeEvent) {
return processMembershipChangeEvent((ClusterMembershipChangeEvent) coreEvent);
}
if (coreEvent instanceof LeaderElectionChangeEvent) {
return processLeaderElectionChangeEvent((LeaderElectionChangeEvent) coreEvent);
}
return Collections.emptyList();
}
private List<ClusterMembershipEvent> processMembershipChangeEvent(ClusterMembershipChangeEvent coreEvent) {
ClusterMembershipRevision<ClusterMember> revision = coreEvent.getRevision();
String memberId = revision.getCurrent().getMemberId();
if (coreEvent.getChangeType() == ClusterMembershipChangeEvent.ChangeType.Removed) {
memberRevisions.remove(memberId);
if (isLeader(revision)) {
leaderId = NO_LEADER_ID;
}
return Collections.singletonList(ClusterMembershipEvent.newBuilder()
.setMemberRemoved(ClusterMembershipEvent.MemberRemoved.newBuilder()
.setRevision(toGrpcClusterMembershipRevision(revision, false))
)
.build()
);
}
memberRevisions.put(memberId, revision);
return Collections.singletonList(newMemberUpdatedEvent(revision, isLeader(revision)));
}
private List<ClusterMembershipEvent> processLeaderElectionChangeEvent(LeaderElectionChangeEvent coreEvent) {
ClusterMembershipRevision<ClusterMemberLeadership> revision = coreEvent.getLeadershipRevision();
String memberId = revision.getCurrent().getMemberId();
if (coreEvent.getChangeType() == LeaderElectionChangeEvent.ChangeType.LocalJoined) {
return Collections.emptyList();
}
if (coreEvent.getChangeType() == LeaderElectionChangeEvent.ChangeType.LocalLeft) {
return Collections.emptyList();
}
if (coreEvent.getChangeType() == LeaderElectionChangeEvent.ChangeType.LeaderElected) {
if (this.leaderId.equals(memberId)) {
return Collections.emptyList();
}
ClusterMembershipRevision<ClusterMember> previousLeader = memberRevisions.get(this.leaderId);
ClusterMembershipRevision<ClusterMember> currentLeader = memberRevisions.get(memberId);
List<ClusterMembershipEvent> events = new ArrayList<>();
if (previousLeader != null) {
events.add(newMemberUpdatedEvent(previousLeader, false));
}
if (currentLeader != null) {
events.add(newMemberUpdatedEvent(currentLeader, true));
}
this.leaderId = revision.getCurrent().getMemberId();
return events;
}
if (coreEvent.getChangeType() == LeaderElectionChangeEvent.ChangeType.LeaderLost) {
if (leaderId.equals(NO_LEADER_ID)) {
return Collections.emptyList();
}
ClusterMembershipRevision<ClusterMember> lostLeader = memberRevisions.get(leaderId);
if (lostLeader == null) {
return Collections.emptyList();
}
this.leaderId = NO_LEADER_ID;
return Collections.singletonList(newMemberUpdatedEvent(lostLeader, false));
}
return Collections.emptyList();
}
ClusterMembershipEvent toGrpcSnapshot() {
ClusterMembershipEvent.Snapshot.Builder builder = ClusterMembershipEvent.Snapshot.newBuilder();
memberRevisions.forEach((id, revision) -> builder.addRevisions(toGrpcClusterMembershipRevision(revision, isLeader(revision))));
return ClusterMembershipEvent.newBuilder()
.setSnapshot(builder)
.build();
}
private boolean isLeader(ClusterMembershipRevision<ClusterMember> revision) {
return revision.getCurrent().getMemberId().equals(leaderId);
}
private ClusterMembershipEvent newMemberUpdatedEvent(ClusterMembershipRevision<ClusterMember> revision, boolean leader) {
return ClusterMembershipEvent.newBuilder()
.setMemberUpdated(ClusterMembershipEvent.MemberUpdated.newBuilder()
.setRevision(toGrpcClusterMembershipRevision(revision, leader))
)
.build();
}
}
| 1,267 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint/grpc/GrpcClusterMembershipService.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.clustermembership.endpoint.grpc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.common.base.Preconditions;
import com.google.protobuf.Empty;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipSnapshotEvent;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipService;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipServiceException;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.time.Clock;
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.DeleteMemberLabelsRequest;
import com.netflix.titus.grpc.protogen.EnableMemberRequest;
import com.netflix.titus.grpc.protogen.MemberId;
import com.netflix.titus.grpc.protogen.UpdateMemberLabelsRequest;
import com.netflix.titus.runtime.endpoint.common.grpc.assistant.GrpcServerCallAssistant;
import io.grpc.stub.StreamObserver;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.netflix.titus.client.clustermembership.grpc.ClusterMembershipGrpcConverters.toGrpcClusterMembershipRevision;
import static com.netflix.titus.runtime.clustermembership.endpoint.grpc.MemberDataMixer.NO_LEADER_ID;
@Singleton
public class GrpcClusterMembershipService extends ClusterMembershipServiceGrpc.ClusterMembershipServiceImplBase {
private final String localMemberId;
private final ClusterMembershipService service;
private final GrpcServerCallAssistant assistant;
private final Clock clock;
@Inject
public GrpcClusterMembershipService(ClusterMembershipService service,
GrpcServerCallAssistant assistant,
TitusRuntime titusRuntime) {
this.localMemberId = service.getLocalLeadership().getCurrent().getMemberId();
this.service = service;
this.assistant = assistant;
this.clock = titusRuntime.getClock();
}
/**
* Get all known cluster members.
*/
@Override
public void getMembers(Empty request, StreamObserver<ClusterMembershipRevisions> responseObserver) {
assistant.callDirect(responseObserver, context -> getMembersInternal());
}
public ClusterMembershipRevisions getMembersInternal() {
List<ClusterMembershipRevision> grpcRevisions = new ArrayList<>();
grpcRevisions.add(toGrpcClusterMembershipRevision(service.getLocalClusterMember(), isLocalLeader()));
String leaderId = getLeaderId();
for (com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision<ClusterMember> sibling : service.getClusterMemberSiblings().values()) {
grpcRevisions.add(toGrpcClusterMembershipRevision(sibling, sibling.getCurrent().getMemberId().equals(leaderId)));
}
return ClusterMembershipRevisions.newBuilder().addAllRevisions(grpcRevisions).build();
}
/**
* Get member with the given id.
*/
@Override
public void getMember(MemberId request, StreamObserver<ClusterMembershipRevision> responseObserver) {
assistant.callDirect(responseObserver, context -> getMemberInternal(request));
}
public ClusterMembershipRevision getMemberInternal(MemberId request) {
String memberId = request.getId();
if (service.getLocalClusterMember().getCurrent().getMemberId().equals(memberId)) {
return toGrpcClusterMembershipRevision(service.getLocalClusterMember(), isLocalLeader());
}
com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision<ClusterMember> sibling = service.getClusterMemberSiblings().get(memberId);
if (sibling == null) {
throw ClusterMembershipServiceException.memberNotFound(memberId);
}
return toGrpcClusterMembershipRevision(sibling, getLeaderId().equals(memberId));
}
/**
* Adds all labels from the request object to the target member. Labels that exist are
* overridden. Returns the updated object.
*/
@Override
public void updateMemberLabels(UpdateMemberLabelsRequest request, StreamObserver<ClusterMembershipRevision> responseObserver) {
assistant.callMono(responseObserver, context -> updateMemberLabelsInternal(request));
}
public Mono<ClusterMembershipRevision> updateMemberLabelsInternal(UpdateMemberLabelsRequest request) {
if (!request.getMemberId().equals(localMemberId)) {
return Mono.error(ClusterMembershipServiceException.localOnly(request.getMemberId()));
}
if (request.getLabelsMap().isEmpty()) {
return Mono.fromCallable(() -> toGrpcClusterMembershipRevision(service.getLocalClusterMember(), isLocalLeader()));
}
return service.updateSelf(current ->
com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision.<ClusterMember>newBuilder()
.withCurrent(current.toBuilder()
.withLabels(CollectionsExt.merge(current.getLabels(), request.getLabelsMap()))
.build()
)
.withCode("updated")
.withMessage("Added labels: " + request.getLabelsMap())
.withTimestamp(clock.wallTime())
.build()
).map(c -> toGrpcClusterMembershipRevision(c, isLocalLeader()));
}
/**
* Removes all specified labels from the target object. Labels that do not exist are ignored.
* Returns the updated object.
*/
@Override
public void deleteMemberLabels(DeleteMemberLabelsRequest request, StreamObserver<ClusterMembershipRevision> responseObserver) {
assistant.callMono(responseObserver, context -> deleteMemberLabelsInternal(request));
}
public Mono<ClusterMembershipRevision> deleteMemberLabelsInternal(DeleteMemberLabelsRequest request) {
if (!request.getMemberId().equals(localMemberId)) {
return Mono.error(ClusterMembershipServiceException.localOnly(request.getMemberId()));
}
if (request.getKeysList().isEmpty()) {
return Mono.fromCallable(() -> toGrpcClusterMembershipRevision(service.getLocalClusterMember(), isLocalLeader()));
}
return service.updateSelf(current ->
com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision.<ClusterMember>newBuilder()
.withCurrent(current.toBuilder()
.withLabels(CollectionsExt.copyAndRemove(current.getLabels(), request.getKeysList()))
.build()
)
.withCode("updated")
.withMessage("Removed labels: " + request.getKeysList())
.withTimestamp(clock.wallTime())
.build()
).map(c -> toGrpcClusterMembershipRevision(c, isLocalLeader()));
}
/**
* Enable or disable a member.
*/
@Override
public void enableMember(EnableMemberRequest request, StreamObserver<ClusterMembershipRevision> responseObserver) {
assistant.callMono(responseObserver, context -> enableMemberInternal(request));
}
public Mono<ClusterMembershipRevision> enableMemberInternal(EnableMemberRequest request) {
if (!request.getMemberId().equals(localMemberId)) {
return Mono.error(ClusterMembershipServiceException.localOnly(request.getMemberId()));
}
return service.updateSelf(current ->
com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision.<ClusterMember>newBuilder()
.withCurrent(current.toBuilder()
.withEnabled(request.getEnabled())
.build()
)
.withCode(request.getEnabled() ? "enabled" : "disabled")
.withMessage("Changed enabled status to: " + request.getEnabled())
.withTimestamp(clock.wallTime())
.build()
).map(c -> toGrpcClusterMembershipRevision(c, isLocalLeader()));
}
/**
* Requests the member that handles this request to stop being leader. If the given member
* is not a leader, the request is ignored.
*/
@Override
public void stopBeingLeader(Empty request, StreamObserver<Empty> responseObserver) {
assistant.callMonoEmpty(responseObserver, context -> stopBeingLeaderInternal());
}
public Mono<Void> stopBeingLeaderInternal() {
return service.stopBeingLeader();
}
/**
* Event stream.
*/
@Override
public void events(Empty request, StreamObserver<ClusterMembershipEvent> responseObserver) {
assistant.callFlux(responseObserver, context -> Flux.defer(() -> {
AtomicReference<MemberDataMixer> leaderRef = new AtomicReference<>();
return service.events().flatMapIterable(event -> {
MemberDataMixer data = leaderRef.get();
if (data == null) {
Preconditions.checkArgument(
event instanceof ClusterMembershipSnapshotEvent,
"Expected ClusterMembershipSnapshotEvent as the first event"
);
ClusterMembershipSnapshotEvent snapshotEvent = (ClusterMembershipSnapshotEvent) event;
data = new MemberDataMixer(snapshotEvent.getClusterMemberRevisions(), snapshotEvent.getLeader());
leaderRef.set(data);
return Collections.singletonList(data.toGrpcSnapshot());
}
return data.process(event);
});
}));
}
private String getLeaderId() {
return service.findLeader().map(l -> l.getCurrent().getMemberId()).orElse(NO_LEADER_ID);
}
private boolean isLocalLeader() {
return service.getLocalLeadership().getCurrent().getLeadershipState() == ClusterMemberLeadershipState.Leader;
}
}
| 1,268 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint/grpc/ClusterMembershipGrpcExceptionMapper.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.clustermembership.endpoint.grpc;
import java.util.Optional;
import java.util.function.Function;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipServiceException;
import io.grpc.Status;
public class ClusterMembershipGrpcExceptionMapper implements Function<Throwable, Optional<Status>> {
private static final ClusterMembershipGrpcExceptionMapper INSTANCE = new ClusterMembershipGrpcExceptionMapper();
@Override
public Optional<Status> apply(Throwable throwable) {
if (!(throwable instanceof ClusterMembershipServiceException)) {
return Optional.empty();
}
ClusterMembershipServiceException serviceException = (ClusterMembershipServiceException) throwable;
switch (serviceException.getErrorCode()) {
case BadSelfUpdate:
case LocalMemberOnly:
return Optional.of(Status.FAILED_PRECONDITION);
case Internal:
return Optional.of(Status.INTERNAL);
case MemberNotFound:
return Optional.of(Status.NOT_FOUND);
}
return Optional.empty();
}
public static ClusterMembershipGrpcExceptionMapper getInstance() {
return INSTANCE;
}
}
| 1,269 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint/rest/ClusterMembershipRestEndpointComponent.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.clustermembership.endpoint.rest;
import com.netflix.titus.runtime.clustermembership.activation.LeaderActivationStatus;
import com.netflix.titus.runtime.clustermembership.endpoint.grpc.GrpcClusterMembershipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ClusterMembershipRestEndpointComponent implements WebMvcConfigurer {
@Autowired
private LeaderActivationStatus leaderActivationStatus;
@Bean
public ClusterMembershipSpringResource getClusterMembershipSpringResource(GrpcClusterMembershipService reactorClusterMembershipService) {
return new ClusterMembershipSpringResource(reactorClusterMembershipService);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(SpringLeaderServerInterceptor.clusterMembershipAllowed(leaderActivationStatus));
}
}
| 1,270 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint/rest/ClusterMembershipSpringResource.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.clustermembership.endpoint.rest;
import java.time.Duration;
import com.netflix.titus.grpc.protogen.ClusterMembershipRevision;
import com.netflix.titus.grpc.protogen.ClusterMembershipRevisions;
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 com.netflix.titus.runtime.clustermembership.endpoint.grpc.GrpcClusterMembershipService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "/api/v3/clustermembership")
public class ClusterMembershipSpringResource {
private static final Duration TIMEOUT = Duration.ofSeconds(1);
private final GrpcClusterMembershipService clusterMembershipService;
public ClusterMembershipSpringResource(GrpcClusterMembershipService clusterMembershipService) {
this.clusterMembershipService = clusterMembershipService;
}
@RequestMapping(method = RequestMethod.GET, path = "/members", produces = "application/json")
public ClusterMembershipRevisions getMembers() {
return clusterMembershipService.getMembersInternal();
}
@RequestMapping(method = RequestMethod.GET, path = "/members/{memberId}", produces = "application/json")
public ClusterMembershipRevision getMember(@PathVariable("memberId") String memberId) {
return clusterMembershipService.getMemberInternal(MemberId.newBuilder().setId(memberId).build());
}
@RequestMapping(method = RequestMethod.POST, path = "/members/{memberId}/labels", consumes = "application/json", produces = "application/json")
public ClusterMembershipRevision updateMemberLabels(@PathVariable("memberId") String memberId,
@RequestBody UpdateMemberLabelsRequest request) {
if (request.getMemberId().equals(memberId)) {
throw new IllegalArgumentException("Member id in path and request body are different");
}
return clusterMembershipService.updateMemberLabelsInternal(request).block(TIMEOUT);
}
@RequestMapping(method = RequestMethod.DELETE, path = "/members/{memberId}/labels", consumes = "application/json", produces = "application/json")
public ClusterMembershipRevision deleteMemberLabels(@PathVariable("memberId") String memberId,
@RequestBody DeleteMemberLabelsRequest request) {
if (request.getMemberId().equals(memberId)) {
throw new IllegalArgumentException("Member id in path and request body are different");
}
return clusterMembershipService.deleteMemberLabelsInternal(request).block(TIMEOUT);
}
@RequestMapping(method = RequestMethod.POST, path = "/members/{memberId}/enable", consumes = "application/json", produces = "application/json")
public ClusterMembershipRevision enableMember(@PathVariable("memberId") String memberId,
@RequestBody EnableMemberRequest request) {
if (request.getMemberId().equals(memberId)) {
throw new IllegalArgumentException("Member id in path and request body are different");
}
return clusterMembershipService.enableMemberInternal(request).block(TIMEOUT);
}
@RequestMapping(method = RequestMethod.POST, path = "/members/{memberId}/stopBeingLeader")
public void stopBeingLeader() {
clusterMembershipService.stopBeingLeaderInternal().block(TIMEOUT);
}
}
| 1,271 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/endpoint/rest/SpringLeaderServerInterceptor.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.clustermembership.endpoint.rest;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.netflix.titus.runtime.clustermembership.activation.LeaderActivationStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class SpringLeaderServerInterceptor extends HandlerInterceptorAdapter {
private final LeaderActivationStatus leaderActivationStatus;
private final List<String> notProtectedPaths;
public SpringLeaderServerInterceptor(LeaderActivationStatus leaderActivationStatus,
List<String> notProtectedPaths) {
this.leaderActivationStatus = leaderActivationStatus;
this.notProtectedPaths = notProtectedPaths;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (leaderActivationStatus.isActivatedLeader()) {
return super.preHandle(request, response, handler);
}
for (String path : notProtectedPaths) {
if (request.getRequestURI().contains(path)) {
return super.preHandle(request, response, handler);
}
}
response.setStatus(503); // Service Unavailable
try (OutputStream os = response.getOutputStream()) {
os.write("Not a leader or not activated yet".getBytes());
}
return false;
}
public static SpringLeaderServerInterceptor clusterMembershipAllowed(LeaderActivationStatus leaderActivationStatus) {
return new SpringLeaderServerInterceptor(leaderActivationStatus, Collections.singletonList("/api/v3/clustermembership"));
}
}
| 1,272 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/connector/ClusterMembershipInMemoryConnectorComponent.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.clustermembership.connector;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMemberAddress;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.NetworkExt;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.scheduler.Schedulers;
@Configuration
@ConditionalOnProperty(name = "titus.clusterMembership.connector.inMemory.enabled", havingValue = "true", matchIfMissing = true)
public class ClusterMembershipInMemoryConnectorComponent {
@Bean
@ConditionalOnMissingBean
public ClusterMembershipRevision<ClusterMember> getInitialLocalMemberRevision(TitusRuntime titusRuntime) {
return newInitialLocalMemberRevision(7004, titusRuntime);
}
@Bean
public ClusterMembershipInMemoryConnector getClusterMembershipConnector(ClusterMembershipRevision<ClusterMember> initialLocalMemberRevision,
TitusRuntime titusRuntime) {
return new ClusterMembershipInMemoryConnector(initialLocalMemberRevision, titusRuntime, Schedulers.parallel());
}
public static ClusterMembershipRevision<ClusterMember> newInitialLocalMemberRevision(int grpcPort, TitusRuntime titusRuntime) {
return ClusterMembershipRevision.<ClusterMember>newBuilder()
.withCurrent(ClusterMember.newBuilder()
.withMemberId(NetworkExt.getHostName().orElse(String.format("%s@localhost", System.getenv("USER"))))
.withEnabled(true)
.withRegistered(false)
.withActive(false)
.withClusterMemberAddresses(getLocalAddresses(grpcPort))
.withLabels(Collections.emptyMap())
.build()
)
.withRevision(0)
.withCode("started")
.withMessage("Initial local membership record")
.withTimestamp(titusRuntime.getClock().wallTime())
.build();
}
private static List<ClusterMemberAddress> getLocalAddresses(int grpcPort) {
return NetworkExt.getLocalIPs()
.map(addresses -> addresses.stream()
.map(ipAddress -> newAddress(grpcPort, ipAddress))
.collect(Collectors.toList())
)
.orElse(Collections.singletonList(newAddress(grpcPort, "localhost")));
}
private static ClusterMemberAddress newAddress(int grpcPort, String ipAddress) {
return ClusterMemberAddress.newBuilder()
.withIpAddress(ipAddress)
.withProtocol("grpc")
.withPortNumber(grpcPort)
.withDescription("GRPC endpoint")
.build();
}
}
| 1,273 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/connector/ClusterMembershipInMemoryConnector.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.clustermembership.connector;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.titus.api.clustermembership.connector.ClusterMembershipConnector;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipSnapshotEvent;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.rx.ReactorExt;
import com.netflix.titus.common.util.rx.invoker.ReactorSerializedInvoker;
import com.netflix.titus.common.util.time.Clock;
import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
@Singleton
public class ClusterMembershipInMemoryConnector implements ClusterMembershipConnector {
private static final int MAX_TASK_QUEUE_SIZE = 10;
private static final Duration EXCESSIVE_TASK_RUNNING_TIME = Duration.ofSeconds(1);
private final Clock clock;
private final AtomicLong revisionIdx = new AtomicLong();
/**
* Execute all actions in order of arrival.
*/
private final ReactorSerializedInvoker<Object> taskInvoker;
private volatile ClusterMembershipRevision<ClusterMember> localMemberRevision;
private volatile ClusterMembershipRevision<ClusterMemberLeadership> localLeadershipRevision;
private final DirectProcessor<ClusterMembershipEvent> eventProcessor = DirectProcessor.create();
private final FluxSink<ClusterMembershipEvent> eventSink = eventProcessor.sink();
@Inject
public ClusterMembershipInMemoryConnector(ClusterMembershipRevision<ClusterMember> localMemberRevision,
TitusRuntime titusRuntime,
Scheduler scheduler) {
this.localMemberRevision = localMemberRevision;
this.clock = titusRuntime.getClock();
this.localLeadershipRevision = ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder()
.withCurrent(ClusterMemberLeadership.newBuilder()
.withMemberId(localMemberRevision.getCurrent().getMemberId())
.withLeadershipState(ClusterMemberLeadershipState.Disabled)
.build()
)
.withCode("started")
.withMessage("Starts disabled after bootstrap")
.withRevision(revisionIdx.incrementAndGet())
.withTimestamp(clock.wallTime())
.build();
this.taskInvoker = ReactorSerializedInvoker.newBuilder()
.withName(ClusterMembershipInMemoryConnector.class.getSimpleName())
.withMaxQueueSize(MAX_TASK_QUEUE_SIZE)
.withExcessiveRunningTime(EXCESSIVE_TASK_RUNNING_TIME)
.withRegistry(titusRuntime.getRegistry())
.withClock(titusRuntime.getClock())
.withScheduler(scheduler)
.build();
}
@PreDestroy
public void shutdown() {
taskInvoker.shutdown(EXCESSIVE_TASK_RUNNING_TIME);
ReactorExt.safeDispose(eventProcessor);
}
@Override
public ClusterMembershipRevision<ClusterMember> getLocalClusterMemberRevision() {
return localMemberRevision;
}
@Override
public Map<String, ClusterMembershipRevision<ClusterMember>> getClusterMemberSiblings() {
return Collections.emptyMap();
}
@Override
public ClusterMembershipRevision<ClusterMemberLeadership> getLocalLeadershipRevision() {
return localLeadershipRevision;
}
@Override
public Optional<ClusterMembershipRevision<ClusterMemberLeadership>> findCurrentLeader() {
return localLeadershipRevision.getCurrent().getLeadershipState() == ClusterMemberLeadershipState.Leader
? Optional.of(localLeadershipRevision)
: Optional.empty();
}
@Override
public Mono<ClusterMembershipRevision<ClusterMember>> register(Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> selfUpdate) {
return invoke(Mono.fromCallable(() -> this.localMemberRevision = changeRegistrationStatus(selfUpdate.apply(localMemberRevision.getCurrent()), true)));
}
@Override
public Mono<ClusterMembershipRevision<ClusterMember>> unregister(Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> selfUpdate) {
return invoke(Mono.fromCallable(() -> this.localMemberRevision = changeRegistrationStatus(selfUpdate.apply(localMemberRevision.getCurrent()), false)));
}
@Override
public Mono<Void> joinLeadershipGroup() {
return invoke(Mono.fromRunnable(() -> {
if (changeLocalLeadershipState(ClusterMemberLeadershipState.Leader)) {
eventProcessor.onNext(ClusterMembershipEvent.localJoinedElection(localLeadershipRevision));
}
}));
}
@Override
public Mono<Boolean> leaveLeadershipGroup(boolean onlyNonLeader) {
return invoke(Mono.fromCallable(() -> {
if (inLeadershipState(ClusterMemberLeadershipState.Disabled) || onlyNonLeader) {
return false;
}
changeLocalLeadershipState(ClusterMemberLeadershipState.Disabled);
eventProcessor.onNext(ClusterMembershipEvent.leaderLost(localLeadershipRevision));
return true;
}));
}
@Override
public Flux<ClusterMembershipEvent> membershipChangeEvents() {
return eventProcessor.transformDeferred(ReactorExt.head(() -> Collections.singletonList(newSnapshot())));
}
private <T> Mono<T> invoke(Mono<T> action) {
return taskInvoker.submit((Mono) action);
}
private boolean inLeadershipState(ClusterMemberLeadershipState state) {
return localLeadershipRevision.getCurrent().getLeadershipState() == state;
}
private boolean changeLocalLeadershipState(ClusterMemberLeadershipState state) {
if (!inLeadershipState(state)) {
this.localLeadershipRevision = localLeadershipRevision.toBuilder()
.withCurrent(localLeadershipRevision.getCurrent().toBuilder().withLeadershipState(state).build())
.build();
return true;
}
return false;
}
private ClusterMembershipRevision<ClusterMember> changeRegistrationStatus(ClusterMembershipRevision<ClusterMember> revision, boolean registered) {
return revision.toBuilder()
.withCurrent(revision.getCurrent().toBuilder().withRegistered(registered).build())
.withRevision(revisionIdx.incrementAndGet())
.withCode("change")
.withMessage("Registration status change")
.withTimestamp(clock.wallTime())
.build();
}
private ClusterMembershipSnapshotEvent newSnapshot() {
return ClusterMembershipEvent.snapshotEvent(
Collections.singletonList(localMemberRevision),
localLeadershipRevision,
inLeadershipState(ClusterMemberLeadershipState.Leader) ? Optional.of(localLeadershipRevision) : Optional.empty()
);
}
}
| 1,274 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/service/ClusterMembershipServiceConfiguration.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.clustermembership.service;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
@Configuration(prefix = "titus.clusterMembership")
public interface ClusterMembershipServiceConfiguration {
@DefaultValue("1000")
long getHealthCheckEvaluationIntervalMs();
@DefaultValue("5000")
long getHealthCheckEvaluationTimeoutMs();
/**
* Set to false to remove a member from the leader election process. Has no effect for member that is a leader.
*/
@DefaultValue("true")
boolean isLeaderElectionEnabled();
}
| 1,275 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/service/ClusterMembershipTransactionLogger.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.clustermembership.service;
import java.time.Duration;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipChangeEvent;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent;
import com.netflix.titus.api.clustermembership.model.event.LeaderElectionChangeEvent;
import com.netflix.titus.common.util.ExceptionExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.Disposable;
import reactor.core.publisher.BufferOverflowStrategy;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
class ClusterMembershipTransactionLogger {
private static final Logger logger = LoggerFactory.getLogger("ClusterMembershipTransactionLogger");
private static final Duration RETRY_INTERVAL = Duration.ofSeconds(1);
private static final int BUFFER_SIZE = 5000;
static Disposable logEvents(Flux<ClusterMembershipEvent> events) {
Scheduler scheduler = Schedulers.newSingle("ClusterMembershipTransactionLogger");
return events
.onBackpressureBuffer(BUFFER_SIZE, BufferOverflowStrategy.ERROR)
.publishOn(scheduler)
.onErrorResume(e -> {
logger.warn("Transactions may be missing in the log. The event stream has terminated with an error and must be re-subscribed: {}", ExceptionExt.toMessage(e));
return Flux.interval(RETRY_INTERVAL).take(1).flatMap(tick -> events);
})
.subscribe(
event -> logger.info(doFormat(event)),
e -> logger.error("Event stream terminated with an error", e),
() -> logger.info("Event stream completed")
);
}
@VisibleForTesting
static String doFormat(ClusterMembershipEvent event) {
if (event instanceof ClusterMembershipChangeEvent) {
return doFormat((ClusterMembershipChangeEvent) event);
}
if (event instanceof LeaderElectionChangeEvent) {
return doFormat((LeaderElectionChangeEvent) event);
}
return null;
}
private static String doFormat(ClusterMembershipChangeEvent event) {
ClusterMember member = event.getRevision().getCurrent();
return doFormat(
"membership",
member.getMemberId(),
member.isActive() + "",
member.isRegistered() + "",
member.isEnabled() + "",
event.getRevision().getRevision() + "",
"n/a",
"n/a"
);
}
private static String doFormat(LeaderElectionChangeEvent event) {
ClusterMemberLeadership member = event.getLeadershipRevision().getCurrent();
return doFormat(
"leadership",
member.getMemberId(),
"n/a",
"n/a",
"n/a",
"n/a",
member.getLeadershipState().name(),
event.getLeadershipRevision().getRevision() + ""
);
}
private static String doFormat(String eventType,
String memberId,
String memberActive,
String memberRegistered,
String memberEnabled,
String memberRevision,
String leadershipState,
String leadershipRevision) {
return String.format(
"eventType=[%6s] memberId=%s active=%-5s registered=%-5s enabled=%-4s memberRevision=%-8s leadershipState=%-10s leadershipRevision=%s",
eventType,
memberId,
memberActive,
memberRegistered,
memberEnabled,
memberRevision,
leadershipState,
leadershipRevision
);
}
}
| 1,276 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/service/ClusterMembershipServiceComponent.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.clustermembership.service;
import com.netflix.titus.api.clustermembership.connector.ClusterMembershipConnector;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipService;
import com.netflix.titus.api.health.HealthIndicator;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.archaius2.Archaius2Ext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ClusterMembershipServiceComponent {
@Bean
public ClusterMembershipServiceConfiguration getClusterMembershipServiceConfigurationBean(TitusRuntime titusRuntime) {
return Archaius2Ext.newConfiguration(ClusterMembershipServiceConfiguration.class, "titus.clusterMembership", titusRuntime.getMyEnvironment());
}
@Bean
public ClusterMembershipService getClusterMembershipService(ClusterMembershipServiceConfiguration configuration,
ClusterMembershipConnector connector,
HealthIndicator healthIndicator,
TitusRuntime titusRuntime) {
return new DefaultClusterMembershipService(configuration, connector, healthIndicator, titusRuntime);
}
}
| 1,277 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/service/DefaultClusterMembershipService.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.clustermembership.service;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.titus.api.clustermembership.connector.ClusterMembershipConnector;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
import com.netflix.titus.api.clustermembership.model.event.ClusterMembershipEvent;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipService;
import com.netflix.titus.api.clustermembership.service.ClusterMembershipServiceException;
import com.netflix.titus.api.health.HealthIndicator;
import com.netflix.titus.api.health.HealthState;
import com.netflix.titus.api.health.HealthStatus;
import com.netflix.titus.common.framework.scheduler.ExecutionContext;
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.retry.Retryers;
import com.netflix.titus.common.util.rx.ReactorExt;
import com.netflix.titus.common.util.time.Clock;
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.Schedulers;
@Singleton
public class DefaultClusterMembershipService implements ClusterMembershipService {
private static final Logger logger = LoggerFactory.getLogger(DefaultClusterMembershipService.class);
private static final Duration HEALTH_CHECK_INITIAL = Duration.ofMillis(1000);
private static final Duration HEALTH_CHECK_TIMEOUT = Duration.ofMillis(2000);
private static final ScheduleDescriptor HEALTH_CHECK_SCHEDULE_DESCRIPTOR = ScheduleDescriptor.newBuilder()
.withName("ClusterMembershipHealthCheck")
.withInitialDelay(Duration.ZERO)
.withInterval(HEALTH_CHECK_INITIAL)
.withTimeout(HEALTH_CHECK_TIMEOUT)
.withDescription("Evaluates local member health and updates the membership state if needed")
.withRetryerSupplier(Retryers::never)
.build();
private final ClusterMembershipServiceConfiguration configuration;
private final ClusterMembershipConnector connector;
private final HealthIndicator healthIndicator;
private final ClusterMembershipServiceMetrics metrics;
private final Clock clock;
private final ScheduleReference healthScheduleRef;
private final Disposable transactionLogDisposable;
@Inject
public DefaultClusterMembershipService(ClusterMembershipServiceConfiguration configuration,
ClusterMembershipConnector connector,
HealthIndicator healthIndicator,
TitusRuntime titusRuntime) {
this.configuration = configuration;
this.connector = connector;
this.healthIndicator = healthIndicator;
this.metrics = new ClusterMembershipServiceMetrics(titusRuntime);
this.clock = titusRuntime.getClock();
this.healthScheduleRef = titusRuntime.getLocalScheduler().scheduleMono(
HEALTH_CHECK_SCHEDULE_DESCRIPTOR.toBuilder()
.withInterval(Duration.ofMillis(configuration.getHealthCheckEvaluationIntervalMs()))
.withTimeout(Duration.ofMillis(configuration.getHealthCheckEvaluationTimeoutMs()))
.build(),
this::clusterStateEvaluator,
Schedulers.parallel()
);
this.transactionLogDisposable = ClusterMembershipTransactionLogger.logEvents(connector.membershipChangeEvents());
}
public void shutdown() {
metrics.shutdown();
healthScheduleRef.cancel();
ReactorExt.safeDispose(transactionLogDisposable);
}
@Override
public ClusterMembershipRevision<ClusterMember> getLocalClusterMember() {
try {
return connector.getLocalClusterMemberRevision();
} catch (Exception e) {
throw ClusterMembershipServiceException.internalError(e);
}
}
@Override
public Map<String, ClusterMembershipRevision<ClusterMember>> getClusterMemberSiblings() {
try {
return connector.getClusterMemberSiblings();
} catch (Exception e) {
throw ClusterMembershipServiceException.internalError(e);
}
}
@Override
public ClusterMembershipRevision<ClusterMemberLeadership> getLocalLeadership() {
try {
return connector.getLocalLeadershipRevision();
} catch (Exception e) {
throw ClusterMembershipServiceException.internalError(e);
}
}
@Override
public Optional<ClusterMembershipRevision<ClusterMemberLeadership>> findLeader() {
try {
return connector.findCurrentLeader();
} catch (Exception e) {
throw ClusterMembershipServiceException.internalError(e);
}
}
@Override
public Mono<ClusterMembershipRevision<ClusterMember>> updateSelf(Function<ClusterMember, ClusterMembershipRevision<ClusterMember>> memberUpdate) {
return connector.register(memberUpdate).onErrorMap(ClusterMembershipServiceException::selfUpdateError);
}
@Override
public Mono<Void> stopBeingLeader() {
return connector.leaveLeadershipGroup(false)
.ignoreElement()
.cast(Void.class)
.onErrorMap(ClusterMembershipServiceException::internalError);
}
@Override
public Flux<ClusterMembershipEvent> events() {
return connector.membershipChangeEvents();
}
private Mono<Void> clusterStateEvaluator(ExecutionContext context) {
return Mono.defer(() -> {
ClusterMember localMember = connector.getLocalClusterMemberRevision().getCurrent();
ClusterMemberLeadershipState localLeadershipState = connector.getLocalLeadershipRevision().getCurrent().getLeadershipState();
HealthStatus health = healthIndicator.health();
// Explicitly disabled
if (!configuration.isLeaderElectionEnabled() || !localMember.isEnabled()) {
if (localLeadershipState == ClusterMemberLeadershipState.NonLeader) {
logger.info("Local member excluded from the leader election. Leaving the leader election process");
return connector.leaveLeadershipGroup(true).flatMap(success ->
success
? connector.register(current -> toInactive(current, "Marked by a user as disabled")).ignoreElement().cast(Void.class)
: Mono.empty()
);
}
if (localLeadershipState == ClusterMemberLeadershipState.Disabled && localMember.isActive()) {
return connector.register(current -> toInactive(current, "Marked by a user as disabled")).ignoreElement().cast(Void.class);
}
return Mono.empty();
}
// Re-enable if healthy
if (health.getHealthState() == HealthState.Healthy) {
if (localLeadershipState == ClusterMemberLeadershipState.Disabled) {
logger.info("Re-enabling local member which is in the disabled state");
return connector.joinLeadershipGroup()
.then(connector.register(this::toActive).ignoreElement().cast(Void.class));
}
if (!localMember.isActive()) {
return connector.register(this::toActive).ignoreElement().cast(Void.class);
}
return Mono.empty();
}
// Disable if unhealthy (and not the leader)
if (localLeadershipState != ClusterMemberLeadershipState.Disabled && localLeadershipState != ClusterMemberLeadershipState.Leader) {
logger.info("Disabling local member as it is unhealthy: {}", health);
return connector.leaveLeadershipGroup(true).flatMap(success ->
success
? connector.register(current -> toInactive(current, "Unhealthy: " + health)).ignoreElement().cast(Void.class)
: Mono.empty()
);
}
if (localLeadershipState == ClusterMemberLeadershipState.Disabled && localMember.isActive()) {
return connector.register(current -> toInactive(current, "Unhealthy: " + health)).ignoreElement().cast(Void.class);
}
return Mono.empty();
}).doOnError(error -> {
logger.info("Cluster membership health evaluation error: {}", error.getMessage());
logger.debug("Stack trace", error);
}).doOnTerminate(() -> {
metrics.updateLocal(
connector.getLocalLeadershipRevision().getCurrent().getLeadershipState(),
healthIndicator.health()
);
metrics.updateSiblings(connector.getClusterMemberSiblings());
});
}
private ClusterMembershipRevision<ClusterMember> toActive(ClusterMember current) {
return ClusterMembershipRevision.<ClusterMember>newBuilder()
.withCurrent(current.toBuilder().withActive(true).build())
.withCode("activated")
.withMessage("Activated")
.withTimestamp(clock.wallTime())
.build();
}
private ClusterMembershipRevision<ClusterMember> toInactive(ClusterMember current, String cause) {
return ClusterMembershipRevision.<ClusterMember>newBuilder()
.withCurrent(current.toBuilder().withActive(false).build())
.withCode("deactivated")
.withMessage(cause)
.withTimestamp(clock.wallTime())
.build();
}
}
| 1,278 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/clustermembership/service/ClusterMembershipServiceMetrics.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.clustermembership.service;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.titus.api.clustermembership.model.ClusterMember;
import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState;
import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision;
import com.netflix.titus.api.health.HealthState;
import com.netflix.titus.api.health.HealthStatus;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.spectator.SpectatorExt;
import com.netflix.titus.common.util.time.Clock;
/**
* Companion object to {@link DefaultClusterMembershipService}.
*/
final class ClusterMembershipServiceMetrics {
public static final String METRIC_ROOT = "titus.clusterMembership.service.";
private final Registry registry;
private final Clock clock;
private final SpectatorExt.FsmMetrics<ClusterMemberLeadershipState> leadershipFsmMetrics;
private final SpectatorExt.FsmMetrics<HealthState> healthFsmMetrics;
private final Id knownSiblingsId;
private final AtomicLong knownSiblingsCounter = new AtomicLong();
private final Id siblingStalenessId;
private final ConcurrentMap<String, Gauge> siblingStaleness = new ConcurrentHashMap<>();
ClusterMembershipServiceMetrics(TitusRuntime titusRuntime) {
// known members count
this.registry = titusRuntime.getRegistry();
this.clock = titusRuntime.getClock();
this.healthFsmMetrics = SpectatorExt.fsmMetrics(
registry.createId(METRIC_ROOT + "localHealthState"),
s -> false,
HealthState.Unknown,
registry
);
this.leadershipFsmMetrics = SpectatorExt.fsmMetrics(
registry.createId(METRIC_ROOT + "localLeadershipState"),
s -> false,
ClusterMemberLeadershipState.Unknown,
registry
);
this.knownSiblingsId = registry.createId(METRIC_ROOT + "knownSiblings");
this.siblingStalenessId = registry.createId(METRIC_ROOT + "siblingStaleness");
PolledMeter.using(registry).withId(knownSiblingsId).monitorValue(knownSiblingsCounter);
}
void shutdown() {
PolledMeter.remove(registry, knownSiblingsId);
updateSiblings(Collections.emptyMap());
}
void updateLocal(ClusterMemberLeadershipState localLeadershipState, HealthStatus health) {
leadershipFsmMetrics.transition(localLeadershipState);
healthFsmMetrics.transition(health.getHealthState());
}
void updateSiblings(Map<String, ClusterMembershipRevision<ClusterMember>> clusterMemberSiblings) {
knownSiblingsCounter.set(clusterMemberSiblings.size());
long now = clock.wallTime();
clusterMemberSiblings.forEach((memberId, sibling) ->
siblingStaleness.computeIfAbsent(
memberId,
id -> registry.gauge(siblingStalenessId.withTag("memberId", memberId))
).set(now - sibling.getTimestamp())
);
siblingStaleness.forEach((memberId, gauge) -> {
if (!clusterMemberSiblings.containsKey(memberId)) {
gauge.set(0);
}
});
siblingStaleness.keySet().retainAll(clusterMemberSiblings.keySet());
}
}
| 1,279 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/health/AlwaysHealthyComponent.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.health;
import com.netflix.titus.api.health.HealthIndicator;
import com.netflix.titus.api.health.HealthIndicators;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AlwaysHealthyComponent {
@Bean
public HealthIndicator getHealthIndicator() {
return HealthIndicators.alwaysHealthy();
}
}
| 1,280 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/fit/FitResource.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.fit;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.netflix.titus.common.framework.fit.FitAction;
import com.netflix.titus.common.framework.fit.FitComponent;
import com.netflix.titus.common.framework.fit.FitFramework;
import com.netflix.titus.common.framework.fit.FitInjection;
import com.netflix.titus.common.framework.fit.FitUtil;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.runtime.Fit;
@Path("/api/diagnostic/fit")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Singleton
public class FitResource {
private final FitFramework fitFramework;
@Inject
public FitResource(TitusRuntime titusRuntime) {
this.fitFramework = titusRuntime.getFitFramework();
}
@GET
@Path("/components")
public Fit.FitComponent getFitComponents() {
return ProtobufFitConverters.toGrpcFitComponent(fitFramework.getRootComponent());
}
@GET
@Path("/actionDescriptors")
public List<Fit.FitActionDescriptor> getFitActionDescriptors() {
return fitFramework.getFitRegistry().getFitActionDescriptors().stream()
.map(ProtobufFitConverters::toGrpcFitActionDescriptor)
.collect(Collectors.toList());
}
@GET
@Path("/actions")
public List<Fit.FitAction> getActions() {
return findAllActions(fitFramework.getRootComponent()).stream().map(ProtobufFitConverters::toGrpcFitAction).collect(Collectors.toList());
}
@POST
@Path("/actions")
public Response addAction(Fit.AddAction request) {
FitComponent fitComponent = FitUtil.getFitComponentOrFail(fitFramework, request.getComponentId());
FitInjection fitInjection = FitUtil.getFitInjectionOrFail(request.getInjectionId(), fitComponent);
Function<FitInjection, FitAction> fitActionFactory = fitFramework.getFitRegistry().newFitActionFactory(
request.getActionKind(), request.getActionId(), request.getPropertiesMap()
);
fitInjection.addAction(fitActionFactory.apply(fitInjection));
return Response.noContent().build();
}
@DELETE
@Path("/actions/{actionId}")
public Response deleteAction(@PathParam("actionId") String actionId,
@QueryParam("componentId") String componentId,
@QueryParam("injectionId") String injectionId) {
FitInjection fitInjection = FitUtil.getFitInjectionOrFail(injectionId, FitUtil.getFitComponentOrFail(fitFramework, componentId));
fitInjection.removeAction(FitUtil.getFitActionOrFail(actionId, fitInjection).getId());
return Response.noContent().build();
}
private List<FitAction> findAllActions(FitComponent fitComponent) {
List<FitAction> result = new ArrayList<>();
fitComponent.getInjections().forEach(i -> result.addAll(i.getActions()));
fitComponent.getChildren().forEach(c -> result.addAll(findAllActions(c)));
return result;
}
}
| 1,281 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/fit/ProtobufFitConverters.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.fit;
import com.netflix.titus.common.framework.fit.FitAction;
import com.netflix.titus.common.framework.fit.FitActionDescriptor;
import com.netflix.titus.common.framework.fit.FitComponent;
import com.netflix.titus.common.framework.fit.FitInjection;
import com.netflix.titus.runtime.Fit;
public final class ProtobufFitConverters {
private ProtobufFitConverters() {
}
public static Fit.FitActionDescriptor toGrpcFitActionDescriptor(FitActionDescriptor fitActionDescriptor) {
return Fit.FitActionDescriptor.newBuilder()
.setKind(fitActionDescriptor.getKind())
.setDescription(fitActionDescriptor.getDescription())
.putAllConfigurableProperties(fitActionDescriptor.getConfigurableProperties())
.build();
}
public static Fit.FitComponent toGrpcFitComponent(FitComponent coreFitComponent) {
Fit.FitComponent.Builder builder = Fit.FitComponent.newBuilder()
.setId(coreFitComponent.getId());
coreFitComponent.getInjections().forEach(i -> builder.addInjections(toGrpcFitInjection(i)));
coreFitComponent.getChildren().forEach(c -> builder.addChildren(toGrpcFitComponent(c)));
return builder.build();
}
public static Fit.FitInjection toGrpcFitInjection(FitInjection coreFitInjection) {
Fit.FitInjection.Builder builder = Fit.FitInjection.newBuilder()
.setId(coreFitInjection.getId());
coreFitInjection.getActions().forEach(a -> builder.addFitActions(toGrpcFitAction(a)));
return builder.build();
}
public static Fit.FitAction toGrpcFitAction(FitAction coreFitAction) {
return Fit.FitAction.newBuilder()
.setId(coreFitAction.getId())
.setActionKind(coreFitAction.getDescriptor().getKind())
.putAllProperties(coreFitAction.getProperties())
.build();
}
}
| 1,282 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/GrpcExceptionMapper.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.net.SocketException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.google.protobuf.Any;
import com.google.rpc.DebugInfo;
import com.netflix.titus.common.util.tuple.Pair;
import io.grpc.Metadata;
import io.grpc.Status;
import rx.exceptions.CompositeException;
import static java.util.Arrays.stream;
/**
* TODO Map data validation errors to FieldViolation GRPC message, after the validation framework is moved to titus-common.
*/
public class GrpcExceptionMapper {
public static final String X_TITUS_DEBUG = "X-Titus-Debug";
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_DEBUG = Metadata.Key.of(X_TITUS_DEBUG, Metadata.ASCII_STRING_MARSHALLER);
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 final List<Function<Throwable, Optional<Status>>> serviceExceptionMappers;
public GrpcExceptionMapper(List<Function<Throwable, Optional<Status>>> serviceExceptionMappers) {
this.serviceExceptionMappers = serviceExceptionMappers;
}
public Pair<Status, Metadata> of(Throwable t, boolean debug) {
Throwable exception = unwrap(t);
Status status = toGrpcStatus(exception)
.withDescription(getNonNullMessage(exception))
.withCause(exception);
int errorCode = status.getCode().value();
Metadata metadata = buildMetadata(exception, errorCode, debug);
return Pair.of(status, metadata);
}
public Pair<Status, Metadata> of(Status status, Metadata trailers, boolean debug) {
Throwable cause = unwrap(status.getCause());
if (cause == null) {
return Pair.of(status, trailers);
}
Status newStatus = toGrpcStatus(cause)
.withDescription(getNonNullMessage(cause))
.withCause(cause);
Metadata metadata = buildMetadata(newStatus.getCause(), newStatus.getCode().value(), debug);
metadata.merge(trailers);
return Pair.of(newStatus, metadata);
}
private Metadata buildMetadata(Throwable exception, int errorCode, boolean debug) {
Metadata metadata = new Metadata();
metadata.put(KEY_TITUS_ERROR_REPORT, getNonNullMessage(exception));
if (debug) {
metadata.put(KEY_TITUS_ERROR_REPORT_BIN, buildRpcStatus(exception, errorCode).toByteArray());
}
return metadata;
}
private com.google.rpc.Status buildRpcStatus(Throwable exception, int errorCode) {
com.google.rpc.Status.Builder builder = com.google.rpc.Status.newBuilder()
.setCode(errorCode)
.setMessage(getNonNullMessage(exception));
DebugInfo debugInfo = DebugInfo.newBuilder()
.addAllStackEntries(stream(exception.getStackTrace()).map(StackTraceElement::toString).collect(Collectors.toList()))
.build();
builder.addDetails(Any.pack(debugInfo));
return builder.build();
}
private Status toGrpcStatus(Throwable original) {
Throwable cause = unwrap(original);
if (cause instanceof SocketException) {
return Status.UNAVAILABLE;
} else if (cause instanceof TimeoutException) {
return Status.DEADLINE_EXCEEDED;
}
for (Function<Throwable, Optional<Status>> mapper : serviceExceptionMappers) {
Status status = mapper.apply(cause).orElse(null);
if (status != null) {
return status;
}
}
return Status.INTERNAL;
}
private static String getNonNullMessage(Throwable t) {
Throwable e = unwrap(t);
return e.getMessage() == null
? e.getClass().getSimpleName() + " (no message)"
: e.getClass().getSimpleName() + ": " + e.getMessage();
}
private static Throwable unwrap(Throwable throwable) {
if (throwable instanceof CompositeException) {
CompositeException composite = (CompositeException) throwable;
if (composite.getExceptions().size() == 1) {
return composite.getExceptions().get(0);
}
}
return throwable;
}
}
| 1,283 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/CommonGrpcEndpointConfiguration.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 com.netflix.archaius.api.annotations.DefaultValue;
public interface CommonGrpcEndpointConfiguration {
@DefaultValue("7104")
int getPort();
/**
* Graceful shutdown time for GRPC server. If zero, shutdown happens immediately, and all client connections are
* terminated abruptly.
*/
@DefaultValue("30000")
long getShutdownTimeoutMs();
/**
* Maximum amount of time a client connection may last. Connections not disconnected by client after this time
* passes, are closed by server. The clients are expected to reconnect if that happens.
*/
@DefaultValue("1800000")
long getMaxConnectionAgeMs();
}
| 1,284 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/GrpcUtil.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.grpc;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import com.google.protobuf.Empty;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.endpoint.metadata.V3HeaderInterceptor;
import io.grpc.CallOptions;
import io.grpc.ClientCall;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import io.grpc.stub.AbstractStub;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.ServerCallStreamObserver;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import reactor.core.Disposable;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoSink;
import rx.Completable;
import rx.Emitter;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
public class GrpcUtil {
private static final String CANCELLING_MESSAGE = "Cancelling the call";
/**
* For request/response GRPC calls, we set execution deadline at both RxJava and GRPC level. As we prefer the timeout
* be triggered by GRPC, which may give us potentially more insight, we adjust RxJava timeout value by this factor.
*/
private static final double RX_CLIENT_TIMEOUT_FACTOR = 1.2;
public static <T> void safeOnError(Logger logger, Throwable error, StreamObserver<T> responseObserver) {
try {
responseObserver.onError(error);
} catch (Exception e) {
if (e instanceof IllegalStateException) { // Stream most likely closed, which is ok
logger.info(e.getMessage());
} else {
logger.error("Error during writing error to StreamObserver", e);
}
}
}
public static <REQ, RESP> ClientResponseObserver<REQ, RESP> createSimpleClientResponseObserver(Emitter<RESP> emitter) {
return createClientResponseObserver(
emitter,
emitter::onNext,
emitter::onError,
emitter::onCompleted
);
}
public static <REQ> ClientResponseObserver<REQ, Empty> createEmptyClientResponseObserver(Emitter<Empty> emitter) {
return createClientResponseObserver(
emitter,
ignored -> {
},
emitter::onError,
emitter::onCompleted
);
}
public static <REQ> ClientResponseObserver<REQ, Empty> createEmptyClientMonoResponse(MonoSink<Empty> monoSink) {
return createClientResponseObserver(
requestStream -> monoSink.onCancel(() -> requestStream.cancel(CANCELLING_MESSAGE, null)),
monoSink::success,
monoSink::error,
monoSink::success
);
}
public static <REQ, RESP> ClientResponseObserver<REQ, RESP> createClientResponseObserver(Emitter<?> emitter,
final Action1<? super RESP> onNext,
final Action1<Throwable> onError,
final Action0 onCompleted) {
return createClientResponseObserver(
requestStream -> emitter.setCancellation(() -> requestStream.cancel(CANCELLING_MESSAGE, null)),
onNext,
onError,
onCompleted
);
}
public static <REQ, RESP> ClientResponseObserver<REQ, RESP> createClientResponseObserver(final Action1<ClientCallStreamObserver<REQ>> beforeStart,
final Action1<? super RESP> onNext,
final Action1<Throwable> onError,
final Action0 onCompleted) {
return new ClientResponseObserver<REQ, RESP>() {
@Override
public void beforeStart(ClientCallStreamObserver<REQ> requestStream) {
beforeStart.call(requestStream);
}
@Override
public void onNext(RESP value) {
onNext.call(value);
}
@Override
public void onError(Throwable t) {
onError.call(t);
}
@Override
public void onCompleted() {
onCompleted.call();
}
};
}
public static <STUB extends AbstractStub<STUB>> STUB createWrappedStub(STUB client,
CallMetadata callMetadata,
long deadlineMs) {
return createWrappedStub(client, callMetadata).withDeadlineAfter(deadlineMs, TimeUnit.MILLISECONDS);
}
public static <STUB extends AbstractStub<STUB>> STUB createWrappedStub(STUB client, CallMetadata callMetadata) {
return V3HeaderInterceptor.attachCallMetadata(client, callMetadata);
}
@Deprecated
public static <STUB extends AbstractStub<STUB>> STUB createWrappedStubWithResolver(STUB client,
CallMetadataResolver callMetadataResolver,
long deadlineMs) {
return createWrappedStubWithResolver(client, callMetadataResolver).withDeadlineAfter(deadlineMs, TimeUnit.MILLISECONDS);
}
@Deprecated
public static <STUB extends AbstractStub<STUB>> STUB createWrappedStubWithResolver(STUB client, CallMetadataResolver callMetadataResolver) {
return callMetadataResolver.resolve()
.map(caller -> V3HeaderInterceptor.attachCallMetadata(client, caller))
.orElse(client);
}
public static <O> Observable<O> toObservable(BiConsumer<Empty, StreamObserver<O>> grpcServiceMethod) {
return toObservable(Empty.getDefaultInstance(), grpcServiceMethod);
}
public static <I, O> Observable<O> toObservable(I input, BiConsumer<I, StreamObserver<O>> grpcServiceMethod) {
return Observable.create(emitter -> {
StreamObserver<O> streamObserver = new StreamObserver<O>() {
@Override
public void onNext(O value) {
emitter.onNext(value);
}
@Override
public void onError(Throwable t) {
emitter.onError(t);
}
@Override
public void onCompleted() {
emitter.onCompleted();
}
};
grpcServiceMethod.accept(input, streamObserver);
}, Emitter.BackpressureMode.NONE);
}
public static void attachCancellingCallback(Emitter emitter, ClientCall... clientCalls) {
emitter.setCancellation(() -> {
for (ClientCall call : clientCalls) {
call.cancel(CANCELLING_MESSAGE, null);
}
});
}
public static void attachCancellingCallback(Emitter emitter, ClientCallStreamObserver... clientCalls) {
emitter.setCancellation(() -> {
for (ClientCallStreamObserver call : clientCalls) {
call.cancel(CANCELLING_MESSAGE, null);
}
});
}
public static void attachCancellingCallback(StreamObserver responseObserver, Subscription subscription) {
ServerCallStreamObserver serverObserver = (ServerCallStreamObserver) responseObserver;
serverObserver.setOnCancelHandler(subscription::unsubscribe);
}
public static void attachCancellingCallback(StreamObserver responseObserver, Disposable disposable) {
ServerCallStreamObserver serverObserver = (ServerCallStreamObserver) responseObserver;
serverObserver.setOnCancelHandler(disposable::dispose);
}
public static <T> Observable<T> createRequestObservable(Action1<Emitter<T>> emitter) {
return Observable.create(
emitter,
Emitter.BackpressureMode.NONE
);
}
public static <T> Observable<T> createRequestObservable(Action1<Emitter<T>> emitter, long timeout) {
return createRequestObservable(emitter).timeout(getRxJavaAdjustedTimeout(timeout), TimeUnit.MILLISECONDS);
}
public static Completable createRequestCompletable(Action1<Emitter<Empty>> emitter, long timeout) {
return createRequestObservable(emitter, timeout).toCompletable();
}
public static Mono<Empty> createMonoVoidRequest(Consumer<MonoSink<Empty>> sinkConsumer, long timeout) {
return Mono.create(sinkConsumer).timeout(getRxJavaAdjustedDuration(timeout));
}
public static long getRxJavaAdjustedTimeout(long initialTimeoutMs) {
return (long) (initialTimeoutMs * RX_CLIENT_TIMEOUT_FACTOR);
}
public static Duration getRxJavaAdjustedDuration(long initialTimeoutMs) {
return Duration.ofMillis((long) (initialTimeoutMs * RX_CLIENT_TIMEOUT_FACTOR));
}
public static boolean isNotOK(Status oneStatus) {
return !Status.Code.OK.equals(oneStatus.getCode());
}
}
| 1,285 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/TitusGrpcServer.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.io.IOException;
import java.net.SocketException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.framework.fit.adapter.GrpcFitInterceptor;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.Evaluators;
import com.netflix.titus.runtime.endpoint.common.grpc.interceptor.CommonErrorCatchingServerInterceptor;
import com.netflix.titus.runtime.endpoint.metadata.V3HeaderInterceptor;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerInterceptor;
import io.grpc.ServerInterceptors;
import io.grpc.ServerServiceDefinition;
import io.grpc.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TitusGrpcServer {
private static final Logger logger = LoggerFactory.getLogger(TitusGrpcServer.class);
private static final Duration DEFAULT_SHUTDOWN_TIME = Duration.ofSeconds(5);
private final Duration shutdownTime;
private final Server server;
private final AtomicBoolean started = new AtomicBoolean();
private TitusGrpcServer(Server server,
Duration shutdownTime) {
this.server = server;
this.shutdownTime = Evaluators.getOrDefault(shutdownTime, DEFAULT_SHUTDOWN_TIME);
}
public int getPort() {
return server.getPort();
}
@PostConstruct
public void start() {
if (!started.getAndSet(true)) {
logger.info("Starting GRPC server {}...", getClass().getSimpleName());
try {
this.server.start();
} catch (final IOException e) {
throw new RuntimeException(e);
}
logger.info("Started {} on port {}.", getClass().getSimpleName(), getPort());
}
}
@PreDestroy
public void shutdown() {
if (!server.isShutdown()) {
if (shutdownTime.toMillis() <= 0) {
server.shutdownNow();
} else {
server.shutdown();
try {
server.awaitTermination(shutdownTime.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException ignore) {
}
if (!server.isShutdown()) {
server.shutdownNow();
}
}
}
}
public static Builder newBuilder(int port, TitusRuntime titusRuntime) {
return new Builder().withPort(port).withTitusRuntime(titusRuntime);
}
public static class Builder {
private int port;
private TitusRuntime titusRuntime;
private final Map<String, ServiceBuilder> serviceBuilders = new HashMap<>();
private final List<ServerInterceptor> interceptors = new ArrayList<>();
private final List<Function<Throwable, Optional<Status>>> serviceExceptionMappers = new ArrayList<>();
private Duration shutdownTime;
private final List<UnaryOperator<ServerBuilder>> serverConfigurers = new ArrayList<>();
private Builder() {
// Add default exception mappings.
serviceExceptionMappers.add(cause -> {
if (cause instanceof SocketException) {
return Optional.of(Status.UNAVAILABLE);
} else if (cause instanceof TimeoutException) {
return Optional.of(Status.DEADLINE_EXCEEDED);
}
return Optional.empty();
});
}
public Builder withPort(int port) {
this.port = port;
return this;
}
public Builder withTitusRuntime(TitusRuntime titusRuntime) {
this.titusRuntime = titusRuntime;
return this;
}
public Builder withShutdownTime(Duration shutdownTime) {
this.shutdownTime = shutdownTime;
return this;
}
public Builder withServerConfigurer(UnaryOperator<ServerBuilder> serverConfigurer) {
this.serverConfigurers.add(serverConfigurer);
return this;
}
public Builder withCallMetadataInterceptor() {
interceptors.add(new V3HeaderInterceptor());
return this;
}
public Builder withExceptionMapper(Function<Throwable, Optional<Status>> serviceExceptionMapper) {
serviceExceptionMappers.add(serviceExceptionMapper);
return this;
}
public Builder withInterceptor(ServerInterceptor serverInterceptor) {
interceptors.add(serverInterceptor);
return this;
}
public Builder withService(ServerServiceDefinition serviceDefinition, List<ServerInterceptor> interceptors) {
serviceBuilders.put(serviceDefinition.getServiceDescriptor().getName(), new ServiceBuilder(serviceDefinition, interceptors));
return this;
}
public TitusGrpcServer build() {
Preconditions.checkArgument(port >= 0, "Port number is negative");
Preconditions.checkNotNull(titusRuntime, "TitusRuntime not set");
List<ServerInterceptor> commonInterceptors = new ArrayList<>();
commonInterceptors.add(new CommonErrorCatchingServerInterceptor(new GrpcExceptionMapper(serviceExceptionMappers)));
GrpcFitInterceptor.getIfFitEnabled(titusRuntime).ifPresent(commonInterceptors::add);
commonInterceptors.addAll(interceptors);
ServerBuilder serverBuilder = ServerBuilder.forPort(port);
for (UnaryOperator<ServerBuilder> c : serverConfigurers) {
c.apply(serverBuilder);
}
for (ServiceBuilder serviceBuilder : serviceBuilders.values()) {
serverBuilder.addService(serviceBuilder.build(commonInterceptors));
}
return new TitusGrpcServer(serverBuilder.build(), shutdownTime);
}
}
private static class ServiceBuilder {
private final ServerServiceDefinition serviceDefinition;
private final List<ServerInterceptor> interceptors;
private ServiceBuilder(ServerServiceDefinition serviceDefinition, List<ServerInterceptor> interceptors) {
this.serviceDefinition = serviceDefinition;
this.interceptors = interceptors;
}
private ServerServiceDefinition build(List<ServerInterceptor> commonInterceptors) {
return ServerInterceptors.intercept(
serviceDefinition,
CollectionsExt.merge(commonInterceptors, interceptors)
);
}
}
}
| 1,286 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/assistant/GrpcCallAssistantComponent.java | package com.netflix.titus.runtime.endpoint.common.grpc.assistant;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.endpoint.resolver.HostCallerIdResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GrpcCallAssistantComponent {
@Bean
public GrpcClientCallAssistantFactory getGrpcClientCallAssistantFactory(GrpcCallAssistantConfiguration configuration,
CallMetadataResolver callMetadataResolver) {
return new DefaultGrpcClientCallAssistantFactory(configuration, callMetadataResolver);
}
@Bean
public GrpcServerCallAssistant getGrpcServerCallAssistant(CallMetadataResolver callMetadataResolver,
HostCallerIdResolver hostCallerIdResolver) {
return new DefaultGrpcServerCallAssistant(callMetadataResolver, hostCallerIdResolver);
}
}
| 1,287 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/assistant/DefaultGrpcClientCallAssistantFactory.java | package com.netflix.titus.runtime.endpoint.common.grpc.assistant;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import io.grpc.stub.AbstractStub;
public class DefaultGrpcClientCallAssistantFactory implements GrpcClientCallAssistantFactory {
private final GrpcCallAssistantConfiguration configuration;
private final CallMetadataResolver callMetadataResolver;
public DefaultGrpcClientCallAssistantFactory(GrpcCallAssistantConfiguration configuration,
CallMetadataResolver callMetadataResolver) {
this.configuration = configuration;
this.callMetadataResolver = callMetadataResolver;
}
@Override
public <STUB extends AbstractStub<STUB>> GrpcClientCallAssistant<STUB> create(STUB stub) {
return new DefaultGrpcClientCallAssistant<>(
configuration,
stub,
callMetadataResolver
);
}
}
| 1,288 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/assistant/GrpcServerCallContext.java | package com.netflix.titus.runtime.endpoint.common.grpc.assistant;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
public class GrpcServerCallContext {
private final CallMetadata callMetadata;
private final String callerAddress;
private final String callerApplicationName;
GrpcServerCallContext(CallMetadata callMetadata, String callerAddress, String callerApplicationName) {
this.callMetadata = callMetadata;
this.callerAddress = callerAddress;
this.callerApplicationName = callerApplicationName;
}
public CallMetadata getCallMetadata() {
return callMetadata;
}
public String getCallerAddress() {
return callerAddress;
}
public String getCallerApplicationName() {
return callerApplicationName;
}
}
| 1,289 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/assistant/GrpcServerCallAssistant.java | package com.netflix.titus.runtime.endpoint.common.grpc.assistant;
import java.util.function.BiConsumer;
import java.util.function.Function;
import com.google.protobuf.Empty;
import io.grpc.stub.StreamObserver;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface GrpcServerCallAssistant {
<T> void callMono(StreamObserver<T> streamObserver, Function<GrpcServerCallContext, Mono<T>> monoResponse);
void callMonoEmpty(StreamObserver<Empty> streamObserver, Function<GrpcServerCallContext, Mono<Void>> monoResponse);
<T> void callFlux(StreamObserver<T> streamObserver, Function<GrpcServerCallContext, Flux<T>> fluxResponse);
<T> void callDirect(StreamObserver<T> streamObserver, Function<GrpcServerCallContext, T> responseFunction);
<T> void inContext(StreamObserver<T> streamObserver,
BiConsumer<GrpcServerCallContext, T> onSuccess,
BiConsumer<GrpcServerCallContext, Throwable> onError,
BiConsumer<GrpcServerCallContext, StreamObserver<T>> context);
}
| 1,290 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/assistant/GrpcClientCallAssistant.java | package com.netflix.titus.runtime.endpoint.common.grpc.assistant;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import com.google.protobuf.Empty;
import io.grpc.stub.AbstractStub;
import io.grpc.stub.StreamObserver;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface GrpcClientCallAssistant<STUB extends AbstractStub<STUB>> {
<T> Mono<T> asMono(BiConsumer<STUB, StreamObserver<T>> grpcInvoker);
Mono<Void> asMonoEmpty(BiConsumer<STUB, StreamObserver<Empty>> grpcInvoker);
<T> Flux<T> asFlux(BiConsumer<STUB, StreamObserver<T>> grpcInvoker);
<T> Flux<T> callFlux(Function<STUB, Flux<T>> grpcExecutor);
void inContext(Consumer<STUB> grpcExecutor);
}
| 1,291 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/assistant/GrpcCallAssistantConfiguration.java | package com.netflix.titus.runtime.endpoint.common.grpc.assistant;
import com.netflix.archaius.api.annotations.DefaultValue;
public interface GrpcCallAssistantConfiguration {
@DefaultValue("10000")
long getRequestTimeoutMs();
@DefaultValue("1800000")
long getStreamTimeoutMs();
}
| 1,292 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/assistant/GrpcClientCallAssistantFactory.java | package com.netflix.titus.runtime.endpoint.common.grpc.assistant;
import io.grpc.stub.AbstractStub;
public interface GrpcClientCallAssistantFactory {
<STUB extends AbstractStub<STUB>> GrpcClientCallAssistant<STUB> create(STUB stub);
}
| 1,293 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/assistant/DefaultGrpcServerCallAssistant.java | package com.netflix.titus.runtime.endpoint.common.grpc.assistant;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import com.google.common.collect.Iterables;
import com.google.protobuf.Empty;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.api.model.callmetadata.CallMetadataConstants;
import com.netflix.titus.api.model.callmetadata.Caller;
import com.netflix.titus.api.model.callmetadata.CallerType;
import com.netflix.titus.common.util.Evaluators;
import com.netflix.titus.common.util.ExceptionExt;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataHeaders;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.endpoint.metadata.V3HeaderInterceptor;
import com.netflix.titus.runtime.endpoint.resolver.HostCallerIdResolver;
import io.grpc.stub.ServerCallStreamObserver;
import io.grpc.stub.StreamObserver;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class DefaultGrpcServerCallAssistant implements GrpcServerCallAssistant {
private final CallMetadataResolver callMetadataResolver;
private final HostCallerIdResolver hostCallerIdResolver;
public DefaultGrpcServerCallAssistant(CallMetadataResolver callMetadataResolver,
HostCallerIdResolver hostCallerIdResolver) {
this.callMetadataResolver = callMetadataResolver;
this.hostCallerIdResolver = hostCallerIdResolver;
}
public <T> void callMono(StreamObserver<T> streamObserver, Function<GrpcServerCallContext, Mono<T>> monoResponse) {
Disposable disposable = monoResponse.apply(buildContext()).subscribe(
next -> {
try {
streamObserver.onNext(next);
} catch (Throwable error) {
ExceptionExt.silent(() -> streamObserver.onError(error));
}
},
error -> ExceptionExt.silent(() -> streamObserver.onError(error)),
() -> ExceptionExt.silent(streamObserver::onCompleted)
);
((ServerCallStreamObserver) streamObserver).setOnCancelHandler(disposable::dispose);
}
@Override
public void callMonoEmpty(StreamObserver<Empty> streamObserver, Function<GrpcServerCallContext, Mono<Void>> monoResponse) {
Disposable disposable = monoResponse.apply(buildContext()).subscribe(
next -> {
// Nothing
},
error -> ExceptionExt.silent(() -> streamObserver.onError(error)),
() -> {
try {
streamObserver.onNext(Empty.getDefaultInstance());
ExceptionExt.silent(streamObserver::onCompleted);
} catch (Exception error) {
ExceptionExt.silent(() -> streamObserver.onError(error));
}
}
);
((ServerCallStreamObserver) streamObserver).setOnCancelHandler(disposable::dispose);
}
@Override
public <T> void callFlux(StreamObserver<T> streamObserver, Function<GrpcServerCallContext, Flux<T>> fluxResponse) {
Disposable disposable = fluxResponse.apply(buildContext()).subscribe(
next -> {
try {
streamObserver.onNext(next);
} catch (Throwable error) {
ExceptionExt.silent(() -> streamObserver.onError(error));
}
},
error -> ExceptionExt.silent(() -> streamObserver.onError(error)),
() -> ExceptionExt.silent(streamObserver::onCompleted)
);
((ServerCallStreamObserver) streamObserver).setOnCancelHandler(disposable::dispose);
}
@Override
public <T> void callDirect(StreamObserver<T> streamObserver, Function<GrpcServerCallContext, T> responseFunction) {
try {
T result = responseFunction.apply(buildContext());
streamObserver.onNext(result);
ExceptionExt.silent(streamObserver::onCompleted);
} catch (Exception error) {
ExceptionExt.silent(() -> streamObserver.onError(error));
}
}
@Override
public <T> void inContext(StreamObserver<T> streamObserver,
BiConsumer<GrpcServerCallContext, T> onSuccess,
BiConsumer<GrpcServerCallContext, Throwable> onError,
BiConsumer<GrpcServerCallContext, StreamObserver<T>> consumer) {
GrpcServerCallContext context = buildContext();
consumer.accept(context, new StreamObserver<T>() {
@Override
public void onNext(T next) {
streamObserver.onNext(next);
onSuccess.accept(context, next);
}
@Override
public void onError(Throwable throwable) {
streamObserver.onError(throwable);
onError.accept(context, throwable);
}
@Override
public void onCompleted() {
streamObserver.onCompleted();
}
});
}
private GrpcServerCallContext buildContext() {
CallMetadata callMetadata = callMetadataResolver.resolve().orElse(null);
Map<String, String> context = V3HeaderInterceptor.CALLER_CONTEXT_CONTEXT_KEY.get();
String callerAddress = context == null ? null : context.get(CallMetadataHeaders.DIRECT_CALLER_CONTEXT_CALLER_ADDRESS);
String callerApplicationName;
if (callMetadata == null) {
callerApplicationName = callerAddress == null ? "unknown" : hostCallerIdResolver.resolve(callerAddress).orElse("unknown");
} else {
Caller directCaller = Iterables.getLast(callMetadata.getCallers());
callerApplicationName = directCaller.getCallerType() == CallerType.Application
? "app#" + directCaller.getId()
: "user#" + directCaller.getId();
}
return new GrpcServerCallContext(
callMetadataResolver.resolve().orElse(CallMetadataConstants.UNDEFINED_CALL_METADATA),
Evaluators.getOrDefault(callerAddress, "unknown"),
callerApplicationName
);
}
}
| 1,294 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/assistant/DefaultGrpcClientCallAssistant.java | package com.netflix.titus.runtime.endpoint.common.grpc.assistant;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import com.google.protobuf.Empty;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.endpoint.metadata.V3HeaderInterceptor;
import io.grpc.Deadline;
import io.grpc.stub.AbstractStub;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.StreamObserver;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class DefaultGrpcClientCallAssistant<STUB extends AbstractStub<STUB>> implements GrpcClientCallAssistant<STUB> {
private final GrpcCallAssistantConfiguration configuration;
private final STUB stub;
private final CallMetadataResolver callMetadataResolver;
public DefaultGrpcClientCallAssistant(GrpcCallAssistantConfiguration configuration,
STUB stub,
CallMetadataResolver callMetadataResolver) {
this.configuration = configuration;
this.stub = stub;
this.callMetadataResolver = callMetadataResolver;
}
@Override
public <T> Mono<T> asMono(BiConsumer<STUB, StreamObserver<T>> grpcInvoker) {
return Mono.create(sink -> {
STUB decoratedStub = decorateStub(configuration.getRequestTimeoutMs());
StreamObserver<T> grpcStreamObserver = new ClientResponseObserver<T, T>() {
@Override
public void beforeStart(ClientCallStreamObserver requestStream) {
sink.onCancel(() -> requestStream.cancel("React subscription cancelled", null));
}
@Override
public void onNext(T value) {
sink.success(value);
}
@Override
public void onError(Throwable error) {
sink.error(error);
}
@Override
public void onCompleted() {
sink.success();
}
};
grpcInvoker.accept(decoratedStub, grpcStreamObserver);
});
}
@Override
public Mono<Void> asMonoEmpty(BiConsumer<STUB, StreamObserver<Empty>> grpcInvoker) {
return Mono.create(sink -> {
STUB decoratedStub = decorateStub(configuration.getRequestTimeoutMs());
StreamObserver<Empty> grpcStreamObserver = new ClientResponseObserver<Empty, Empty>() {
@Override
public void beforeStart(ClientCallStreamObserver requestStream) {
sink.onCancel(() -> requestStream.cancel("React subscription cancelled", null));
}
@Override
public void onNext(Empty value) {
sink.success();
}
@Override
public void onError(Throwable error) {
sink.error(error);
}
@Override
public void onCompleted() {
sink.success();
}
};
grpcInvoker.accept(decoratedStub, grpcStreamObserver);
});
}
@Override
public <T> Flux<T> asFlux(BiConsumer<STUB, StreamObserver<T>> grpcInvoker) {
return Flux.create(sink -> {
STUB decoratedStub = decorateStub(configuration.getStreamTimeoutMs());
StreamObserver<T> grpcStreamObserver = new ClientResponseObserver<T, T>() {
@Override
public void beforeStart(ClientCallStreamObserver requestStream) {
sink.onCancel(() -> requestStream.cancel("React subscription cancelled", null));
}
@Override
public void onNext(T value) {
sink.next(value);
}
@Override
public void onError(Throwable error) {
sink.error(error);
}
@Override
public void onCompleted() {
sink.complete();
}
};
grpcInvoker.accept(decoratedStub, grpcStreamObserver);
});
}
@Override
public <T> Flux<T> callFlux(Function<STUB, Flux<T>> grpcExecutor) {
return Flux.defer(() -> {
STUB decoratedStub = decorateStub(configuration.getStreamTimeoutMs());
return grpcExecutor.apply(decoratedStub);
});
}
@Override
public void inContext(Consumer<STUB> grpcExecutor) {
STUB decoratedStub = decorateStub(configuration.getStreamTimeoutMs());
grpcExecutor.accept(decoratedStub);
}
private STUB decorateStub(long timeoutMs) {
STUB decoratedStub = callMetadataResolver.resolve().map(callMetadata ->
V3HeaderInterceptor.attachCallMetadata(stub, callMetadata)
).orElse(stub);
decoratedStub = decoratedStub.withDeadline(Deadline.after(timeoutMs, TimeUnit.MILLISECONDS));
return decoratedStub;
}
}
| 1,295 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/interceptor/CommonErrorCatchingServerInterceptor.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.interceptor;
import com.netflix.titus.common.util.Evaluators;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.runtime.endpoint.common.grpc.GrpcExceptionMapper;
import io.grpc.ForwardingServerCall;
import io.grpc.ForwardingServerCallListener;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.titus.common.util.Evaluators.getOrDefault;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcExceptionMapper.KEY_TITUS_DEBUG;
/**
* (adapted from netflix-grpc-extensions)
* <p>
* Interceptor that ensures any exception thrown by a method handler is propagated
* as a close() to all upstream {@link ServerInterceptor}s.
* Custom exceptions mapping can be provided through customMappingFunction.
*/
public final class CommonErrorCatchingServerInterceptor implements ServerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(CommonErrorCatchingServerInterceptor.class);
private final GrpcExceptionMapper exceptionMapper;
public CommonErrorCatchingServerInterceptor(GrpcExceptionMapper exceptionMapper) {
this.exceptionMapper = exceptionMapper;
}
private <ReqT, RespT> void handlingException(ServerCall<ReqT, RespT> call, Exception e, boolean debug) {
logger.info("Returning exception to the client: {}", e.getMessage(), e);
Pair<Status, Metadata> statusAndMeta = exceptionMapper.of(e, debug);
Status status = statusAndMeta.getLeft();
safeClose(() -> call.close(status, statusAndMeta.getRight()));
throw status.asRuntimeException();
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
boolean debug = "true".equalsIgnoreCase(getOrDefault(headers.get(KEY_TITUS_DEBUG), "false"));
ServerCall.Listener<ReqT> listener = null;
try {
listener = next.startCall(new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {
@Override
public void close(Status status, Metadata trailers) {
if (status.getCode() != Status.Code.OK) {
Pair<Status, Metadata> pair = exceptionMapper.of(status, trailers, debug);
Status newStatus = pair.getLeft();
if (isCriticalError(newStatus)) {
logger.warn("Returning exception to the client: {}", formatStatus(newStatus));
} else {
logger.debug("Returning exception to the client: {}", formatStatus(newStatus));
}
Evaluators.acceptNotNull(newStatus.getCause(), error -> logger.debug("Stack trace", error));
safeClose(() -> super.close(newStatus, pair.getRight()));
}
safeClose(() -> super.close(status, trailers));
}
}, headers);
} catch (Exception e) {
handlingException(call, e, debug);
}
return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(listener) {
// Clients sends one requests are handled through onHalfClose() (not onMessage)
@Override
public void onHalfClose() {
try {
super.onHalfClose();
} catch (Exception e) {
handlingException(call, e, debug);
}
}
// Streaming client requests are handled in onMessage()
@Override
public void onMessage(ReqT message) {
try {
super.onMessage(message);
} catch (Exception e) {
handlingException(call, e, debug);
}
}
};
}
private boolean isCriticalError(Status status) {
switch (status.getCode()) {
case OK:
case CANCELLED:
case INVALID_ARGUMENT:
case NOT_FOUND:
case ALREADY_EXISTS:
case PERMISSION_DENIED:
case FAILED_PRECONDITION:
case OUT_OF_RANGE:
case UNAUTHENTICATED:
return false;
case UNKNOWN:
case DEADLINE_EXCEEDED:
case RESOURCE_EXHAUSTED:
case ABORTED:
case UNIMPLEMENTED:
case INTERNAL:
case UNAVAILABLE:
case DATA_LOSS:
return true;
}
// In case we missed something
return true;
}
private String formatStatus(Status status) {
return "{code=" + status.getCode()
+ ", description=" + status.getDescription()
+ ", error=" + (status.getCause() == null ? "N/A" : status.getCause().getMessage())
+ '}';
}
private void safeClose(Runnable action) {
try {
action.run();
} catch (IllegalStateException ignore) {
// Ignore, as most likely connection is already closed
}
}
}
| 1,296 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/metadata/CallMetadataHeaders.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.metadata;
import io.grpc.CompressorRegistry;
public final class CallMetadataHeaders {
/**
* If set to true, additional debug information is returned for failing requests.
*/
public final static String DEBUG_HEADER = "X-Titus-Debug";
/**
* Set compression type. The default GRPC compressor is 'gzip', so it is safe to assume it is always supported.
* Other compressor types may require additional dependencies/configuration with the compressor registry
* {@link CompressorRegistry}.
*/
public final static String COMPRESSION_HEADER = "X-Titus-Compression";
/*
* Caller authentication/authorization headers.
*/
/**
* The original caller id. When a request is forwarded through multiple intermediaries, this header
* should include the identity of a user/application that originates the request.
*/
public final static String CALLER_ID_HEADER = "X-Titus-CallerId";
/**
* Type of a caller id set in {@link #CALLER_ID_HEADER}.
*/
public final static String CALLER_TYPE_HEADER = "X-Titus-CallerType";
/**
* The identity of an entity making direct call to Titus without any intermediaries in between.
* <h1>Limitations</h1>
* The current model allows to capture a single intermediary only.
*/
public final static String DIRECT_CALLER_ID_HEADER = "X-Titus-DirectCallerId";
/**
* Type of a caller id set in {@link #DIRECT_CALLER_ID_HEADER}.
*/
public final static String DIRECT_CALLER_TYPE_HEADER = "X-Titus-DirectCallerType";
/**
* A reason for making the call. The value if set is part of the transaction log/activity history.
*/
public final static String CALL_REASON_HEADER = "X-Titus-CallReason";
/**
* For internal usage only (TitusFederation -> TitusGateway -> TitusMaster).
*/
public static String CALL_METADATA_HEADER = "X-Titus-CallMetadata-bin";
/*
* Direct caller context data.
*/
/**
* Direct caller server group stack name.
*/
public static final String DIRECT_CALLER_CONTEXT_STACK = "titus.serverGroup.stack";
/**
* Direct caller server group detail.
*/
public static final String DIRECT_CALLER_CONTEXT_DETAIL = "titus.serverGroup.detail";
/**
* Direct caller instance id.
*/
public static final String DIRECT_CALLER_CONTEXT_INSTANCE_ID = "titus.caller.instanceId";
/**
* Name of the service that is invoked.
*/
public static final String DIRECT_CALLER_CONTEXT_SERVICE_NAME = "titus.service.name";
/**
* Name of the method that is invoked.
*/
public static final String DIRECT_CALLER_CONTEXT_SERVICE_METHOD = "titus.service.method";
/**
* Transport type (HTTP/GRPC).
*/
public static final String DIRECT_CALLER_CONTEXT_TRANSPORT_TYPE = "titus.transport.type";
/**
* True for TLS, false for plain text.
*/
public static final String DIRECT_CALLER_CONTEXT_TRANSPORT_SECURE = "titus.transport.secure";
/**
* Caller address.
*/
public static final String DIRECT_CALLER_CONTEXT_CALLER_ADDRESS = "titus.transport.remoteAddress";
/**
* Local server IP address.
*/
public static final String DIRECT_CALLER_CONTEXT_LOCAL_ADDRESS = "titus.transport.localAddress";
/**
* Local server port number.
*/
public static final String DIRECT_CALLER_CONTEXT_LOCAL_PORT = "titus.transport.localPort";
private CallMetadataHeaders() {
}
}
| 1,297 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/metadata/AnonymousCallMetadataResolver.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.metadata;
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 java.util.Collections;
import java.util.Optional;
import javax.inject.Singleton;
@Singleton
public class AnonymousCallMetadataResolver implements CallMetadataResolver {
private static final AnonymousCallMetadataResolver INSTANCE = new AnonymousCallMetadataResolver();
private static final String ANONYMOUS_ID = "anonymous";
private static final CallMetadata ANONYMOUS = CallMetadata.newBuilder()
.withCallerId(ANONYMOUS_ID)
.withCallPath(Collections.singletonList(ANONYMOUS_ID))
.withCallReason("")
.withCallers(Collections.singletonList(Caller.newBuilder()
.withId(ANONYMOUS_ID)
.withCallerType(CallerType.Unknown)
.build()
))
.build();
private static final Optional<CallMetadata> ANONYMOUS_OPTIONAL = Optional.of(ANONYMOUS);
@Override
public Optional<CallMetadata> resolve() {
return ANONYMOUS_OPTIONAL;
}
public static AnonymousCallMetadataResolver getInstance() {
return INSTANCE;
}
}
| 1,298 |
0 | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-common-server/src/main/java/com/netflix/titus/runtime/endpoint/metadata/V3HeaderInterceptor.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.metadata;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.runtime.endpoint.common.grpc.CommonRuntimeGrpcModelConverters;
import io.grpc.Context;
import io.grpc.Contexts;
import io.grpc.Grpc;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.stub.AbstractStub;
import io.grpc.stub.MetadataUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.titus.common.util.CollectionsExt.asSet;
/**
*
*/
public class V3HeaderInterceptor implements ServerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(V3HeaderInterceptor.class);
private static final String UNKNOWN_IP = "unknown";
private static final String X_TITUS_GRPC_CALLER_CONTEXT = "X-Titus-GrpcCallerContext";
private static final Set<String> ALLOWED_COMPRESSION_TYPES = asSet("gzip");
public static Metadata.Key<String> DEBUG_KEY = Metadata.Key.of(CallMetadataHeaders.DEBUG_HEADER, Metadata.ASCII_STRING_MARSHALLER);
public static Metadata.Key<String> COMPRESSION_KEY = Metadata.Key.of(CallMetadataHeaders.COMPRESSION_HEADER, Metadata.ASCII_STRING_MARSHALLER);
public static Metadata.Key<String> CALLER_ID_KEY = Metadata.Key.of(CallMetadataHeaders.CALLER_ID_HEADER, Metadata.ASCII_STRING_MARSHALLER);
public static Metadata.Key<String> CALLER_TYPE_KEY = Metadata.Key.of(CallMetadataHeaders.CALLER_TYPE_HEADER, Metadata.ASCII_STRING_MARSHALLER);
public static Metadata.Key<String> DIRECT_CALLER_ID_KEY = Metadata.Key.of(CallMetadataHeaders.DIRECT_CALLER_ID_HEADER, Metadata.ASCII_STRING_MARSHALLER);
public static Metadata.Key<String> CALL_REASON_KEY = Metadata.Key.of(CallMetadataHeaders.CALL_REASON_HEADER, Metadata.ASCII_STRING_MARSHALLER);
public static Metadata.Key<byte[]> CALL_METADATA_KEY = Metadata.Key.of(CallMetadataHeaders.CALL_METADATA_HEADER, Metadata.BINARY_BYTE_MARSHALLER);
public static Context.Key<String> DEBUG_CONTEXT_KEY = Context.key(CallMetadataHeaders.DEBUG_HEADER);
public static Context.Key<String> COMPRESSION_CONTEXT_KEY = Context.key(CallMetadataHeaders.COMPRESSION_HEADER);
public static Context.Key<String> CALLER_ID_CONTEXT_KEY = Context.key(CallMetadataHeaders.CALLER_ID_HEADER);
public static Context.Key<String> CALLER_TYPE_CONTEXT_KEY = Context.key(CallMetadataHeaders.CALLER_TYPE_HEADER);
public static Context.Key<String> DIRECT_CALLER_ID_CONTEXT_KEY = Context.key(CallMetadataHeaders.DIRECT_CALLER_ID_HEADER);
public static Context.Key<String> DIRECT_CALLER_TYPE_CONTEXT_KEY = Context.key(CallMetadataHeaders.DIRECT_CALLER_TYPE_HEADER);
public static Context.Key<String> CALL_REASON_CONTEXT_KEY = Context.key(CallMetadataHeaders.CALL_REASON_HEADER);
public static Context.Key<Map<String, String>> CALLER_CONTEXT_CONTEXT_KEY = Context.key(X_TITUS_GRPC_CALLER_CONTEXT);
public static Context.Key<CallMetadata> CALL_METADATA_CONTEXT_KEY = Context.key(CallMetadataHeaders.CALL_METADATA_HEADER);
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
Context wrappedContext = Context.current();
Object debugValue = headers.get(DEBUG_KEY);
if (debugValue != null) {
boolean debugEnabled = Boolean.parseBoolean(debugValue.toString());
if (debugEnabled) {
wrappedContext = wrappedContext.withValue(DEBUG_CONTEXT_KEY, "true");
}
}
Object compressionValue = headers.get(COMPRESSION_KEY);
if (compressionValue != null) {
String compressionType = compressionValue.toString();
if (ALLOWED_COMPRESSION_TYPES.contains(compressionType)) {
call.setCompression(compressionType);
wrappedContext = wrappedContext.withValue(COMPRESSION_CONTEXT_KEY, compressionType);
}
}
wrappedContext = copyIntoContext(wrappedContext, headers, CALLER_ID_KEY, CALLER_ID_CONTEXT_KEY);
wrappedContext = copyIntoContext(wrappedContext, headers, CALLER_TYPE_KEY, CALLER_TYPE_CONTEXT_KEY);
wrappedContext = copyIntoContext(wrappedContext, headers, DIRECT_CALLER_ID_KEY, DIRECT_CALLER_ID_CONTEXT_KEY);
wrappedContext = copyIntoContext(wrappedContext, headers, CALL_REASON_KEY, CALL_REASON_CONTEXT_KEY);
wrappedContext = copyDirectCallerContextIntoContext(wrappedContext, call);
Object callMetadataValue = headers.get(CALL_METADATA_KEY);
if (callMetadataValue != null) {
try {
com.netflix.titus.grpc.protogen.CallMetadata grpcCallMetadata = com.netflix.titus.grpc.protogen.CallMetadata.parseFrom((byte[]) callMetadataValue);
wrappedContext = wrappedContext.withValue(CALL_METADATA_CONTEXT_KEY, CommonRuntimeGrpcModelConverters.toCallMetadata(grpcCallMetadata));
} catch (Exception e) {
// Ignore bad header value.
logger.info("Invalid CallMetadata in a request header", e);
}
}
return wrappedContext == Context.current()
? next.startCall(call, headers)
: Contexts.interceptCall(wrappedContext, call, headers, next);
}
public static <STUB extends AbstractStub<STUB>> STUB attachCallMetadata(STUB serviceStub, CallMetadata callMetadata) {
Metadata metadata = new Metadata();
metadata.put(CALL_METADATA_KEY, CommonRuntimeGrpcModelConverters.toGrpcCallMetadata(callMetadata).toByteArray());
return serviceStub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata));
}
private static Context copyIntoContext(Context context, Metadata headers, Metadata.Key<String> headerKey, Context.Key<String> contextKey) {
Object value = headers.get(headerKey);
return value == null ? context : context.withValue(contextKey, value.toString());
}
private <ReqT, RespT> Context copyDirectCallerContextIntoContext(Context context, ServerCall<ReqT, RespT> call) {
Map<String, String> callerContext = new HashMap<>();
String fullName = call.getMethodDescriptor().getFullMethodName();
int methodBegin = fullName.indexOf('/');
String serviceName;
String methodName;
if (methodBegin <= 0) {
serviceName = fullName;
methodName = fullName;
} else {
serviceName = fullName.substring(0, methodBegin);
methodName = Character.toLowerCase(fullName.charAt(methodBegin + 1)) + fullName.substring(methodBegin + 2);
}
callerContext.put(CallMetadataHeaders.DIRECT_CALLER_CONTEXT_SERVICE_NAME, serviceName);
callerContext.put(CallMetadataHeaders.DIRECT_CALLER_CONTEXT_SERVICE_METHOD, methodName);
callerContext.put(CallMetadataHeaders.DIRECT_CALLER_CONTEXT_TRANSPORT_TYPE, "GRPC");
callerContext.put(CallMetadataHeaders.DIRECT_CALLER_CONTEXT_TRANSPORT_SECURE, "?");
String callerAddress = processAddress(call.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)).getLeft();
callerContext.put(CallMetadataHeaders.DIRECT_CALLER_CONTEXT_CALLER_ADDRESS, callerAddress);
Pair<String, Integer> localIpAndPort = processAddress(call.getAttributes().get(Grpc.TRANSPORT_ATTR_LOCAL_ADDR));
callerContext.put(CallMetadataHeaders.DIRECT_CALLER_CONTEXT_LOCAL_ADDRESS, localIpAndPort.getLeft());
callerContext.put(CallMetadataHeaders.DIRECT_CALLER_CONTEXT_LOCAL_PORT, "" + localIpAndPort.getRight());
return context.withValue(CALLER_CONTEXT_CONTEXT_KEY, callerContext);
}
private Pair<String, Integer> processAddress(@Nullable final SocketAddress socketAddress) {
if (socketAddress == null) {
return Pair.of(UNKNOWN_IP, 0);
}
if (!(socketAddress instanceof InetSocketAddress)) {
return Pair.of(socketAddress.toString(), 0);
}
final InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
final String hostString = inetSocketAddress.getHostString();
return Pair.of(hostString == null ? UNKNOWN_IP : hostString, inetSocketAddress.getPort());
}
}
| 1,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.