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-common/src/main/java/com/netflix/titus/common/framework/scheduler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/model/ScheduledAction.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.scheduler.model; import java.util.Collections; import java.util.List; import java.util.Objects; import com.google.common.base.Preconditions; public class ScheduledAction { private final String id; private final SchedulingStatus status; private final List<SchedulingStatus> statusHistory; private final ExecutionId executionId; private ScheduledAction(String id, SchedulingStatus status, List<SchedulingStatus> statusHistory, ExecutionId executionId) { this.id = id; this.status = status; this.statusHistory = statusHistory; this.executionId = executionId; } public String getId() { return id; } public SchedulingStatus getStatus() { return status; } public ExecutionId getExecutionId() { return executionId; } public List<SchedulingStatus> getStatusHistory() { return statusHistory; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ScheduledAction that = (ScheduledAction) o; return Objects.equals(id, that.id) && Objects.equals(status, that.status) && Objects.equals(statusHistory, that.statusHistory) && Objects.equals(executionId, that.executionId); } @Override public int hashCode() { return Objects.hash(id, status, statusHistory, executionId); } public Builder toBuilder() { return newBuilder().withId(id).withStatus(status).withStatusHistory(statusHistory).withIteration(executionId); } @Override public String toString() { return "ScheduledAction{" + "id='" + id + '\'' + ", status=" + status + ", statusHistory=" + statusHistory + ", iteration=" + executionId + '}'; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private String id; private SchedulingStatus status; private List<SchedulingStatus> statusHistory = Collections.emptyList(); private ExecutionId executionId; private Builder() { } public Builder withId(String id) { this.id = id; return this; } public Builder withStatus(SchedulingStatus status) { this.status = status; return this; } public Builder withStatusHistory(List<SchedulingStatus> statusHistory) { this.statusHistory = statusHistory; return this; } public Builder withIteration(ExecutionId executionId) { this.executionId = executionId; return this; } public ScheduledAction build() { Preconditions.checkNotNull(id, "Id cannot be null"); Preconditions.checkNotNull(status, "Status cannot be null"); Preconditions.checkNotNull(statusHistory, "Status history cannot be null"); Preconditions.checkNotNull(executionId, "Iteration cannot be null"); return new ScheduledAction(id, status, statusHistory, executionId); } } }
900
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/model/ExecutionId.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.scheduler.model; import java.util.Objects; public class ExecutionId { private static final ExecutionId INITIAL = new ExecutionId(1, 1, 1); private final int id; private final int attempt; private final int total; public ExecutionId(int id, int attempt, int total) { this.id = id; this.attempt = attempt; this.total = total; } public int getId() { return id; } public int getAttempt() { return attempt; } public int getTotal() { return total; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ExecutionId that = (ExecutionId) o; return id == that.id && attempt == that.attempt && total == that.total; } @Override public int hashCode() { return Objects.hash(id, attempt, total); } @Override public String toString() { return "Iteration{" + "id=" + id + ", attempt=" + attempt + ", total=" + total + '}'; } public static ExecutionId initial() { return INITIAL; } public static ExecutionId nextIteration(ExecutionId executionId) { return new ExecutionId(executionId.getId() + 1, executionId.getAttempt(), executionId.getTotal() + 1); } public static ExecutionId nextAttempt(ExecutionId executionId) { return new ExecutionId(executionId.getId(), executionId.getAttempt() + 1, executionId.getTotal() + 1); } }
901
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/model/event/LocalSchedulerEvent.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.scheduler.model.event; import java.util.Objects; import com.netflix.titus.common.framework.scheduler.model.Schedule; public abstract class LocalSchedulerEvent { private final Schedule schedule; LocalSchedulerEvent(Schedule schedule) { this.schedule = schedule; } public Schedule getSchedule() { return schedule; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocalSchedulerEvent that = (LocalSchedulerEvent) o; return Objects.equals(schedule, that.schedule); } @Override public int hashCode() { return Objects.hash(schedule); } @Override public String toString() { return getClass().getSimpleName() + "{" + "schedule=" + schedule + '}'; } }
902
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/model/event/ScheduleAddedEvent.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.scheduler.model.event; import com.netflix.titus.common.framework.scheduler.model.Schedule; public class ScheduleAddedEvent extends LocalSchedulerEvent { public ScheduleAddedEvent(Schedule schedule) { super(schedule); } }
903
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/model/event/ScheduleUpdateEvent.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.scheduler.model.event; import com.netflix.titus.common.framework.scheduler.model.Schedule; public class ScheduleUpdateEvent extends LocalSchedulerEvent { public ScheduleUpdateEvent(Schedule schedule) { super(schedule); } }
904
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/model/event/ScheduleRemovedEvent.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.scheduler.model.event; import com.netflix.titus.common.framework.scheduler.model.Schedule; public class ScheduleRemovedEvent extends LocalSchedulerEvent { public ScheduleRemovedEvent(Schedule schedule) { super(schedule); } }
905
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/OneOffReconciler.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import com.google.common.base.Preconditions; import com.netflix.titus.common.framework.simplereconciler.internal.DefaultOneOffReconciler; import com.netflix.titus.common.framework.simplereconciler.internal.provider.ActionProviderSelectorFactory; import com.netflix.titus.common.runtime.TitusRuntime; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import static com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProviderPolicy.DEFAULT_EXTERNAL_POLICY_NAME; import static com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProviderPolicy.getDefaultExternalPolicy; /** * A simple reconciliation engine, which serializes client and internal/reconciler actions that work over the same * data item. */ public interface OneOffReconciler<DATA> { Mono<Void> close(); DATA getCurrent(); Mono<DATA> apply(Function<DATA, Mono<DATA>> action); Flux<DATA> changes(); static <DATA> Builder<DATA> newBuilder(String id) { return new Builder<>(id); } class Builder<DATA> { private final String id; private DATA initial; private Duration quickCycle; private Duration longCycle; private ReconcilerActionProvider<DATA> externalActionProvider; private Map<String, ReconcilerActionProvider<DATA>> internalActionProviders = new HashMap<>(); private Scheduler scheduler; private TitusRuntime titusRuntime; private Builder(String id) { this.id = id; } public Builder<DATA> withInitial(DATA initial) { this.initial = initial; return this; } /** * Monitoring interval for running actions. */ public Builder<DATA> withQuickCycle(Duration quickCycle) { this.quickCycle = quickCycle; return this; } /** * Monitoring interval at which reconciliation function is run. The interval value should be a multiplication of * {@link #withQuickCycle(Duration)} value. */ public Builder<DATA> withLongCycle(Duration longCycle) { this.longCycle = longCycle; return this; } public Builder<DATA> withExternalActionProviderPolicy(ReconcilerActionProviderPolicy policy) { // The action provider resolves in this case to an empty list as we handle the external change actions in a different way. Preconditions.checkArgument(!internalActionProviders.containsKey(policy.getName()), "External and internal policy names are equal: name=%s", policy.getName()); this.externalActionProvider = new ReconcilerActionProvider<>(policy, true, data -> Collections.emptyList()); return this; } public Builder<DATA> withReconcilerActionsProvider(Function<DATA, List<Mono<Function<DATA, DATA>>>> reconcilerActionsProvider) { withReconcilerActionsProvider(ReconcilerActionProviderPolicy.getDefaultInternalPolicy(), reconcilerActionsProvider); return this; } public Builder<DATA> withReconcilerActionsProvider(ReconcilerActionProviderPolicy policy, Function<DATA, List<Mono<Function<DATA, DATA>>>> reconcilerActionsProvider) { Preconditions.checkArgument(!policy.getName().equals(DEFAULT_EXTERNAL_POLICY_NAME), "Attempted to use the default external policy name for an internal one: name=%s", DEFAULT_EXTERNAL_POLICY_NAME); Preconditions.checkArgument(externalActionProvider == null || !externalActionProvider.getPolicy().getName().equals(policy.getName()), "External and internal policy names must be different: name=%s", policy.getName()); internalActionProviders.put(policy.getName(), new ReconcilerActionProvider<>(policy, false, reconcilerActionsProvider)); return this; } public Builder<DATA> withScheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } public Builder<DATA> withTitusRuntime(TitusRuntime titusRuntime) { this.titusRuntime = titusRuntime; return this; } public OneOffReconciler<DATA> build() { Preconditions.checkNotNull(id, "id is null"); Preconditions.checkNotNull(titusRuntime, "TitusRuntime is null"); List<ReconcilerActionProvider<DATA>> actionProviders = new ArrayList<>(); if (externalActionProvider == null) { actionProviders.add(new ReconcilerActionProvider<>(getDefaultExternalPolicy(), true, data -> Collections.emptyList())); } else { actionProviders.add(externalActionProvider); } actionProviders.addAll(internalActionProviders.values()); ActionProviderSelectorFactory<DATA> providerSelector = new ActionProviderSelectorFactory<>(id, actionProviders, titusRuntime); return new DefaultOneOffReconciler<>( id, initial, quickCycle, longCycle, providerSelector, scheduler, titusRuntime ); } } }
906
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/ManyReconciler.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler; import java.io.Closeable; import java.time.Duration; 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.UUID; import java.util.function.Function; import com.google.common.base.Preconditions; import com.netflix.titus.common.framework.simplereconciler.internal.DefaultManyReconciler; import com.netflix.titus.common.framework.simplereconciler.internal.ReconcilerExecutorMetrics; import com.netflix.titus.common.framework.simplereconciler.internal.ShardedManyReconciler; import com.netflix.titus.common.framework.simplereconciler.internal.provider.ActionProviderSelectorFactory; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.closeable.CloseableReference; import com.netflix.titus.common.util.collections.index.IndexSet; import com.netflix.titus.common.util.collections.index.IndexSetHolder; import com.netflix.titus.common.util.collections.index.IndexSetHolderBasic; import com.netflix.titus.common.util.collections.index.IndexSetHolderConcurrent; import com.netflix.titus.common.util.collections.index.Indexes; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import static com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProviderPolicy.DEFAULT_EXTERNAL_POLICY_NAME; import static com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProviderPolicy.getDefaultExternalPolicy; /** * A simple reconciliation framework that manages multiple data items. Each individual data item is processed * independently, with no concurrency constraints. */ public interface ManyReconciler<DATA> { Mono<Void> add(String id, DATA initial); Mono<Void> remove(String id); Mono<Void> close(); Map<String, DATA> getAll(); IndexSet<String, DATA> getIndexSet(); Optional<DATA> findById(String id); int size(); Mono<DATA> apply(String id, Function<DATA, Mono<DATA>> action); Flux<List<SimpleReconcilerEvent<DATA>>> changes(String clientId); default Flux<List<SimpleReconcilerEvent<DATA>>> changes() { return changes(UUID.randomUUID().toString()); } static <DATA> Builder<DATA> newBuilder() { return new Builder<>(); } class Builder<DATA> { private String name = "default"; private Duration quickCycle; private Duration longCycle; private ReconcilerActionProvider<DATA> externalActionProvider; private final Map<String, ReconcilerActionProvider<DATA>> internalActionProviders = new HashMap<>(); private Scheduler reconcilerScheduler; private Scheduler notificationScheduler; private TitusRuntime titusRuntime; private int shardCount; private IndexSet<String, DATA> indexes; private Builder() { } /** * Reconciler unique name (for reporting purposes). */ public Builder<DATA> withName(String name) { this.name = name; return this; } public Builder<DATA> withShardCount(int shardCount) { this.shardCount = shardCount; return this; } /** * Monitoring interval for running actions. */ public Builder<DATA> withQuickCycle(Duration quickCycle) { this.quickCycle = quickCycle; return this; } /** * Monitoring interval at which reconciliation function is run. The interval value should be a multiplication of * {@link #withQuickCycle(Duration)} value. */ public Builder<DATA> withLongCycle(Duration longCycle) { this.longCycle = longCycle; return this; } public Builder<DATA> withExternalActionProviderPolicy(ReconcilerActionProviderPolicy policy) { // The action provider resolves in this case to an empty list as we handle the external change actions in a different way. Preconditions.checkArgument(!internalActionProviders.containsKey(policy.getName()), "External and internal policy names are equal: name=%s", policy.getName()); this.externalActionProvider = new ReconcilerActionProvider<>(policy, true, data -> Collections.emptyList()); return this; } public Builder<DATA> withReconcilerActionsProvider(Function<DATA, List<Mono<Function<DATA, DATA>>>> reconcilerActionsProvider) { withReconcilerActionsProvider(ReconcilerActionProviderPolicy.getDefaultInternalPolicy(), reconcilerActionsProvider); return this; } public Builder<DATA> withReconcilerActionsProvider(ReconcilerActionProviderPolicy policy, Function<DATA, List<Mono<Function<DATA, DATA>>>> reconcilerActionsProvider) { Preconditions.checkArgument(!policy.getName().equals(DEFAULT_EXTERNAL_POLICY_NAME), "Attempted to use the default external policy name for an internal one: name=%s", DEFAULT_EXTERNAL_POLICY_NAME); Preconditions.checkArgument(externalActionProvider == null || !externalActionProvider.getPolicy().getName().equals(policy.getName()), "External and internal policy names must be different: name=%s", policy.getName()); internalActionProviders.put(policy.getName(), new ReconcilerActionProvider<>(policy, false, reconcilerActionsProvider)); return this; } public Builder<DATA> withReconcilerScheduler(Scheduler reconcilerScheduler) { this.reconcilerScheduler = reconcilerScheduler; return this; } public Builder<DATA> withNotificationScheduler(Scheduler notificationScheduler) { this.notificationScheduler = notificationScheduler; return this; } public Builder<DATA> withIndexes(IndexSet<String, DATA> indexes) { this.indexes = indexes; return this; } public Builder<DATA> withTitusRuntime(TitusRuntime titusRuntime) { this.titusRuntime = titusRuntime; return this; } public ManyReconciler<DATA> build() { Preconditions.checkNotNull(name, "Name is null"); Preconditions.checkNotNull(titusRuntime, "TitusRuntime is null"); // Indexes are optional. If not set, provide the default value. if (indexes == null) { indexes = Indexes.empty(); } return shardCount <= 1 ? buildDefaultManyReconciler() : buildShardedManyReconciler(); } private ManyReconciler<DATA> buildDefaultManyReconciler() { CloseableReference<Scheduler> reconcilerSchedulerRef = reconcilerScheduler == null ? CloseableReference.referenceOf(Schedulers.newSingle("reconciler-internal-" + name, true), Scheduler::dispose) : CloseableReference.referenceOf(reconcilerScheduler); CloseableReference<Scheduler> notificationSchedulerRef = notificationScheduler == null ? CloseableReference.referenceOf(Schedulers.newSingle("reconciler-notification-" + name, true), Scheduler::dispose) : CloseableReference.referenceOf(notificationScheduler); IndexSetHolderBasic<String, DATA> indexSetHolder = new IndexSetHolderBasic<>(indexes); return new DefaultManyReconciler<>( name, quickCycle, longCycle, buildActionProviderSelectorFactory(), reconcilerSchedulerRef, notificationSchedulerRef, indexSetHolder, buildIndexSetHolderMonitor(indexSetHolder), titusRuntime ); } private ManyReconciler<DATA> buildShardedManyReconciler() { Function<Integer, CloseableReference<Scheduler>> reconcilerSchedulerSupplier = shardIndex -> CloseableReference.referenceOf( Schedulers.newSingle("reconciler-internal-" + name + "-" + shardIndex, true), Scheduler::dispose ); CloseableReference<Scheduler> notificationSchedulerRef = notificationScheduler == null ? CloseableReference.referenceOf(Schedulers.newSingle("reconciler-notification-" + name, true), Scheduler::dispose) : CloseableReference.referenceOf(notificationScheduler); Function<String, Integer> shardIndexSupplier = id -> Math.abs(id.hashCode()) % shardCount; IndexSetHolderConcurrent<String, DATA> indexSetHolder = new IndexSetHolderConcurrent<>(indexes); return ShardedManyReconciler.newSharedDefaultManyReconciler( name, shardCount, shardIndexSupplier, quickCycle, longCycle, buildActionProviderSelectorFactory(), reconcilerSchedulerSupplier, notificationSchedulerRef, indexSetHolder, buildIndexSetHolderMonitor(indexSetHolder), titusRuntime ); } private Closeable buildIndexSetHolderMonitor(IndexSetHolder<String, DATA> indexSetHolder) { return Indexes.monitor( titusRuntime.getRegistry().createId(ReconcilerExecutorMetrics.ROOT_NAME + "indexes"), indexSetHolder, titusRuntime.getRegistry() ); } private ActionProviderSelectorFactory<DATA> buildActionProviderSelectorFactory() { List<ReconcilerActionProvider<DATA>> actionProviders = new ArrayList<>(); if (externalActionProvider == null) { actionProviders.add(new ReconcilerActionProvider<>(getDefaultExternalPolicy(), true, data -> Collections.emptyList())); } else { actionProviders.add(externalActionProvider); } actionProviders.addAll(internalActionProviders.values()); ActionProviderSelectorFactory<DATA> providerSelector = new ActionProviderSelectorFactory<>(name, actionProviders, titusRuntime); return providerSelector; } } }
907
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/ReconcilerActionProviderPolicy.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.common.framework.simplereconciler; import java.time.Duration; import java.util.Objects; import com.google.common.base.Preconditions; /** * {@link ReconcilerActionProviderPolicy} provides evaluation rules and ordering. Reconciler actions come from two * main sources: external (user actions), and internal. Only actions coming from one source can be processed at a time. */ public class ReconcilerActionProviderPolicy { public static String DEFAULT_EXTERNAL_POLICY_NAME = "external"; public static String DEFAULT_INTERNAL_POLICY_NAME = "internal"; /** * A priority set for providers that configure minimumExecutionInterval, when the last evaluation time exceeds * this time. */ public static final int EXCEEDED_MIN_EXECUTION_INTERVAL_PRIORITY = 10; /** * Priority assigned to the external change actions. Internal action providers with a lower priority value will be always * executed before this one. */ public static final int DEFAULT_EXTERNAL_ACTIONS_PRIORITY = 100; public static final int DEFAULT_INTERNAL_ACTIONS_PRIORITY = 200; /** * Default policy assigned to the external change action provider. */ private static final ReconcilerActionProviderPolicy DEFAULT_EXTERNAL_ACTION_PROVIDER_POLICY = newBuilder() .withName(DEFAULT_EXTERNAL_POLICY_NAME) .withPriority(DEFAULT_EXTERNAL_ACTIONS_PRIORITY) .withExecutionInterval(Duration.ZERO) .build(); /** * Default policy assigned to the external change action provider. */ private static final ReconcilerActionProviderPolicy DEFAULT_INTERNAL_ACTION_PROVIDER_POLICY = newBuilder() .withName(DEFAULT_INTERNAL_POLICY_NAME) .withPriority(DEFAULT_INTERNAL_ACTIONS_PRIORITY) .withExecutionInterval(Duration.ZERO) .build(); private final String name; /** * Execution priority. The lower the value, the higher the priority. */ private final int priority; /** * Evaluation frequency. It is guaranteed the time between a subsequent provider evaluations is at least the * configured interval value. But the actual time might be longer if a processing takes a lot of time or there * are other action providers with a higher priority. The time interval is measured between the last action * completion time and the next action start time. */ private final Duration executionInterval; /** * Minimum execution frequency. If this limit is crossed, the provider priority is boosted to the top level. * If there are many action providers at the top level, they are executed in the round robin fashion. * If set to zero, the constraint is ignored. */ private final Duration minimumExecutionInterval; public ReconcilerActionProviderPolicy(String name, int priority, Duration executionInterval, Duration minimumExecutionInterval) { this.name = name; this.priority = priority; this.executionInterval = executionInterval; this.minimumExecutionInterval = minimumExecutionInterval; } public String getName() { return name; } public int getPriority() { return priority; } public Duration getExecutionInterval() { return executionInterval; } public static ReconcilerActionProviderPolicy getDefaultExternalPolicy() { return DEFAULT_EXTERNAL_ACTION_PROVIDER_POLICY; } public static ReconcilerActionProviderPolicy getDefaultInternalPolicy() { return DEFAULT_INTERNAL_ACTION_PROVIDER_POLICY; } public Duration getMinimumExecutionInterval() { return minimumExecutionInterval; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ReconcilerActionProviderPolicy that = (ReconcilerActionProviderPolicy) o; return priority == that.priority && Objects.equals(name, that.name) && Objects.equals(executionInterval, that.executionInterval) && Objects.equals(minimumExecutionInterval, that.minimumExecutionInterval); } @Override public int hashCode() { return Objects.hash(name, priority, executionInterval, minimumExecutionInterval); } @Override public String toString() { return "ReconcilerActionProviderPolicy{" + "name='" + name + '\'' + ", priority=" + priority + ", executionInterval=" + executionInterval + ", minimumExecutionInterval=" + minimumExecutionInterval + '}'; } public static Builder newBuilder() { return new Builder(); } public Builder toBuilder() { return newBuilder().withName(name) .withPriority(priority) .withExecutionInterval(executionInterval) .withMinimumExecutionInterval(minimumExecutionInterval); } public static final class Builder { private String name; private int priority; private Duration executionInterval; private Duration minimumExecutionInterval; private Builder() { } public Builder withName(String name) { this.name = name; return this; } public Builder withPriority(int priority) { this.priority = priority; return this; } public Builder withExecutionInterval(Duration executionInterval) { this.executionInterval = executionInterval; return this; } public Builder withMinimumExecutionInterval(Duration minimumExecutionInterval) { this.minimumExecutionInterval = minimumExecutionInterval; return this; } public ReconcilerActionProviderPolicy build() { Preconditions.checkNotNull(name, "policy name not set"); if (executionInterval == null) { executionInterval = Duration.ZERO; } if (minimumExecutionInterval == null) { minimumExecutionInterval = Duration.ZERO; } return new ReconcilerActionProviderPolicy(name, priority, executionInterval, minimumExecutionInterval); } } }
908
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/SimpleReconcilerEvent.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler; import java.util.Objects; public class SimpleReconcilerEvent<DATA> { public enum Kind { Added, Updated, Removed } private final Kind kind; private final String id; private final DATA data; /** * A unique identifier associated with each reconciler action and data element version. Consecutive transaction ids * are strictly increasing numbers, but they do not have to be continuous. Each managed data has its own transaction * id sequence. A client may use the transaction id, to chose the latest data version. */ private final long transactionId; public SimpleReconcilerEvent(Kind kind, String id, DATA data, long transactionId) { this.kind = kind; this.id = id; this.data = data; this.transactionId = transactionId; } public Kind getKind() { return kind; } public String getId() { return id; } public DATA getData() { return data; } public long getTransactionId() { return transactionId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SimpleReconcilerEvent<?> that = (SimpleReconcilerEvent<?>) o; return transactionId == that.transactionId && kind == that.kind && Objects.equals(id, that.id) && Objects.equals(data, that.data); } @Override public int hashCode() { return Objects.hash(kind, id, data, transactionId); } @Override public String toString() { return "SimpleReconcilerEvent{" + "kind=" + kind + ", id='" + id + '\'' + ", data=" + data + ", transactionId='" + transactionId + '\'' + '}'; } }
909
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/ReconcilerActionProvider.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.common.framework.simplereconciler; import java.util.List; import java.util.function.Function; import reactor.core.publisher.Mono; public class ReconcilerActionProvider<DATA> { private final ReconcilerActionProviderPolicy policy; private final boolean external; private final Function<DATA, List<Mono<Function<DATA, DATA>>>> actionProvider; public ReconcilerActionProvider(ReconcilerActionProviderPolicy policy, boolean external, Function<DATA, List<Mono<Function<DATA, DATA>>>> actionProvider) { this.policy = policy; this.external = external; this.actionProvider = actionProvider; } public boolean isExternal() { return external; } public ReconcilerActionProviderPolicy getPolicy() { return policy; } public Function<DATA, List<Mono<Function<DATA, DATA>>>> getActionProvider() { return actionProvider; } public Builder<DATA> toBuilder() { return ReconcilerActionProvider.<DATA>newBuilder().withPolicy(policy).withExternal(external).withActionProvider(actionProvider); } public static <DATA> Builder<DATA> newBuilder() { return new Builder<>(); } public static final class Builder<DATA> { private ReconcilerActionProviderPolicy policy; private boolean external; private Function<DATA, List<Mono<Function<DATA, DATA>>>> actionProvider; private Builder() { } public Builder<DATA> withPolicy(ReconcilerActionProviderPolicy policy) { this.policy = policy; return this; } public Builder<DATA> withExternal(boolean external) { this.external = external; return this; } public Builder<DATA> withActionProvider(Function<DATA, List<Mono<Function<DATA, DATA>>>> actionProvider) { this.actionProvider = actionProvider; return this; } public ReconcilerActionProvider<DATA> build() { return new ReconcilerActionProvider<>(policy, external, actionProvider); } } }
910
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/ReconcilerEngine.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProvider; import com.netflix.titus.common.framework.simplereconciler.internal.provider.ActionProviderSelector; import com.netflix.titus.common.framework.simplereconciler.internal.transaction.FailedTransaction; import com.netflix.titus.common.framework.simplereconciler.internal.transaction.SingleTransaction; import com.netflix.titus.common.framework.simplereconciler.internal.transaction.Transaction; import com.netflix.titus.common.framework.simplereconciler.internal.transaction.TransactionStatus; 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.common.util.ExceptionExt; import com.netflix.titus.common.util.time.Clock; import com.netflix.titus.common.util.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoSink; class ReconcilerEngine<DATA> { private static final Logger logger = LoggerFactory.getLogger(ReconcilerEngine.class); static final IllegalStateException EXCEPTION_CLOSED = new IllegalStateException("Reconciler closed"); static final IllegalStateException EXCEPTION_CANCELLED = new IllegalStateException("cancelled"); private final String id; private final ActionProviderSelector<DATA> providerSelector; private final Clock clock; private final BlockingQueue<ChangeActionHolder<DATA>> referenceChangeActions = new LinkedBlockingQueue<>(); private final BlockingQueue<Runnable> closeCallbacks = new LinkedBlockingQueue<>(); private final ReconcilerExecutorMetrics metrics; private final AtomicReference<ReconcilerState> state = new AtomicReference<>(ReconcilerState.Running); private volatile DATA current; /** * We start the transaction numbering from 1, as 0 is reserved for the initial engine creation step. */ private final AtomicLong nextTransactionId = new AtomicLong(1); private volatile Transaction<DATA> pendingTransaction; ReconcilerEngine(String id, DATA initial, ActionProviderSelector<DATA> providerSelector, ReconcilerExecutorMetrics metrics, TitusRuntime titusRuntime) { this.id = id; this.current = initial; this.providerSelector = providerSelector; this.metrics = metrics; this.clock = titusRuntime.getClock(); } void addOnCloseListener(Runnable action) { closeCallbacks.add(action); if (state.get() == ReconcilerState.Closed) { action.run(); } } String getId() { return id; } DATA getCurrent() { return current; } long getNextTransactionId() { return nextTransactionId.get(); } public ReconcilerState getState() { return state.get(); } Transaction<DATA> getPendingTransaction() { return pendingTransaction; } Mono<DATA> apply(Function<DATA, Mono<DATA>> action) { return Mono.create(sink -> { if (state.get() != ReconcilerState.Running) { sink.error(EXCEPTION_CLOSED); return; } long transactionId = nextTransactionId.getAndIncrement(); Function<DATA, Mono<Function<DATA, DATA>>> internalAction = data -> action.apply(data).map(d -> dd -> d); referenceChangeActions.add(new ChangeActionHolder<>(internalAction, transactionId, clock.wallTime(), sink)); // Check again, as it may not be cleaned up by the worker process if the shutdown was in progress. if (state.get() != ReconcilerState.Running) { sink.error(EXCEPTION_CLOSED); } metrics.updateExternalActionQueueSize(id, referenceChangeActions.size()); }); } void close() { state.compareAndSet(ReconcilerState.Running, ReconcilerState.Closing); Evaluators.acceptNotNull(pendingTransaction, Transaction::cancel); } boolean processDataUpdates() { if (pendingTransaction != null) { if (pendingTransaction.getStatus().getState() == TransactionStatus.State.ResultReady) { pendingTransaction.readyToClose(current); if (pendingTransaction.getStatus().getState() == TransactionStatus.State.Completed) { this.current = pendingTransaction.getStatus().getResult(); return true; } else { Throwable error = pendingTransaction.getStatus().getError(); logger.warn("Reconciliation action failure during data merging: status={}, error={}", pendingTransaction.getStatus(), error.getMessage()); logger.debug("Stack trace", error); } } } return false; } /** * Returns function, so evaluation which notifies a subscriber may be run on a different thread. * <p> * TODO Support concurrent transactions in the reconciliation loop. */ Optional<Pair<Optional<DATA>, Runnable>> closeFinishedTransaction() { if (pendingTransaction == null) { return Optional.empty(); } TransactionStatus<DATA> status = pendingTransaction.getStatus(); TransactionStatus.State state = status.getState(); // Still running if (state == TransactionStatus.State.Started || state == TransactionStatus.State.ResultReady) { if (this.state.get() != ReconcilerState.Running) { pendingTransaction.cancel(); } return Optional.empty(); } // If sink is null, it is a reconciliation action MonoSink<DATA> sink = pendingTransaction.getActionHolder().getSubscriberSink(); try { // Completed if (state == TransactionStatus.State.Completed) { DATA result = status.getResult(); if (sink == null) { return Optional.of(Pair.of(Optional.ofNullable(result), Evaluators::doNothing)); } if (result == null) { return Optional.of(Pair.of(Optional.empty(), () -> ExceptionExt.silent(sink::success))); } return Optional.of(Pair.of(Optional.of(result), () -> ExceptionExt.silent(() -> sink.success(result)))); } // Failed if (state == TransactionStatus.State.Failed) { if (sink == null) { logger.warn("Reconciler action failure: {}", pendingTransaction.getStatus().getError().getMessage()); return Optional.empty(); } return Optional.of(Pair.of(Optional.empty(), () -> ExceptionExt.silent(() -> sink.error(status.getError())))); } // Cancelled if (state == TransactionStatus.State.Cancelled) { if (sink == null) { return Optional.empty(); } return Optional.of(Pair.of(Optional.empty(), () -> ExceptionExt.silent(() -> sink.error(new IllegalStateException("cancelled"))))); } // Not reachable unless there is a serious bug. logger.error("Unexpected state: {}", state); return Optional.empty(); } finally { pendingTransaction = null; } } Optional<Runnable> tryToClose() { if (pendingTransaction != null || !referenceChangeActions.isEmpty() || !state.compareAndSet(ReconcilerState.Closing, ReconcilerState.Closed)) { return Optional.empty(); } return Optional.of(() -> closeCallbacks.forEach(c -> ExceptionExt.silent(c::run))); } void startNextChangeAction() { long now = clock.wallTime(); Iterator<ReconcilerActionProvider<DATA>> nextIt = providerSelector.next(now); while (nextIt.hasNext()) { ReconcilerActionProvider<DATA> next = nextIt.next(); providerSelector.updateEvaluationTime(next.getPolicy().getName(), now); if (next.isExternal()) { // Start next reference change action, if present and exit. if (startNextExternalChangeAction()) { return; } } else { // Run reconciler if (startReconcileAction(next.getActionProvider())) { return; } } } } boolean startNextExternalChangeAction() { try { if (pendingTransaction != null) { return false; } ChangeActionHolder<DATA> actionHolder; Transaction<DATA> transaction = null; while (transaction == null && (actionHolder = referenceChangeActions.poll()) != null) { // Ignore all unsubscribed actions if (actionHolder.isCancelled()) { continue; } // Create transaction if (state.get() == ReconcilerState.Running) { try { transaction = new SingleTransaction<>(current, actionHolder); } catch (Exception e) { transaction = new FailedTransaction<>(actionHolder, e); } } else { transaction = new FailedTransaction<>(actionHolder, EXCEPTION_CANCELLED); } } return (pendingTransaction = transaction) != null; } finally { metrics.updateExternalActionQueueSize(id, referenceChangeActions.size()); } } boolean startReconcileAction(Function<DATA, List<Mono<Function<DATA, DATA>>>> actionProvider) { if (state.get() != ReconcilerState.Running) { return false; } List<Mono<Function<DATA, DATA>>> reconcilerActions = actionProvider.apply(current); if (CollectionsExt.isNullOrEmpty(reconcilerActions)) { return false; } // TODO We process first transaction only, as composite transactions are not implemented yet. Mono<Function<DATA, DATA>> action = reconcilerActions.get(0); Function<DATA, Mono<Function<DATA, DATA>>> internalAction = data -> action; long transactionId = nextTransactionId.getAndIncrement(); ChangeActionHolder<DATA> actionHolder = new ChangeActionHolder<>( internalAction, transactionId, clock.wallTime(), null ); pendingTransaction = new SingleTransaction<>(current, actionHolder); return true; } }
911
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/ShardedManyReconciler.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.common.framework.simplereconciler.internal; import java.io.Closeable; 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.atomic.AtomicReference; import java.util.function.Function; import com.netflix.titus.common.framework.simplereconciler.ManyReconciler; import com.netflix.titus.common.framework.simplereconciler.SimpleReconcilerEvent; import com.netflix.titus.common.framework.simplereconciler.internal.provider.ActionProviderSelectorFactory; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.closeable.CloseableReference; import com.netflix.titus.common.util.collections.index.IndexSet; import com.netflix.titus.common.util.collections.index.IndexSetHolder; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; /** * A wrapper around a collection of {@link ManyReconciler}s. Shard allocation is based on the managed entity id, which * eliminates the need for extra level coordination to prevent the same id to be assigned concurrently to many shards. */ public class ShardedManyReconciler<DATA> implements ManyReconciler<DATA> { private static final IllegalStateException EXCEPTION_CLOSED = new IllegalStateException("Sharded reconciler closed"); private final Function<String, Integer> shardIndexSupplier; private final CloseableReference<Scheduler> notificationSchedulerRef; private final IndexSetHolder<String, DATA> indexSetHolder; private final List<ManyReconciler<DATA>> shards; private final AtomicReference<ReconcilerState> stateRef = new AtomicReference<>(ReconcilerState.Running); public ShardedManyReconciler(int shardCount, Function<String, Integer> shardIndexSupplier, Function<Integer, ManyReconciler<DATA>> reconcilerShardFactory, CloseableReference<Scheduler> notificationSchedulerRef, IndexSetHolder<String, DATA> indexSetHolder) { this.shardIndexSupplier = shardIndexSupplier; this.notificationSchedulerRef = notificationSchedulerRef; this.indexSetHolder = indexSetHolder; List<ManyReconciler<DATA>> shards = new ArrayList<>(); for (int i = 0; i < shardCount; i++) { shards.add(reconcilerShardFactory.apply(i)); } this.shards = shards; } @Override public Mono<Void> add(String id, DATA initial) { return Mono.defer(() -> { if (stateRef.get() != ReconcilerState.Running) { return Mono.error(EXCEPTION_CLOSED); } return getShard(id).add(id, initial); }); } @Override public Mono<Void> remove(String id) { return Mono.defer(() -> { if (stateRef.get() != ReconcilerState.Running) { return Mono.error(EXCEPTION_CLOSED); } return getShard(id).remove(id); }).publishOn(notificationSchedulerRef.get()); } @Override public Mono<Void> close() { return Mono.defer(() -> { if (stateRef.get() == ReconcilerState.Closed) { return Mono.empty(); } stateRef.compareAndSet(ReconcilerState.Running, ReconcilerState.Closing); List<Mono<Void>> closeShardActions = new ArrayList<>(); for (ManyReconciler<DATA> shard : shards) { closeShardActions.add(shard.close()); } return Flux.merge(closeShardActions).ignoreElements() .then(Mono.<Void>empty()) .doFinally(signal -> stateRef.set(ReconcilerState.Closed)); }); } @Override public Map<String, DATA> getAll() { Map<String, DATA> result = new HashMap<>(); for (ManyReconciler<DATA> shard : shards) { result.putAll(shard.getAll()); } return result; } @Override public IndexSet<String, DATA> getIndexSet() { return indexSetHolder.getIndexSet(); } @Override public Optional<DATA> findById(String id) { return getShard(id).findById(id); } @Override public int size() { int sum = 0; for (ManyReconciler<DATA> shard : shards) { sum += shard.size(); } return sum; } @Override public Mono<DATA> apply(String id, Function<DATA, Mono<DATA>> action) { return Mono.defer(() -> { if (stateRef.get() != ReconcilerState.Running) { return Mono.error(EXCEPTION_CLOSED); } return getShard(id).apply(id, action); }).publishOn(notificationSchedulerRef.get()); } @Override public Flux<List<SimpleReconcilerEvent<DATA>>> changes(String clientId) { return Flux.defer(() -> { if (stateRef.get() != ReconcilerState.Running) { return Flux.error(EXCEPTION_CLOSED); } List<Flux<List<SimpleReconcilerEvent<DATA>>>> shardsChanges = new ArrayList<>(); shards.forEach(shard -> shardsChanges.add(shard.changes(clientId))); return SnapshotMerger.mergeWithSingleSnapshot(shardsChanges); }).publishOn(notificationSchedulerRef.get()); } private int computeShardOf(String id) { return Math.min(Math.max(0, shardIndexSupplier.apply(id)), shards.size() - 1); } private ManyReconciler<DATA> getShard(String id) { return shards.get(computeShardOf(id)); } public static <DATA> ManyReconciler<DATA> newSharedDefaultManyReconciler(String name, int shardCount, Function<String, Integer> shardIndexSupplier, Duration quickCycle, Duration longCycle, ActionProviderSelectorFactory<DATA> selectorFactory, Function<Integer, CloseableReference<Scheduler>> reconcilerSchedulerSupplier, CloseableReference<Scheduler> notificationSchedulerRef, IndexSetHolder<String, DATA> indexSetHolder, Closeable indexMetricsCloseable, TitusRuntime titusRuntime) { return new ShardedManyReconciler<>( shardCount, shardIndexSupplier, shardIndex -> new DefaultManyReconciler<>( name + "#" + shardIndex, quickCycle, longCycle, selectorFactory, reconcilerSchedulerSupplier.apply(shardIndex), notificationSchedulerRef, indexSetHolder, indexMetricsCloseable, titusRuntime ), notificationSchedulerRef, indexSetHolder ); } }
912
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/ReconcilerExecutorMetrics.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; 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.common.runtime.TitusRuntime; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.time.Clock; public class ReconcilerExecutorMetrics { public static final String ROOT_NAME = "titus.simpleReconciliation.engine."; private static final String EVALUATIONS = ROOT_NAME + "evaluations"; private static final String EXTERNAL_ACTIONS_QUEUE_SIZE = ROOT_NAME + "externalActionQueueSize"; private static final String SINCE_LAST_EVALUATION = ROOT_NAME + "sinceLastEvaluation"; private final Id evaluationId; private final Id sinceLastEvaluationId; private final Id externalActionQueueSizeId; private final ConcurrentMap<String, Gauge> externalActionsQueueSizes = new ConcurrentHashMap<>(); private volatile long lastEvaluationTimestamp; private final Registry registry; private final Clock clock; public ReconcilerExecutorMetrics(String name, TitusRuntime titusRuntime) { this.registry = titusRuntime.getRegistry(); this.clock = titusRuntime.getClock(); this.lastEvaluationTimestamp = clock.wallTime(); this.evaluationId = registry.createId(EVALUATIONS, "reconcilerName", name); this.sinceLastEvaluationId = registry.createId(SINCE_LAST_EVALUATION, "reconcilerName", name); this.externalActionQueueSizeId = registry.createId(EXTERNAL_ACTIONS_QUEUE_SIZE, "reconcilerName", name); PolledMeter.using(registry).withId(sinceLastEvaluationId).monitorValue(this, self -> self.clock.wallTime() - self.lastEvaluationTimestamp); } void shutdown() { PolledMeter.remove(registry, sinceLastEvaluationId); externalActionsQueueSizes.values().forEach(g -> g.set(0)); externalActionsQueueSizes.clear(); } void remove(String id) { Evaluators.acceptNotNull(externalActionsQueueSizes.remove(id), g -> g.set(0.0)); } void evaluated(long executionTimeNs) { registry.timer(evaluationId).record(executionTimeNs, TimeUnit.NANOSECONDS); lastEvaluationTimestamp = clock.wallTime(); } void evaluated(long executionTimeNs, Throwable error) { registry.timer(evaluationId.withTag("error", error.getClass().getSimpleName())).record(executionTimeNs, TimeUnit.NANOSECONDS); } void updateExternalActionQueueSize(String id, int size) { externalActionsQueueSizes.computeIfAbsent(id, i -> registry.gauge(externalActionQueueSizeId.withTag("executorId", id)) ).set(size); } }
913
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/SnapshotMerger.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.common.framework.simplereconciler.internal; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.LinkedBlockingQueue; import com.netflix.titus.common.util.tuple.Pair; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * Helper class that given a list of {@link Flux} list emitters, merges first elements into a single list to build * one snapshot value. */ public class SnapshotMerger { public static <K, T> Flux<List<T>> mergeIndexedStreamWithSingleSnapshot(List<Flux<Pair<K, List<T>>>> indexedStreams) { return Flux.defer(() -> { ConcurrentMap<K, List<T>> snapshots = new ConcurrentHashMap<>(); BlockingQueue<List<T>> updates = new LinkedBlockingQueue<>(); return Flux.merge(indexedStreams).flatMap(pair -> { List<T> event = pair.getRight(); if (snapshots.size() == indexedStreams.size()) { return Mono.just(event); } K shardKey = pair.getLeft(); if (snapshots.containsKey(shardKey)) { updates.add(event); return Flux.empty(); } snapshots.put(shardKey, event); if (snapshots.size() < indexedStreams.size()) { return Flux.empty(); } // We can build full snapshot List<T> mergedSnapshot = new ArrayList<>(); snapshots.forEach((idx, snapshot) -> mergedSnapshot.addAll(snapshot)); List<List<T>> allEvents = new ArrayList<>(); allEvents.add(mergedSnapshot); updates.drainTo(allEvents); return Flux.fromIterable(allEvents); }); }); } public static <T> Flux<List<T>> mergeWithSingleSnapshot(List<Flux<List<T>>> streams) { return Flux.defer(() -> { List<Flux<Pair<Integer, List<T>>>> indexedStreams = new ArrayList<>(); for (int i = 0; i < streams.size(); i++) { int idx = i; indexedStreams.add(streams.get(i).map(e -> Pair.of(idx, e))); } return mergeIndexedStreamWithSingleSnapshot(indexedStreams); }); /* return Flux.defer(() -> { List<Flux<Pair<Integer, List<T>>>> indexedStreams = new ArrayList<>(); for (int i = 0; i < streams.size(); i++) { int idx = i; indexedStreams.add(streams.get(i).map(e -> Pair.of(idx, e))); } ConcurrentMap<Integer, List<T>> snapshots = new ConcurrentHashMap<>(); BlockingQueue<List<T>> updates = new LinkedBlockingQueue<>(); return Flux.merge(indexedStreams).flatMap(pair -> { List<T> event = pair.getRight(); if (snapshots.size() == streams.size()) { return Mono.just(event); } int shardIdx = pair.getLeft(); if (snapshots.containsKey(shardIdx)) { updates.add(event); return Flux.empty(); } snapshots.put(shardIdx, event); if (snapshots.size() < streams.size()) { return Flux.empty(); } // We can build full snapshot List<T> mergedSnapshot = new ArrayList<>(); snapshots.forEach((idx, snapshot) -> mergedSnapshot.addAll(snapshot)); List<List<T>> allEvents = new ArrayList<>(); allEvents.add(mergedSnapshot); updates.drainTo(allEvents); return Flux.fromIterable(allEvents); }); }); */ } }
914
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/DefaultOneOffReconciler.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.time.Duration; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Function; import com.netflix.titus.common.framework.simplereconciler.OneOffReconciler; import com.netflix.titus.common.framework.simplereconciler.internal.provider.ActionProviderSelectorFactory; import com.netflix.titus.common.framework.simplereconciler.internal.transaction.Transaction; import com.netflix.titus.common.runtime.TitusRuntime; 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.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.ReplayProcessor; import reactor.core.scheduler.Scheduler; public class DefaultOneOffReconciler<DATA> implements OneOffReconciler<DATA> { private static final Logger logger = LoggerFactory.getLogger(DefaultOneOffReconciler.class); private final long quickCycleMs; private final long longCycleMs; private final Clock clock; private final TitusRuntime titusRuntime; private final ReconcilerExecutorMetrics metrics; private final ReconcilerEngine<DATA> executor; private final Scheduler.Worker worker; private volatile long lastLongCycleTimestamp; private final ReplayProcessor<DATA> eventProcessor = ReplayProcessor.create(1); private final Flux<DATA> eventStream = eventProcessor.transformDeferred(ReactorExt.badSubscriberHandler(logger)); public DefaultOneOffReconciler(String id, DATA initial, Duration quickCycle, Duration longCycle, ActionProviderSelectorFactory<DATA> selectorFactory, Scheduler scheduler, TitusRuntime titusRuntime) { this.quickCycleMs = quickCycle.toMillis(); this.longCycleMs = longCycle.toMillis(); this.worker = scheduler.createWorker(); this.clock = titusRuntime.getClock(); this.titusRuntime = titusRuntime; this.metrics = new ReconcilerExecutorMetrics(id, titusRuntime); this.executor = new ReconcilerEngine<>(id, initial, selectorFactory.create(), metrics, titusRuntime); eventProcessor.onNext(initial); doSchedule(0); } @Override public Mono<Void> close() { return Mono.create(sink -> { if (executor.getState() == ReconcilerState.Closed) { sink.success(); } else { executor.addOnCloseListener(() -> { sink.success(); worker.dispose(); }); executor.close(); } }); } @Override public DATA getCurrent() { return executor.getCurrent(); } @Override public Mono<DATA> apply(Function<DATA, Mono<DATA>> action) { return executor.apply(action); } @Override public Flux<DATA> changes() { return eventStream; } private void doSchedule(long delayMs) { worker.schedule(() -> { if (executor.getState() == ReconcilerState.Closing) { executor.tryToClose().ifPresent(Runnable::run); } // Self-terminate if (executor.getState() == ReconcilerState.Closed) { eventProcessor.onComplete(); worker.dispose(); return; } long startTimeMs = clock.wallTime(); long startTimeNs = clock.nanoTime(); try { boolean fullCycle = (startTimeMs - lastLongCycleTimestamp) >= longCycleMs; if (fullCycle) { lastLongCycleTimestamp = startTimeMs; } doLoop(fullCycle); doSchedule(quickCycleMs); } catch (Exception e) { metrics.evaluated(clock.nanoTime() - startTimeNs, e); logger.warn("Unexpected error in the reconciliation loop", e); doSchedule(longCycleMs); } finally { metrics.evaluated(clock.nanoTime() - startTimeNs); } }, delayMs, TimeUnit.MILLISECONDS); } private void doLoop(boolean fullReconciliationCycle) { Transaction<DATA> transactionBefore = executor.getPendingTransaction(); boolean completedNow; if (transactionBefore == null) { completedNow = false; } else { executor.processDataUpdates(); executor.closeFinishedTransaction().ifPresent(pair -> { Optional<DATA> data = pair.getLeft(); Runnable action = pair.getRight(); // Emit event first, and run action after, so subscription completes only after events were propagated. data.ifPresent(eventProcessor::onNext); action.run(); }); Transaction<DATA> pendingTransaction = executor.getPendingTransaction(); if (pendingTransaction != null) { return; } completedNow = true; } // Trigger actions on engines. if (fullReconciliationCycle || completedNow) { try { executor.startNextChangeAction(); } catch (Exception e) { logger.warn("[{}] Unexpected error from reconciliation engine 'triggerActions' method", executor.getId(), e); titusRuntime.getCodeInvariants().unexpectedError("Unexpected error in ReconciliationEngine", e); } } } }
915
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/EventDistributor.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.common.framework.simplereconciler.internal; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; import com.google.common.base.Preconditions; import com.google.common.base.Stopwatch; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.common.framework.simplereconciler.SimpleReconcilerEvent; import com.netflix.titus.common.util.ExceptionExt; import reactor.core.publisher.FluxSink; /** * {@link EventDistributor} takes over event notifications from the internal reconciler stream, and distributes them * to registered stream observers. Events notifications are processed by a dedicated thread. */ class EventDistributor<DATA> { private static final String ROOT_METRIC_NAME = "titus.simpleReconciliation.eventDistributor."; private final Supplier<List<SimpleReconcilerEvent<DATA>>> snapshotSupplier; private final Registry registry; private final LinkedBlockingQueue<EmitterHolder> sinkQueue = new LinkedBlockingQueue<>(); private final LinkedBlockingQueue<SimpleReconcilerEvent<DATA>> eventQueue = new LinkedBlockingQueue<>(); private final AtomicInteger eventQueueDepth = new AtomicInteger(); // This is modified only by the internal thread. No need to sync. We use map here for fast removal. // This collection is observed by Spectator poller, so we have to use ConcurrentMap. private final ConcurrentMap<Long, EmitterHolder> activeSinks = new ConcurrentHashMap<>(); private final AtomicLong nextSinkId = new AtomicLong(); private volatile Thread eventLoopThread; private volatile boolean shutdown; // Metrics private final Timer metricLoopExecutionTime; private final Counter metricEmittedEvents; EventDistributor(Supplier<List<SimpleReconcilerEvent<DATA>>> snapshotSupplier, Registry registry) { this.snapshotSupplier = snapshotSupplier; this.metricLoopExecutionTime = registry.timer(ROOT_METRIC_NAME + "executionTime"); this.registry = registry; PolledMeter.using(registry).withName(ROOT_METRIC_NAME + "eventQueue").monitorValue(this, self -> self.eventQueueDepth.get()); PolledMeter.using(registry).withName(ROOT_METRIC_NAME + "activeSubscribers").monitorSize(activeSinks); this.metricEmittedEvents = registry.counter(ROOT_METRIC_NAME + "emittedEvents"); } void start() { Preconditions.checkState(!shutdown, "Already shutdown"); if (eventLoopThread == null) { this.eventLoopThread = new Thread("event-distributor") { @Override public void run() { doLoop(); } }; eventLoopThread.setDaemon(true); eventLoopThread.start(); } } void stop(long timeoutMs) { this.shutdown = true; if (eventLoopThread != null) { try { eventLoopThread.interrupt(); if (timeoutMs > 0) { try { eventLoopThread.join(timeoutMs); } catch (InterruptedException ignore) { } } } finally { eventLoopThread = null; } } } void connectSink(String clientId, FluxSink<List<SimpleReconcilerEvent<DATA>>> sink) { sinkQueue.add(new EmitterHolder(clientId, sink)); } void addEvents(List<SimpleReconcilerEvent<DATA>> events) { eventQueue.addAll(events); eventQueueDepth.accumulateAndGet(events.size(), Integer::sum); } private void doLoop() { while (true) { if (shutdown) { completeEmitters(); return; } Stopwatch start = Stopwatch.createStarted(); List<SimpleReconcilerEvent<DATA>> events = new ArrayList<>(); try { SimpleReconcilerEvent<DATA> event = eventQueue.poll(1, TimeUnit.MILLISECONDS); if (event != null) { events.add(event); } } catch (InterruptedException ignore) { } // Build snapshot early before draining the event queue List<SimpleReconcilerEvent<DATA>> snapshot = null; if (!sinkQueue.isEmpty()) { snapshot = snapshotSupplier.get(); } eventQueue.drainTo(events); eventQueueDepth.accumulateAndGet(events.size(), (current, delta) -> current - delta); // We emit events to already connected sinks first. For new sinks, we build snapshot and merge it with the // pending event queue in addNewSinks method. processEvents(events); removeUnsubscribedSinks(); if (snapshot != null) { addNewSinks(snapshot, events); } metricEmittedEvents.increment(events.size()); metricLoopExecutionTime.record(start.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); } } private void addNewSinks(List<SimpleReconcilerEvent<DATA>> snapshot, List<SimpleReconcilerEvent<DATA>> events) { ArrayList<EmitterHolder> newEmitters = new ArrayList<>(); sinkQueue.drainTo(newEmitters); if (!newEmitters.isEmpty()) { List<SimpleReconcilerEvent<DATA>> merged = mergeSnapshotAndPendingEvents(snapshot, events); newEmitters.forEach(holder -> { activeSinks.put(nextSinkId.getAndIncrement(), holder); holder.onNext(merged); }); } } private void removeUnsubscribedSinks() { Set<Long> cancelled = new HashSet<>(); activeSinks.forEach((id, holder) -> { if (holder.isCancelled()) { cancelled.add(id); } }); activeSinks.keySet().removeAll(cancelled); } private List<SimpleReconcilerEvent<DATA>> mergeSnapshotAndPendingEvents(List<SimpleReconcilerEvent<DATA>> snapshot, List<SimpleReconcilerEvent<DATA>> events) { if (events.isEmpty()) { return snapshot; } Map<String, SimpleReconcilerEvent<DATA>> eventsById = new HashMap<>(); events.forEach(event -> eventsById.put(event.getId(), event)); List<SimpleReconcilerEvent<DATA>> mergeResult = new ArrayList<>(); for (SimpleReconcilerEvent<DATA> event : snapshot) { SimpleReconcilerEvent<DATA> fromQueue = eventsById.get(event.getId()); if (fromQueue == null || fromQueue.getTransactionId() < event.getTransactionId()) { mergeResult.add(event); } else if (fromQueue.getKind() != SimpleReconcilerEvent.Kind.Removed) { mergeResult.add(new SimpleReconcilerEvent<>( SimpleReconcilerEvent.Kind.Added, fromQueue.getId(), fromQueue.getData(), fromQueue.getTransactionId() )); } } return mergeResult; } private void processEvents(List<SimpleReconcilerEvent<DATA>> events) { if (events.isEmpty()) { return; } Set<Long> cancelled = new HashSet<>(); activeSinks.forEach((id, holder) -> { if (!holder.onNext(events)) { cancelled.add(id); } }); activeSinks.keySet().removeAll(cancelled); } private void completeEmitters() { removeUnsubscribedSinks(); Throwable error = new IllegalStateException("Reconciler framework stream closed"); activeSinks.forEach((id, holder) -> holder.onError(error)); activeSinks.clear(); for (EmitterHolder next; (next = sinkQueue.poll()) != null; ) { next.onError(error); } } private class EmitterHolder { private final String id; private final FluxSink<List<SimpleReconcilerEvent<DATA>>> emitter; private volatile boolean cancelled; private final Timer metricOnNext; private final Timer metricOnError; private EmitterHolder(String id, FluxSink<List<SimpleReconcilerEvent<DATA>>> emitter) { this.id = id; this.emitter = emitter; this.metricOnNext = registry.timer(ROOT_METRIC_NAME + "sink", "action", "next", "clientId", id); this.metricOnError = registry.timer(ROOT_METRIC_NAME + "sink", "action", "error", "clientId", id); emitter.onCancel(() -> cancelled = true); } private String getId() { return id; } private boolean isCancelled() { return cancelled; } private boolean onNext(List<SimpleReconcilerEvent<DATA>> event) { if (cancelled) { return false; } Stopwatch stopwatch = Stopwatch.createStarted(); try { emitter.next(event); metricOnNext.record(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); } catch (Throwable e) { ExceptionExt.silent(() -> emitter.error(e)); this.cancelled = true; metricOnError.record(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); return false; } return true; } private void onError(Throwable error) { Stopwatch stopwatch = Stopwatch.createStarted(); try { emitter.error(error); } catch (Throwable ignore) { } finally { metricOnError.record(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); cancelled = true; } } } }
916
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/DefaultManyReconciler.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.io.Closeable; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import com.netflix.titus.common.framework.simplereconciler.ManyReconciler; import com.netflix.titus.common.framework.simplereconciler.SimpleReconcilerEvent; import com.netflix.titus.common.framework.simplereconciler.internal.provider.ActionProviderSelectorFactory; import com.netflix.titus.common.framework.simplereconciler.internal.transaction.Transaction; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.ExceptionExt; import com.netflix.titus.common.util.closeable.CloseableReference; import com.netflix.titus.common.util.collections.index.IndexSet; import com.netflix.titus.common.util.collections.index.IndexSetHolder; import com.netflix.titus.common.util.time.Clock; import com.netflix.titus.common.util.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoSink; import reactor.core.publisher.Sinks; import reactor.core.scheduler.Scheduler; public class DefaultManyReconciler<DATA> implements ManyReconciler<DATA> { private static final Logger logger = LoggerFactory.getLogger(DefaultManyReconciler.class); private static final IllegalStateException EXCEPTION_CLOSED = new IllegalStateException("Reconciler closed"); private final ActionProviderSelectorFactory<DATA> selectorFactory; private final long quickCycleMs; private final long longCycleMs; private final CloseableReference<Scheduler> reconcilerSchedulerRef; private final CloseableReference<Scheduler> notificationSchedulerRef; private final IndexSetHolder<String, DATA> indexSetHolder; private final Closeable indexMetricsCloseable; private final EventDistributor<DATA> eventDistributor; private final Clock clock; private final TitusRuntime titusRuntime; private final BlockingQueue<AddHolder> addHolders = new LinkedBlockingQueue<>(); private final Map<String, ReconcilerEngine<DATA>> executors = new ConcurrentHashMap<>(); private final BlockingQueue<Pair<String, FluxSink<List<SimpleReconcilerEvent<DATA>>>>> eventListenerHolders = new LinkedBlockingQueue<>(); private final AtomicReference<ReconcilerState> stateRef = new AtomicReference<>(ReconcilerState.Running); private final Scheduler.Worker reconcilerWorker; private final ReconcilerExecutorMetrics metrics; private volatile long lastLongCycleTimestamp; private final Sinks.Empty<Void> closedProcessor = Sinks.empty(); public DefaultManyReconciler( String name, Duration quickCycle, Duration longCycle, ActionProviderSelectorFactory<DATA> selectorFactory, CloseableReference<Scheduler> reconcilerSchedulerRef, CloseableReference<Scheduler> notificationSchedulerRef, IndexSetHolder<String, DATA> indexSetHolder, Closeable indexMetricsCloseable, TitusRuntime titusRuntime) { this.quickCycleMs = quickCycle.toMillis(); this.longCycleMs = longCycle.toMillis(); this.selectorFactory = selectorFactory; this.reconcilerSchedulerRef = reconcilerSchedulerRef; this.notificationSchedulerRef = notificationSchedulerRef; this.indexSetHolder = indexSetHolder; this.indexMetricsCloseable = indexMetricsCloseable; this.eventDistributor = new EventDistributor<>(this::buildSnapshot, titusRuntime.getRegistry()); this.clock = titusRuntime.getClock(); this.titusRuntime = titusRuntime; this.reconcilerWorker = reconcilerSchedulerRef.get().createWorker(); this.metrics = new ReconcilerExecutorMetrics(name, titusRuntime); eventDistributor.start(); doSchedule(0); } @Override public Mono<Void> add(String id, DATA initial) { return Mono.<Void>create(sink -> { if (stateRef.get() != ReconcilerState.Running) { sink.error(EXCEPTION_CLOSED); } else { AddHolder holder = new AddHolder(id, initial, sink); addHolders.add(holder); // Check again to deal with race condition during shutdown process if (stateRef.get() != ReconcilerState.Running) { sink.error(EXCEPTION_CLOSED); } } }).publishOn(notificationSchedulerRef.get()); } @Override public Mono<Void> remove(String id) { return Mono.<Void>create(sink -> { if (stateRef.get() != ReconcilerState.Running) { sink.error(EXCEPTION_CLOSED); } else { ReconcilerEngine<DATA> executor = executors.get(id); if (executor == null) { sink.error(new IllegalArgumentException("Reconciler not found for data item " + id)); } else if (executor.getState() == ReconcilerState.Closed) { // If already closed, terminate immediately sink.success(); } else { executor.addOnCloseListener(sink::success); executor.close(); } } }).publishOn(notificationSchedulerRef.get()); } @Override public Mono<Void> close() { return Mono.defer(() -> { stateRef.compareAndSet(ReconcilerState.Running, ReconcilerState.Closing); return closedProcessor.asMono().doFinally(signal -> { reconcilerSchedulerRef.close(); // TODO There may be pending notifications, so we have to delay the actual close. There must be a better solution than timer. notificationSchedulerRef.get().createWorker().schedule(notificationSchedulerRef::close, 5_000, TimeUnit.MILLISECONDS); ExceptionExt.silent(indexMetricsCloseable::close); }); }); } @Override public Map<String, DATA> getAll() { Map<String, DATA> all = new HashMap<>(); executors.forEach((id, executor) -> all.put(id, executor.getCurrent())); return all; } @Override public IndexSet<String, DATA> getIndexSet() { return indexSetHolder.getIndexSet(); } @Override public Optional<DATA> findById(String id) { return Optional.ofNullable(Evaluators.applyNotNull(executors.get(id), ReconcilerEngine::getCurrent)); } @Override public int size() { return executors.size(); } @Override public Mono<DATA> apply(String id, Function<DATA, Mono<DATA>> action) { return Mono.defer(() -> { ReconcilerEngine<DATA> executor = executors.get(id); if (executor == null) { return Mono.error(new IllegalArgumentException("Reconciler not found for data item " + id)); } return executor.apply(action); }); } @Override public Flux<List<SimpleReconcilerEvent<DATA>>> changes(String clientId) { return Flux.<List<SimpleReconcilerEvent<DATA>>>create(sink -> { if (stateRef.get() != ReconcilerState.Running) { sink.error(EXCEPTION_CLOSED); } else { eventListenerHolders.add(Pair.of(clientId, sink)); // Check again to deal with race condition during shutdown process if (stateRef.get() != ReconcilerState.Running) { sink.error(EXCEPTION_CLOSED); } } }).publishOn(notificationSchedulerRef.get()); } private void doSchedule(long delayMs) { reconcilerWorker.schedule(() -> { long startTimeMs = clock.wallTime(); long startTimeNs = clock.nanoTime(); try { // Self-terminate if (stateRef.get() == ReconcilerState.Closed) { reconcilerWorker.dispose(); return; } if (stateRef.get() == ReconcilerState.Closing && tryClose()) { reconcilerWorker.dispose(); return; } connectEventListeners(); boolean fullCycle = (startTimeMs - lastLongCycleTimestamp) >= longCycleMs; if (fullCycle) { lastLongCycleTimestamp = startTimeMs; } doProcess(fullCycle); doSchedule(quickCycleMs); } catch (Throwable e) { metrics.evaluated(clock.nanoTime() - startTimeNs, e); logger.warn("Unexpected error in the reconciliation loop", e); doSchedule(longCycleMs); } finally { metrics.evaluated(clock.nanoTime() - startTimeNs); } }, delayMs, TimeUnit.MILLISECONDS); } private boolean tryClose() { // Cancel newly added for (AddHolder holder; (holder = addHolders.poll()) != null; ) { holder.getSink().error(EXCEPTION_CLOSED); } // Cancel newly added event listeners for (Pair<String, FluxSink<List<SimpleReconcilerEvent<DATA>>>> holder; (holder = eventListenerHolders.poll()) != null; ) { holder.getRight().error(EXCEPTION_CLOSED); } // Close active executors. executors.forEach((id, executor) -> { if (executor.getState() == ReconcilerState.Running) { executor.close(); } }); if (addHolders.isEmpty() && executors.isEmpty()) { stateRef.set(ReconcilerState.Closed); eventDistributor.stop(0L); closedProcessor.tryEmitEmpty(); metrics.shutdown(); } return stateRef.get() == ReconcilerState.Closed; } private void connectEventListeners() { if (eventListenerHolders.isEmpty()) { return; } for (Pair<String, FluxSink<List<SimpleReconcilerEvent<DATA>>>> holder; (holder = eventListenerHolders.poll()) != null; ) { eventDistributor.connectSink(holder.getLeft(), holder.getRight()); } } /** * Snapshot is built by {@link EventDistributor} thread, but as {@link #executors} is {@link ConcurrentHashMap}, and * {@link ReconcilerEngine#getCurrent()} is a volatile access it is safe to do so. */ private List<SimpleReconcilerEvent<DATA>> buildSnapshot() { List<SimpleReconcilerEvent<DATA>> allState = new ArrayList<>(); executors.forEach((id, executor) -> { // We emit event with the id of the last completed transaction. long transactionId = executor.getNextTransactionId() - 1; SimpleReconcilerEvent<DATA> event = new SimpleReconcilerEvent<>( SimpleReconcilerEvent.Kind.Added, executor.getId(), executor.getCurrent(), transactionId ); allState.add(event); }); return allState; } private void doProcess(boolean fullReconciliationCycle) { // Data update executors.forEach((id, executor) -> { if (executor.processDataUpdates()) { indexSetHolder.add(Collections.singletonList(executor.getCurrent())); } }); // Complete subscribers Set<String> justChanged = new HashSet<>(); executors.forEach((id, executor) -> { Transaction<DATA> transactionBefore = executor.getPendingTransaction(); if (transactionBefore != null) { executor.closeFinishedTransaction().ifPresent(pair -> { Optional<DATA> data = pair.getLeft(); Runnable action = pair.getRight(); // Emit event first, and run action after, so subscription completes only after events were propagated. data.ifPresent(t -> eventDistributor.addEvents( Collections.singletonList(new SimpleReconcilerEvent<>( SimpleReconcilerEvent.Kind.Updated, executor.getId(), t, transactionBefore.getActionHolder().getTransactionId() )) )); action.run(); }); if (executor.getPendingTransaction() == null) { justChanged.add(executor.getId()); } } }); // Remove closed executors. for (Iterator<ReconcilerEngine<DATA>> it = executors.values().iterator(); it.hasNext(); ) { ReconcilerEngine<DATA> executor = it.next(); if (executor.getState() == ReconcilerState.Closing) { Optional<Runnable> runnable = executor.tryToClose(); if (executor.getState() == ReconcilerState.Closed) { it.remove(); indexSetHolder.remove(Collections.singletonList(executor.getId())); metrics.remove(executor.getId()); // This is the very last action, so we can take safely the next transaction id without progressing it. eventDistributor.addEvents(Collections.singletonList( new SimpleReconcilerEvent<>(SimpleReconcilerEvent.Kind.Removed, executor.getId(), executor.getCurrent(), executor.getNextTransactionId()) )); runnable.ifPresent(Runnable::run); } } } // Add new executors for (AddHolder holder; (holder = addHolders.poll()) != null; ) { ReconcilerEngine<DATA> executor = holder.getExecutor(); executors.put(holder.getId(), executor); indexSetHolder.add(Collections.singletonList(executor.getCurrent())); // We set transaction id "0" for the newly added executors. eventDistributor.addEvents(Collections.singletonList( new SimpleReconcilerEvent<>(SimpleReconcilerEvent.Kind.Added, executor.getId(), executor.getCurrent(), 0) )); holder.getSink().success(); justChanged.add(holder.getId()); } // Trigger actions on executors. executors.forEach((id, executor) -> { if (executor.getPendingTransaction() == null) { if (fullReconciliationCycle || justChanged.contains(id)) { try { executor.startNextChangeAction(); } catch (Exception e) { logger.warn("[{}] Unexpected error from reconciliation executor", executor.getId(), e); titusRuntime.getCodeInvariants().unexpectedError("Unexpected error in reconciliation executor", e); } } } }); } private class AddHolder { private final ReconcilerEngine<DATA> executor; private final MonoSink<Void> sink; private AddHolder(String id, DATA initial, MonoSink<Void> sink) { this.sink = sink; this.executor = new ReconcilerEngine<>( id, initial, selectorFactory.create(), metrics, titusRuntime ); } private String getId() { return executor.getId(); } private ReconcilerEngine<DATA> getExecutor() { return executor; } private MonoSink<Void> getSink() { return sink; } } }
917
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/ChangeActionHolder.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import javax.annotation.Nullable; import com.netflix.titus.common.util.rx.ReactorExt; import reactor.core.Disposable; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoSink; public final class ChangeActionHolder<DATA> { private final Function<DATA, Mono<Function<DATA, DATA>>> action; private final long transactionId; private final long createTimestamp; private final MonoSink<DATA> subscriberSink; private AtomicBoolean cancelledRef = new AtomicBoolean(); private final Queue<Disposable> cancelCallbacks = new ConcurrentLinkedQueue<>(); public ChangeActionHolder(Function<DATA, Mono<Function<DATA, DATA>>> action, long transactionId, long createTimestamp, @Nullable MonoSink<DATA> subscriberSink) { this.action = action; this.transactionId = transactionId; this.createTimestamp = createTimestamp; this.subscriberSink = subscriberSink; if (subscriberSink != null) { subscriberSink.onCancel(() -> { cancelledRef.set(true); Disposable next; while ((next = cancelCallbacks.poll()) != null) { ReactorExt.safeDispose(next); } }); } } public Function<DATA, Mono<Function<DATA, DATA>>> getAction() { return action; } public long getTransactionId() { return transactionId; } public long getCreateTimestamp() { return createTimestamp; } public boolean isCancelled() { return cancelledRef.get(); } @Nullable public MonoSink<DATA> getSubscriberSink() { return subscriberSink; } /** * All callbacks should obey the {@link Disposable#dispose()} idempotence contract. */ public void addCancelCallback(Disposable cancelCallback) { cancelCallbacks.add(cancelCallback); if (cancelledRef.get()) { ReactorExt.safeDispose(cancelCallback); } } }
918
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/ReconcilerState.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; enum ReconcilerState { Running, Closing, Closed }
919
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/transaction/SingleTransaction.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal.transaction; import java.util.function.Function; import java.util.function.Supplier; import com.google.common.base.Preconditions; import com.netflix.titus.common.framework.simplereconciler.internal.ChangeActionHolder; import com.netflix.titus.common.util.rx.ReactorExt; import reactor.core.Disposable; import reactor.core.Disposables; public class SingleTransaction<DATA> implements Transaction<DATA> { private final ChangeActionHolder<DATA> actionHolder; private volatile Disposable subscription; private volatile TransactionStatus<DATA> transactionStatus; public SingleTransaction(DATA current, ChangeActionHolder<DATA> actionHolder) { this.actionHolder = actionHolder; this.transactionStatus = TransactionStatus.started(); try { this.subscription = actionHolder.getAction().apply(current) .doOnCancel(() -> transitionIfRunning(TransactionStatus::cancelled)) .subscribe( newValue -> transitionIfRunning(() -> transactionStatus.resultReady(newValue)), error -> transitionIfRunning(() -> TransactionStatus.failed(error)), () -> transitionIfRunning(() -> transactionStatus.resultReady(Function.identity())) ); } catch (Exception e) { this.subscription = Disposables.disposed(); this.transactionStatus = TransactionStatus.failed(e); return; } actionHolder.addCancelCallback(subscription); } @Override public void cancel() { ReactorExt.safeDispose(subscription); } @Override public ChangeActionHolder<DATA> getActionHolder() { return actionHolder; } @Override public TransactionStatus<DATA> getStatus() { return transactionStatus; } @Override public void readyToClose(DATA current) { synchronized (this) { Preconditions.checkState(transactionStatus.getState() == TransactionStatus.State.ResultReady); transactionStatus = transactionStatus.complete(current); } } private void transitionIfRunning(Supplier<TransactionStatus<DATA>> nextStatusSupplier) { synchronized (this) { if (transactionStatus.getState() == TransactionStatus.State.Started) { try { transactionStatus = nextStatusSupplier.get(); } catch (Exception e) { transactionStatus = TransactionStatus.failed(e); } } } } }
920
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/transaction/TransactionStatus.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal.transaction; import java.util.Objects; import java.util.function.Function; import javax.annotation.Nullable; import com.google.common.base.Preconditions; public class TransactionStatus<DATA> { public enum State { Started, ResultReady, Completed, Failed, Cancelled; } private final State state; private final Function<DATA, DATA> resultEvaluator; private final DATA result; private final Throwable error; public TransactionStatus(State state, @Nullable Function<DATA, DATA> resultEvaluator, @Nullable DATA result, @Nullable Throwable error) { this.state = state; this.resultEvaluator = resultEvaluator; this.result = result; this.error = error; } public State getState() { return state; } @Nullable public DATA getResult() { return result; } public Throwable getError() { return error; } public TransactionStatus<DATA> resultReady(Function<DATA, DATA> resultEvaluator) { Preconditions.checkState(state == State.Started, "Not in Started state: %s", state); return new TransactionStatus<>(State.ResultReady, resultEvaluator, null, null); } public TransactionStatus<DATA> complete(DATA current) { Preconditions.checkState(state == State.ResultReady, "Not in ResultReady state: %s", state); try { return new TransactionStatus<>( State.Completed, null, resultEvaluator.apply(current), null ); } catch (Exception e) { return failed(e); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TransactionStatus<?> that = (TransactionStatus<?>) o; return state == that.state && Objects.equals(resultEvaluator, that.resultEvaluator) && Objects.equals(result, that.result) && Objects.equals(error, that.error); } @Override public int hashCode() { return Objects.hash(state, resultEvaluator, result, error); } @Override public String toString() { switch (state) { case ResultReady: case Completed: return "TransactionStatus{" + "state=" + state + ", result=" + result + '}'; case Failed: return "TransactionStatus{" + "state=" + state + ", error=" + error + '}'; case Started: case Cancelled: default: return "TransactionStatus{" + "state=" + state + '}'; } } public static <DATA> TransactionStatus<DATA> started() { return new TransactionStatus<>(State.Started, null, null, null); } public static <DATA> TransactionStatus<DATA> failed(Throwable error) { Preconditions.checkNotNull(error, "Error is null"); return new TransactionStatus<>(State.Failed, null, null, error); } public static <DATA> TransactionStatus<DATA> cancelled() { return new TransactionStatus<>(State.Cancelled, null, null, null); } }
921
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/transaction/FailedTransaction.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal.transaction; import com.netflix.titus.common.framework.simplereconciler.internal.ChangeActionHolder; public class FailedTransaction<DATA> implements Transaction<DATA> { private final ChangeActionHolder actionHolder; private final TransactionStatus<DATA> transactionStatus; public FailedTransaction(ChangeActionHolder actionHolder, Throwable error) { this.actionHolder = actionHolder; this.transactionStatus = TransactionStatus.failed(error); } @Override public void cancel() { } @Override public ChangeActionHolder<DATA> getActionHolder() { return actionHolder; } @Override public TransactionStatus<DATA> getStatus() { return transactionStatus; } @Override public void readyToClose(DATA currentValue) { } }
922
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/transaction/Transaction.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal.transaction; import com.netflix.titus.common.framework.simplereconciler.internal.ChangeActionHolder; public interface Transaction<DATA> { ChangeActionHolder<DATA> getActionHolder(); TransactionStatus<DATA> getStatus(); void cancel(); void readyToClose(DATA currentValue); }
923
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/provider/ActionProviderSelectorFactory.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.common.framework.simplereconciler.internal.provider; import java.util.List; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProvider; import com.netflix.titus.common.runtime.TitusRuntime; public class ActionProviderSelectorFactory<DATA> { private final String name; private final List<ReconcilerActionProvider<DATA>> actionProviders; private final TitusRuntime titusRuntime; public ActionProviderSelectorFactory(String name, List<ReconcilerActionProvider<DATA>> actionProviders, TitusRuntime titusRuntime) { this.name = name; this.actionProviders = actionProviders; this.titusRuntime = titusRuntime; } public ActionProviderSelector<DATA> create() { return new ActionProviderSelector<>(name, actionProviders, titusRuntime); } }
924
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/provider/ActionProviderSelector.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.common.framework.simplereconciler.internal.provider; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import com.google.common.base.Preconditions; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProvider; import com.netflix.titus.common.framework.simplereconciler.ReconcilerActionProviderPolicy; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.collections.OneItemIterator; import com.netflix.titus.common.util.time.Clock; public class ActionProviderSelector<DATA> { private static final String ROOT_NAME = "titus.simpleReconciliation.engine.provider"; private final List<ProviderState<DATA>> providerList; private final Map<String, ProviderState<DATA>> providers; public ActionProviderSelector(String name, List<ReconcilerActionProvider<DATA>> providers, TitusRuntime titusRuntime) { this.providerList = providers.stream() .map(actionProvider -> new ProviderState<>(name, actionProvider, titusRuntime)) .collect(Collectors.toList()); this.providers = providerList.stream().collect( Collectors.toMap(p -> p.getActionProvider().getPolicy().getName(), Function.identity()) ); } public Iterator<ReconcilerActionProvider<DATA>> next(long now) { // We handle explicitly the two most common cases for the best performance. if (providerList.size() == 1) { return handleOne(now); } if (providerList.size() == 2) { return handleTwo(now); } return handleMany(now); } public void updateEvaluationTime(String name, long timestamp) { ProviderState<DATA> provider = Preconditions.checkNotNull(providers.get(name), "unknown provider: name=%s", name); provider.updateEvaluationTime(timestamp); } private Iterator<ReconcilerActionProvider<DATA>> handleOne(long now) { ProviderState<DATA> provider = providerList.get(0); if (!provider.isDue(now)) { return Collections.emptyIterator(); } return new OneItemIterator<>(provider.getActionProvider()); } private Iterator<ReconcilerActionProvider<DATA>> handleTwo(long now) { ProviderState<DATA> provider1 = providerList.get(0); ProviderState<DATA> provider2 = providerList.get(1); if (provider1.isDue(now)) { if (provider2.isDue(now)) { int provider1Priority = provider1.getEffectivePriority(now); int provider2Priority = provider2.getEffectivePriority(now); if (provider1Priority == provider2Priority) { if (provider1.getLastUpdateTimestamp() < provider2.getLastUpdateTimestamp()) { return CollectionsExt.newIterator(provider1.getActionProvider(), provider2.getActionProvider()); } return CollectionsExt.newIterator(provider2.getActionProvider(), provider1.getActionProvider()); } else if (provider1Priority < provider2Priority) { return CollectionsExt.newIterator(provider1.getActionProvider(), provider2.getActionProvider()); } return CollectionsExt.newIterator(provider2.getActionProvider(), provider1.getActionProvider()); } return CollectionsExt.newIterator(provider1.getActionProvider()); } if (provider2.isDue(now)) { return CollectionsExt.newIterator(provider2.getActionProvider()); } return Collections.emptyIterator(); } private Iterator<ReconcilerActionProvider<DATA>> handleMany(long now) { List<ProviderState<DATA>> filtered = new ArrayList<>(); for (ProviderState<DATA> p : providerList) { if (p.isDue(now)) { filtered.add(p); } } filtered.sort(new ProviderStateComparator<>(now)); List<ReconcilerActionProvider<DATA>> result = new ArrayList<>(); for (ProviderState<DATA> p : filtered) { result.add(p.getActionProvider()); } return result.iterator(); } private static class ProviderState<DATA> { private final ReconcilerActionProvider<DATA> actionProvider; private final long executionIntervalMs; private final long minimumExecutionIntervalMs; private final Clock clock; private long lastUpdateTimestamp; private ProviderState(String name, ReconcilerActionProvider<DATA> actionProvider, TitusRuntime titusRuntime) { this.actionProvider = actionProvider; this.executionIntervalMs = Math.max(0, actionProvider.getPolicy().getExecutionInterval().toMillis()); this.minimumExecutionIntervalMs = Math.max(0, actionProvider.getPolicy().getMinimumExecutionInterval().toMillis()); this.lastUpdateTimestamp = -1; this.clock = titusRuntime.getClock(); Registry registry = titusRuntime.getRegistry(); PolledMeter.using(registry) .withId(registry.createId(ROOT_NAME + "timeSinceLastEvaluation", "provider", name)) .monitorValue(this, self -> clock.wallTime() - self.lastUpdateTimestamp ); } private ReconcilerActionProvider<DATA> getActionProvider() { return actionProvider; } private int getEffectivePriority(long now) { int priority = actionProvider.getPolicy().getPriority(); if (minimumExecutionIntervalMs < 1) { return priority; } long elapsed = now - this.lastUpdateTimestamp; if (elapsed < minimumExecutionIntervalMs) { return priority; } return ReconcilerActionProviderPolicy.EXCEEDED_MIN_EXECUTION_INTERVAL_PRIORITY; } private long getLastUpdateTimestamp() { return lastUpdateTimestamp; } private boolean isDue(long now) { if (executionIntervalMs < 1) { return true; } return lastUpdateTimestamp + executionIntervalMs <= now; } public void updateEvaluationTime(long now) { this.lastUpdateTimestamp = now; } } private static class ProviderStateComparator<DATA> implements Comparator<ProviderState<DATA>> { private final long now; public ProviderStateComparator(long now) { this.now = now; } @Override public int compare(ProviderState<DATA> first, ProviderState<DATA> second) { int priority1 = first.getEffectivePriority(now); int priority2 = second.getEffectivePriority(now); if (priority1 < priority2) { return -1; } if (priority2 < priority1) { return 1; } return Long.compare(first.getLastUpdateTimestamp(), second.getLastUpdateTimestamp()); } } }
925
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/ReconcileEventFactory.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler; import java.util.Optional; /** * Each change in {@link ReconciliationEngine} emits a notification. Notification types are not predefined by the * framework, and instead a user must provide a factory to produce them. The events are emitted via * {@link ReconciliationEngine#events()}, and {@link ReconciliationFramework#events()} observables. * * @param <EVENT> event model type */ public interface ReconcileEventFactory<EVENT> { EVENT newCheckpointEvent(long timestamp); /** * Called when a new {@link ChangeAction} is registered, but not executed yet. */ EVENT newBeforeChangeEvent(ReconciliationEngine<EVENT> engine, ChangeAction changeAction, String transactionId); /** * Called when a {@link ChangeAction} execution is completed. */ EVENT newAfterChangeEvent(ReconciliationEngine<EVENT> engine, ChangeAction changeAction, long waitTimeMs, long executionTimeMs, String transactionId); /** * Called when a {@link ChangeAction} execution is completes with an error. */ EVENT newChangeErrorEvent(ReconciliationEngine<EVENT> engine, ChangeAction changeAction, Throwable error, long waitTimeMs, long executionTimeMs, String transactionId); /** * Called when a new {@link ReconciliationEngine} instance is created, and populated with the initial model. */ EVENT newModelEvent(ReconciliationEngine<EVENT> engine, EntityHolder newRoot); /** * Called after each update to {@link EntityHolder} instance. */ EVENT newModelUpdateEvent(ReconciliationEngine<EVENT> engine, ChangeAction changeAction, ModelActionHolder modelActionHolder, EntityHolder changedEntityHolder, Optional<EntityHolder> previousEntityHolder, String transactionId); /** * Called after failed update to an {@link EntityHolder} instance. */ EVENT newModelUpdateErrorEvent(ReconciliationEngine<EVENT> engine, ChangeAction changeAction, ModelActionHolder modelActionHolder, EntityHolder previousEntityHolder, Throwable error, String transactionId); }
926
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/ModelActionHolder.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * {@link ModelAction} wrapper with context information. */ public class ModelActionHolder { public enum Model {Reference, Running, Store} private final Model model; private final ModelAction action; private ModelActionHolder(Model model, ModelAction action) { this.model = model; this.action = action; } public Model getModel() { return model; } public ModelAction getAction() { return action; } public static ModelActionHolder reference(ModelAction action) { return new ModelActionHolder(Model.Reference, action); } public static List<ModelActionHolder> referenceList(ModelAction action) { return Collections.singletonList(new ModelActionHolder(Model.Reference, action)); } public static ModelActionHolder running(ModelAction action) { return new ModelActionHolder(Model.Running, action); } public static List<ModelActionHolder> runningList(ModelAction action) { return Collections.singletonList(new ModelActionHolder(Model.Running, action)); } public static ModelActionHolder store(ModelAction action) { return new ModelActionHolder(Model.Store, action); } public static List<ModelActionHolder> storeList(ModelAction action) { return Collections.singletonList(new ModelActionHolder(Model.Store, action)); } public static List<ModelActionHolder> allModels(ModelAction action) { return Arrays.asList(reference(action), running(action), store(action)); } public static List<ModelActionHolder> referenceAndRunning(ModelAction action) { return Arrays.asList(reference(action), running(action)); } public static List<ModelActionHolder> referenceAndStore(ModelAction action) { return Arrays.asList(reference(action), store(action)); } public static List<ModelActionHolder> runningAndStore(ModelAction action) { return Arrays.asList(running(action), store(action)); } }
927
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/ModelAction.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler; import java.util.Optional; import com.netflix.titus.common.util.tuple.Pair; public interface ModelAction { /** * Update an {@link EntityHolder} hierarchy. It is expected that only one {@link EntityHolder} is modified by * single action. The result always contains a new root value (left), and the entity that was created or updated (right). * If the root value was updated, both left and right fields contain a reference to the new root value. * * @return {@link Optional#empty()} if no change was made, or new versions of the {@link EntityHolder} entities */ Optional<Pair<EntityHolder, EntityHolder>> apply(EntityHolder rootHolder); }
928
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/EntityHolder.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler; 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.function.Consumer; import com.netflix.titus.common.util.tuple.Pair; /** * Composite entity hierarchy. The parent-child association runs from parent to child only. {@link EntityHolder} instances * are immutable, thus each change produces a new version of an entity. Also each child update requires update of a parent * entity, when the reference to the child changes (a new version is created). */ public class EntityHolder { private final String id; private final Object entity; private final List<EntityHolder> children; private final Map<String, EntityHolder> childrenById; private final Map<String, Object> attributes; private EntityHolder(String id, Object entity, Map<String, EntityHolder> childrenById, Map<String, Object> attributes) { this.id = id; this.entity = entity; this.childrenById = childrenById; this.children = new ArrayList<>(childrenById.values()); this.attributes = attributes; } public String getId() { return id; } public <E> E getEntity() { return (E) entity; } public List<EntityHolder> getChildren() { return children; } public Map<String, Object> getAttributes() { return attributes; } public Optional<EntityHolder> findById(String requestedId) { if (this.id.equals(requestedId)) { return Optional.of(this); } return findChildById(requestedId); } public Optional<EntityHolder> findChildById(String childId) { if (children.isEmpty()) { return Optional.empty(); } EntityHolder entityHolder = childrenById.get(childId); if (entityHolder != null) { return Optional.of(entityHolder); } for (EntityHolder child : children) { Optional<EntityHolder> result = child.findChildById(childId); if (result.isPresent()) { return result; } } return Optional.empty(); } public EntityHolder addChild(EntityHolder child) { Map<String, EntityHolder> newChildrenById = new HashMap<>(childrenById); newChildrenById.put(child.getId(), child); return new EntityHolder(id, entity, newChildrenById, attributes); } public Pair<EntityHolder, Optional<EntityHolder>> removeChild(String id) { if (!childrenById.containsKey(id)) { return Pair.of(this, Optional.empty()); } Map<String, EntityHolder> newChildrenById = new HashMap<>(childrenById); EntityHolder removedChild = newChildrenById.remove(id); EntityHolder newRoot = new EntityHolder(this.id, this.entity, newChildrenById, this.attributes); return Pair.of(newRoot, Optional.of(removedChild)); } public EntityHolder addTag(String tagName, Object tagValue) { Map<String, Object> newTags = new HashMap<>(attributes); newTags.put(tagName, tagValue); return new EntityHolder(id, entity, childrenById, newTags); } public EntityHolder removeTag(String tagName) { if (!attributes.containsKey(tagName)) { return this; } Map<String, Object> newTags = new HashMap<>(attributes); newTags.remove(tagName); return new EntityHolder(id, entity, childrenById, newTags); } public <E> EntityHolder setEntity(E entity) { return new EntityHolder(id, entity, childrenById, attributes); } public void visit(Consumer<EntityHolder> visitor) { visitor.accept(this); children.forEach(c -> c.visit(visitor)); } public static <E> EntityHolder newRoot(String id, E entity) { return new EntityHolder(id, entity, Collections.emptyMap(), Collections.emptyMap()); } }
929
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/ReconciliationFramework.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler; import java.util.List; import java.util.Optional; import java.util.function.BiFunction; import com.netflix.titus.common.util.tuple.Pair; import rx.Completable; import rx.Observable; /** * {@link ReconciliationFramework} manages lifecycle of multiple {@link ReconciliationEngine} instances, as well * as orchestrates their reconciliation processes. */ public interface ReconciliationFramework<EVENT> { /** * Starts the framework */ void start(); /** * Stops the reconciliation framework * * @return true if it was stopped in the specified timeout */ boolean stop(long timeoutMs); /** * Event stream of changes in the engine. */ Observable<EVENT> events(); /** * @return {@link ReconciliationEngine} with root node having the given id or {@link Optional#empty()}. */ Optional<ReconciliationEngine<EVENT>> findEngineByRootId(String id); /** * @return parent and its child node with the given child id or {@link Optional#empty()}. */ Optional<Pair<ReconciliationEngine<EVENT>, EntityHolder>> findEngineByChildId(String childId); /** * Returns all roots of {@link ReconciliationEngine} instances ordered by the requested ordering criteria. The returned * list is immutable, and constitutes a snapshot of the entity model. * * @throws IllegalArgumentException if the ordering criteria are not recognized */ <ORDER_BY> List<EntityHolder> orderedView(ORDER_BY orderingCriteria); /** * Creates a new reconciliation engine. */ Observable<ReconciliationEngine<EVENT>> newEngine(EntityHolder bootstrapModel); /** * Removes an existing reconciliation engine. */ Completable removeEngine(ReconciliationEngine<EVENT> engine); /** * Change reference entities for the provided list of the reconciliation engines. The returned observable completes * successfully if the change action and the all model update actions completed successfully. */ Observable<Void> changeReferenceModel(MultiEngineChangeAction multiEngineChangeAction, BiFunction<String, Observable<List<ModelActionHolder>>, ChangeAction> engineChangeActionFactory, String... rootEntityHolderIds); }
930
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/DifferenceResolvers.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler; import java.util.function.Function; import com.netflix.titus.common.framework.reconciler.internal.DispatchingDifferenceResolver; /** * {@link ReconciliationEngine.DifferenceResolver} wrappers, and helper functions. */ public final class DifferenceResolvers { private DifferenceResolvers() { } public static <EVENT> ReconciliationEngine.DifferenceResolver<EVENT> dispatcher(Function<EntityHolder, ReconciliationEngine.DifferenceResolver<EVENT>> dispatcherFun) { return new DispatchingDifferenceResolver<>(dispatcherFun); } }
931
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/MultiEngineChangeAction.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler; import java.util.List; import java.util.Map; import rx.Observable; /** * Change action which modifies state of multiple reconcilation engines. */ public interface MultiEngineChangeAction { /** * Performs changes on external resources, and if successful emits corresponding model updates for each * reconciliation engine which is part of this change. */ Observable<Map<String, List<ModelActionHolder>>> apply(); }
932
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/ChangeAction.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler; import java.util.List; import rx.Observable; /** */ public interface ChangeAction { /** * Performs changes on external resources, and if successful emits corresponding model updates. */ Observable<List<ModelActionHolder>> apply(); }
933
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/ReconciliationEngine.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler; import java.util.List; import rx.Observable; /** */ public interface ReconciliationEngine<EVENT> { interface DifferenceResolver<EVENT> { List<ChangeAction> apply(ReconciliationEngine<EVENT> engine); } /** * Change reference entity. The return observable completes successfully if the reference update was * successful. The action itself may include calls to external system to make the change persistent. * Examples of actions: * <ul> * <li>Job scale up</li> * <li>User requested task termination</li> * </ul> * Task completion can take some time, but it is always guarded by a timeout. If timeout triggers, the result is unknown. * Multiple change requests are processed in order of arrival, one at a time. If action execution deadline is * crossed, it is rejected. The deadline value must be always greater than the execution timeout. */ Observable<Void> changeReferenceModel(ChangeAction changeAction); /** * Change reference entity with the given id. Change actions for non-overlapping entities can be executed in parallel. */ Observable<Void> changeReferenceModel(ChangeAction changeAction, String entityHolderId); /** * Returns immutable reference model. */ EntityHolder getReferenceView(); /** * Returns immutable running model. */ EntityHolder getRunningView(); /** * Returns immutable persisted model. */ EntityHolder getStoreView(); <ORDER_BY> List<EntityHolder> orderedView(ORDER_BY orderingCriteria); /** * Emits an event for each requested system change , and reconciliation action. */ Observable<EVENT> events(); }
934
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/InternalReconciliationEngine.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import com.netflix.titus.common.framework.reconciler.ReconciliationEngine; public interface InternalReconciliationEngine<EVENT> extends ReconciliationEngine<EVENT> { boolean hasPendingTransactions(); /** * Apply pending model updates. The model updates come from recently completed change actions (either requested or reconcile), * and must be processed by the event loop before next action(s) are started. * * @return true if the reference model (visible by the external clients) was updated */ boolean applyModelUpdates(); void emitEvents(); boolean closeFinishedTransactions(); /** * Emit events and execute pending actions. The execution order is: * <ul> * <li>Emit all queued events first</li> * <li>If there is pending reference change action, exit</li> * <li>Start next reference change action, if present and exit</li> * <li>If no reference action waits in the queue, check if there are running reconciliation actions. Exit if there are any.</li> * <li>Compute the difference between the reference and running states, and create reconcile action list</li> * <li>Start all independent actions from the beginning of the list</li> * </ul> * * @return true if there are actions running, false otherwise */ boolean triggerActions(); }
935
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/SingleTransaction.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import com.netflix.titus.common.framework.reconciler.ChangeAction; import com.netflix.titus.common.framework.reconciler.EntityHolder; import com.netflix.titus.common.framework.reconciler.ModelActionHolder; import com.netflix.titus.common.framework.reconciler.ReconcileEventFactory; import com.netflix.titus.common.util.time.Clock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observer; import rx.Subscriber; import rx.Subscription; import rx.subjects.PublishSubject; class SingleTransaction<EVENT> implements Transaction { private static final Logger logger = LoggerFactory.getLogger(SingleTransaction.class); enum TransactionStep { ChangeActionStarted, ChangeActionCompleted, ChangeActionFailed, ChangeActionUnsubscribed, ModelsUpdated, EventsEmitted, ErrorEventsEmitted, SubscribersCompleted } private final DefaultReconciliationEngine<EVENT> engine; private final ReconcileEventFactory<EVENT> eventFactory; private final PublishSubject<EVENT> eventSubject; private final ReconciliationEngineMetrics<EVENT> metrics; private final Clock clock; private final ChangeAction changeAction; private final Optional<Subscriber<Void>> changeActionSubscriber; private final String transactionId; private final long changeActionWaitTimeMs; private final Subscription changeActionSubscription; private TransactionStep transactionStep = TransactionStep.ChangeActionStarted; // Set by change action, which my be executed by a different thread. private volatile List<ModelActionHolder> modelActionHolders; private volatile Throwable changeActionError; private volatile long changeActionExecutionTimeMs; private final List<EVENT> modelEventQueue = new ArrayList<>(); SingleTransaction(DefaultReconciliationEngine<EVENT> engine, ChangeAction changeAction, long changeActionCreateTimestamp, Optional<Subscriber<Void>> changeActionSubscriber, String transactionId, boolean byReconciler) { this.engine = engine; this.eventFactory = engine.getEventFactory(); this.eventSubject = engine.getEventSubject(); this.metrics = engine.getMetrics(); this.clock = engine.getTitusRuntime().getClock(); this.changeAction = changeAction; this.changeActionSubscriber = changeActionSubscriber; this.transactionId = transactionId; this.changeActionWaitTimeMs = clock.wallTime() - changeActionCreateTimestamp; long startTimeNs = clock.nanoTime(); metrics.changeActionStarted(changeAction, changeActionCreateTimestamp, byReconciler); AtomicBoolean metricsNotUpdated = new AtomicBoolean(true); this.changeActionSubscription = changeAction.apply() .doOnUnsubscribe(() -> { if (metricsNotUpdated.getAndSet(false)) { metrics.changeActionUnsubscribed(changeAction, clock.nanoTime() - startTimeNs, byReconciler); } if (transactionStep == TransactionStep.ChangeActionStarted) { this.transactionStep = TransactionStep.ChangeActionUnsubscribed; } }) .subscribe( modelActionHolders -> { this.modelActionHolders = modelActionHolders; }, e -> { if (metricsNotUpdated.getAndSet(false)) { metrics.changeActionFinished(changeAction, clock.nanoTime() - startTimeNs, e, byReconciler); } this.changeActionError = e; this.changeActionExecutionTimeMs = passedMs(startTimeNs); this.transactionStep = TransactionStep.ChangeActionFailed; logger.debug("Action execution error", e); }, () -> { if (metricsNotUpdated.getAndSet(false)) { metrics.changeActionFinished(changeAction, clock.nanoTime() - startTimeNs, byReconciler); } if (modelActionHolders == null) { // TODO invariant violation this.modelActionHolders = Collections.emptyList(); } this.changeActionExecutionTimeMs = passedMs(startTimeNs); this.transactionStep = TransactionStep.ChangeActionCompleted; } ); changeActionSubscriber.ifPresent(subscriber -> subscriber.add(changeActionSubscription)); } @Override public void close() { this.changeActionSubscription.unsubscribe(); this.transactionStep = TransactionStep.SubscribersCompleted; } @Override public boolean isClosed() { return transactionStep == TransactionStep.SubscribersCompleted; } @Override public Optional<ModelHolder> applyModelUpdates(ModelHolder modelHolder) { if (transactionStep != TransactionStep.ChangeActionCompleted) { return Optional.empty(); } this.transactionStep = TransactionStep.ModelsUpdated; if (modelActionHolders.isEmpty()) { return Optional.empty(); } EntityHolder referenceRootHolder = modelHolder.getReference(); EntityHolder runningRootHolder = modelHolder.getRunning(); EntityHolder storeRootHolder = modelHolder.getStore(); try { for (ModelActionHolder updateAction : modelActionHolders) { switch (updateAction.getModel()) { case Reference: referenceRootHolder = applyModelUpdate(updateAction, referenceRootHolder).orElse(referenceRootHolder); break; case Running: runningRootHolder = applyModelUpdate(updateAction, runningRootHolder).orElse(runningRootHolder); break; case Store: storeRootHolder = applyModelUpdate(updateAction, storeRootHolder).orElse(storeRootHolder); break; } } } catch (Exception e) { String message = String.format("Change action failure during model update for %s (%s)", referenceRootHolder.getId(), e.toString()); logger.warn(message, e); engine.getTitusRuntime().getCodeInvariants().unexpectedError(message, e); this.changeActionError = e; this.transactionStep = TransactionStep.ChangeActionFailed; return Optional.empty(); } return Optional.of(new ModelHolder(referenceRootHolder, runningRootHolder, storeRootHolder)); } @Override public void emitEvents() { if (transactionStep == TransactionStep.ModelsUpdated) { modelEventQueue.forEach(this::emitEvent); emitEvent(eventFactory.newAfterChangeEvent(engine, changeAction, changeActionWaitTimeMs, changeActionExecutionTimeMs, transactionId)); this.transactionStep = TransactionStep.EventsEmitted; } else if (transactionStep == TransactionStep.ChangeActionFailed) { emitEvent(eventFactory.newChangeErrorEvent(engine, changeAction, changeActionError, changeActionWaitTimeMs, changeActionExecutionTimeMs, transactionId)); this.transactionStep = TransactionStep.ErrorEventsEmitted; } } @Override public boolean completeSubscribers() { if (transactionStep == TransactionStep.EventsEmitted) { try { changeActionSubscriber.ifPresent(Observer::onCompleted); } catch (Exception e) { logger.warn("Client subscriber onCompleted handler threw an exception: rootId={}, transactionId={}, error={}", engine.getRunningView().getId(), transactionId, e.getMessage()); } this.transactionStep = TransactionStep.SubscribersCompleted; return true; } else if (transactionStep == TransactionStep.ErrorEventsEmitted) { try { changeActionSubscriber.ifPresent(subscriber -> subscriber.onError(changeActionError)); } catch (Exception e) { logger.warn("Client subscriber onError handler threw an exception: rootId={}, transactionId={}, error={}", engine.getRunningView().getId(), transactionId, e.getMessage()); } this.transactionStep = TransactionStep.SubscribersCompleted; return true; } else if (transactionStep == TransactionStep.ChangeActionUnsubscribed) { this.transactionStep = TransactionStep.SubscribersCompleted; return true; } return false; } private Optional<EntityHolder> applyModelUpdate(ModelActionHolder updateAction, EntityHolder rootHolder) { ReconcileEventFactory<EVENT> eventFactory = engine.getEventFactory(); try { return updateAction.getAction().apply(rootHolder).map(newRootAndChangedItem -> { EntityHolder newRoot = newRootAndChangedItem.getLeft(); EntityHolder changedItem = newRootAndChangedItem.getRight(); Optional<EntityHolder> previousHolder = rootHolder.findById(changedItem.getId()); modelEventQueue.add(eventFactory.newModelUpdateEvent(engine, changeAction, updateAction, changedItem, previousHolder, transactionId)); return newRoot; }); } catch (Exception e) { modelEventQueue.add(eventFactory.newModelUpdateErrorEvent(engine, changeAction, updateAction, rootHolder, e, transactionId)); logger.warn("Failed to update state of {} ({})", rootHolder.getId(), e.toString()); throw e; } } private void emitEvent(EVENT event) { long startTimeNs = clock.nanoTime(); try { eventSubject.onNext(event); metrics.emittedEvent(event, clock.nanoTime() - startTimeNs); } catch (Exception e) { metrics.emittedEvent(event, clock.nanoTime() - startTimeNs, e); logger.error("Bad subscriber", e); } } private long passedMs(long startTimeNs) { return TimeUnit.NANOSECONDS.toMillis(clock.nanoTime() - startTimeNs); } }
936
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/DefaultReconciliationEngine.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import com.netflix.spectator.api.Tag; import com.netflix.titus.common.framework.reconciler.ChangeAction; import com.netflix.titus.common.framework.reconciler.EntityHolder; import com.netflix.titus.common.framework.reconciler.ReconcileEventFactory; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.rx.ObservableExt; import com.netflix.titus.common.util.time.Clock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import rx.subjects.PublishSubject; public class DefaultReconciliationEngine<EVENT> implements InternalReconciliationEngine<EVENT> { private static final Logger logger = LoggerFactory.getLogger(DefaultReconciliationEngine.class); private final AtomicLong nextTransactionId = new AtomicLong(); private final DifferenceResolver<EVENT> runningDifferenceResolver; private final ReconcileEventFactory<EVENT> eventFactory; private volatile ModelHolder modelHolder; private final BlockingQueue<EVENT> changeActionEventQueue = new LinkedBlockingQueue<>(); private final BlockingQueue<ChangeActionHolder> referenceChangeActions = new LinkedBlockingQueue<>(); private final ReconciliationEngineMetrics<EVENT> metrics; private final TitusRuntime titusRuntime; private final Clock clock; private IndexSet<EntityHolder> indexSet; private Transaction pendingTransaction = EmptyTransaction.EMPTY; private final PublishSubject<EVENT> eventSubject = PublishSubject.create(); private final Observable<EVENT> eventObservable; private boolean firstTrigger; public DefaultReconciliationEngine(EntityHolder bootstrapModel, boolean newlyCreated, DifferenceResolver<EVENT> runningDifferenceResolver, Map<Object, Comparator<EntityHolder>> indexComparators, ReconcileEventFactory<EVENT> eventFactory, Function<ChangeAction, List<Tag>> extraChangeActionTags, Function<EVENT, List<Tag>> extraModelActionTags, TitusRuntime titusRuntime) { this.runningDifferenceResolver = runningDifferenceResolver; this.eventFactory = eventFactory; this.indexSet = IndexSet.newIndexSet(indexComparators); this.titusRuntime = titusRuntime; this.clock = titusRuntime.getClock(); this.eventObservable = ObservableExt.protectFromMissingExceptionHandlers(eventSubject, logger); this.modelHolder = new ModelHolder(bootstrapModel, bootstrapModel, bootstrapModel); this.firstTrigger = newlyCreated; this.metrics = new ReconciliationEngineMetrics<>(extraChangeActionTags, extraModelActionTags, titusRuntime.getRegistry(), clock); indexEntityHolder(bootstrapModel); } @Override public boolean applyModelUpdates() { return pendingTransaction.applyModelUpdates(modelHolder) .map(newModelHolder -> { boolean isReferenceModelChanged = newModelHolder != modelHolder && newModelHolder.getReference() != modelHolder.getReference(); this.modelHolder = newModelHolder; if (isReferenceModelChanged) { indexEntityHolder(modelHolder.getReference()); } return isReferenceModelChanged; }) .orElse(false); } @Override public boolean hasPendingTransactions() { return !pendingTransaction.isClosed() || !referenceChangeActions.isEmpty(); } @Override public void emitEvents() { /* We need to emit first holder state after initialization, but we can do this only after {@link ReconcileEventFactory} has a chance to subscribe. Alternatively we could shift the logic to {@link ReconcileEventFactory}, but this would create two sources of events for an engine. */ if (firstTrigger) { firstTrigger = false; emitEvent(eventFactory.newModelEvent(this, modelHolder.getReference())); } if (!changeActionEventQueue.isEmpty()) { List<EVENT> eventsToEmit = new ArrayList<>(); changeActionEventQueue.drainTo(eventsToEmit); eventsToEmit.forEach(this::emitEvent); } pendingTransaction.emitEvents(); } @Override public boolean closeFinishedTransactions() { return pendingTransaction.completeSubscribers(); } @Override public boolean triggerActions() { if (!pendingTransaction.isClosed()) { return true; } long startTimeNs = clock.nanoTime(); try { // Start next reference change action, if present and exit. if (startNextReferenceChangeAction()) { return true; } // Compute the current difference between the reference and persistent/runtime models, and create a list // of actions to correct that. The returned action set can be run in parallel. List<ChangeAction> reconcileActions = runningDifferenceResolver.apply(this); if (!reconcileActions.isEmpty()) { startReconcileAction(reconcileActions); return true; } return false; } catch (Exception e) { metrics.evaluated(clock.nanoTime() - startTimeNs, e); titusRuntime.getCodeInvariants().unexpectedError("Unexpected error in ReconciliationEngine", e); return true; } finally { metrics.evaluated(clock.nanoTime() - startTimeNs); } } @Override public Observable<Void> changeReferenceModel(ChangeAction referenceUpdate) { return changeReferenceModel(referenceUpdate, modelHolder.getReference().getId()); } @Override public Observable<Void> changeReferenceModel(ChangeAction referenceUpdate, String entityHolderId) { return Observable.unsafeCreate(subscriber -> { String transactionId = Long.toString(nextTransactionId.getAndIncrement()); changeActionEventQueue.add(eventFactory.newBeforeChangeEvent(this, referenceUpdate, transactionId)); referenceChangeActions.add(new ChangeActionHolder(entityHolderId, referenceUpdate, subscriber, transactionId, clock.wallTime())); metrics.updateChangeActionQueueSize(referenceChangeActions.size()); }); } @Override public EntityHolder getReferenceView() { return modelHolder.getReference(); } @Override public EntityHolder getRunningView() { return modelHolder.getRunning(); } @Override public EntityHolder getStoreView() { return modelHolder.getStore(); } @Override public <ORDER_BY> List<EntityHolder> orderedView(ORDER_BY orderingCriteria) { return indexSet.getOrdered(orderingCriteria); } @Override public Observable<EVENT> events() { return eventObservable; } void shutdown() { pendingTransaction.close(); eventSubject.onCompleted(); metrics.shutdown(); } ReconcileEventFactory<EVENT> getEventFactory() { return eventFactory; } PublishSubject<EVENT> getEventSubject() { return eventSubject; } ReconciliationEngineMetrics<EVENT> getMetrics() { return metrics; } TitusRuntime getTitusRuntime() { return titusRuntime; } private boolean startNextReferenceChangeAction() { try { ChangeActionHolder actionHolder; List<Transaction> transactions = new ArrayList<>(); List<EntityHolder> changePoints = new ArrayList<>(); while ((actionHolder = referenceChangeActions.peek()) != null) { // Ignore all unsubscribed actions Subscriber<Void> subscriber = actionHolder.getSubscriber(); if (subscriber.isUnsubscribed()) { referenceChangeActions.poll(); continue; } // Emit errors if the change point (EntityHolder for the action) not found Optional<EntityHolder> changePointOpt = modelHolder.getReference().findById(actionHolder.getEntityHolderId()); if (!changePointOpt.isPresent()) { referenceChangeActions.poll(); transactions.add(new FailedTransaction<>(this, actionHolder, new IllegalStateException("Entity holder not found: id=" + actionHolder.getEntityHolderId()))); continue; } // Check if the current item overlaps with the already taken actions EntityHolder changePoint = changePointOpt.get(); if (!changePoints.isEmpty() && isOverlapping(changePoint, changePoints)) { break; } // Create transaction changePoints.add(changePoint); Transaction transaction; try { transaction = new SingleTransaction<>(this, actionHolder.getChangeAction(), actionHolder.getCreateTimestamp(), Optional.of(actionHolder.getSubscriber()), actionHolder.getTransactionId(), false); } catch (Exception e) { transaction = new FailedTransaction<>(this, actionHolder, e); } transactions.add(transaction); referenceChangeActions.poll(); } if (transactions.isEmpty()) { return false; } pendingTransaction = transactions.size() == 1 ? transactions.get(0) : new CompositeTransaction(transactions); return true; } finally { metrics.updateChangeActionQueueSize(referenceChangeActions.size()); } } private boolean isOverlapping(EntityHolder changePoint, List<EntityHolder> changePoints) { for (EntityHolder next : changePoints) { if (next.findById(changePoint.getId()).isPresent()) { return true; } if (changePoint.findChildById(next.getId()).isPresent()) { return true; } } return false; } private void startReconcileAction(List<ChangeAction> reconcileActions) { long transactionId = nextTransactionId.getAndIncrement(); long nestedId = 0; long now = clock.wallTime(); List<Transaction> transactions = new ArrayList<>(); for (ChangeAction changeAction : reconcileActions) { String compositeTransactionId = reconcileActions.size() == 1 ? Long.toString(transactionId) : transactionId + "." + nestedId; nestedId++; emitEvent(eventFactory.newBeforeChangeEvent(this, changeAction, compositeTransactionId)); transactions.add(new SingleTransaction<>(this, changeAction, now, Optional.empty(), compositeTransactionId, true)); } pendingTransaction = transactions.size() == 1 ? transactions.get(0) : new CompositeTransaction(transactions); } private void indexEntityHolder(EntityHolder entityHolder) { indexSet = indexSet.apply(entityHolder.getChildren()); } void emitEvent(EVENT event) { long startTimeNs = clock.nanoTime(); try { eventSubject.onNext(event); metrics.emittedEvent(event, clock.nanoTime() - startTimeNs); } catch (Exception e) { metrics.emittedEvent(event, clock.nanoTime() - startTimeNs, e); logger.error("Bad subscriber", e); } } }
937
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/IndexSet.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; /** * TODO Optimize. This is expensive and inefficient implementation. */ public class IndexSet<T> { private static final IndexSet<?> EMPTY = new IndexSet<>(Collections.emptyMap()); private final Map<Object, Index<T>> indexes; private IndexSet(Map<Object, Index<T>> indexes) { this.indexes = indexes; } public IndexSet<T> apply(Collection<T> added) { Map<Object, Index<T>> copy = new HashMap<>(); indexes.forEach((k, v) -> copy.put(k, v.apply(added))); return new IndexSet<>(copy); } public List<T> getOrdered(Object indexId) { Index<T> result = indexes.get(indexId); if (result == null) { throw new IllegalArgumentException("Unknown index id " + indexId); } return result.getOrdered(); } public static <T> IndexSet<T> empty() { return (IndexSet<T>) EMPTY; } public static <T> IndexSet<T> newIndexSet(Map<Object, Comparator<T>> comparators) { Map<Object, Index<T>> indexes = new HashMap<>(); comparators.forEach((k, v) -> indexes.put(k, Index.newIndex(v))); return new IndexSet<>(indexes); } static class Index<T> { private final Comparator<T> comparator; private final List<T> ordered; private Index(Comparator<T> comparator, List<T> ordered) { this.comparator = comparator; this.ordered = ordered; } Index<T> apply(Collection<T> added) { List<T> copy = new ArrayList<>(added); copy.sort(comparator); return new Index<>(comparator, copy); } List<T> getOrdered() { return ordered; } static <T> Index<T> newIndex(Comparator<T> comparator) { return new Index<>(comparator, Collections.emptyList()); } } }
938
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/EventDistributor.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.common.framework.reconciler.internal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.base.Preconditions; import com.google.common.base.Stopwatch; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.common.framework.reconciler.ReconcileEventFactory; import com.netflix.titus.common.framework.reconciler.ReconciliationEngine; import com.netflix.titus.common.util.ExceptionExt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Emitter; import rx.Subscription; /** * {@link EventDistributor} takes over event notifications from the internal reconciler stream, and distributes them * to registered stream observers. Events notifications are processed by a dedicated thread. */ class EventDistributor<EVENT> { private static final Logger logger = LoggerFactory.getLogger(EventDistributor.class); private static final String ROOT_METRIC_NAME = DefaultReconciliationFramework.ROOT_METRIC_NAME + "eventDistributor."; private final ReconcileEventFactory<EVENT> eventFactory; private final long checkpointIntervalMs; // This collection is observed by Spectator poller, so we have to use ConcurrentMap. private final ConcurrentMap<String, EngineHolder> engineHolders = new ConcurrentHashMap<>(); private final LinkedBlockingQueue<EmitterHolder> emitterQueue = new LinkedBlockingQueue<>(); private final LinkedBlockingQueue<EVENT> eventQueue = new LinkedBlockingQueue<>(); private final AtomicInteger eventQueueDepth = new AtomicInteger(); // This is modified only by the internal thread. No need to sync. We use map here for fast removal. // This collection is observed by Spectator poller, so we have to use ConcurrentMap. private final ConcurrentMap<String, EmitterHolder> activeEmitters = new ConcurrentHashMap<>(); private volatile Thread eventLoopThread; private volatile boolean shutdown; // Metrics private final Timer metricLoopExecutionTime; private final Counter metricEmittedEvents; EventDistributor(ReconcileEventFactory<EVENT> eventFactory, long checkpointIntervalMs, Registry registry) { this.eventFactory = eventFactory; this.checkpointIntervalMs = checkpointIntervalMs; PolledMeter.using(registry).withName(ROOT_METRIC_NAME + "connectedEngines").monitorSize(engineHolders); this.metricLoopExecutionTime = registry.timer(ROOT_METRIC_NAME + "executionTime"); PolledMeter.using(registry).withName(ROOT_METRIC_NAME + "eventQueue").monitorValue(this, self -> self.eventQueueDepth.get()); PolledMeter.using(registry).withName(ROOT_METRIC_NAME + "activeSubscribers").monitorSize(activeEmitters); this.metricEmittedEvents = registry.counter(ROOT_METRIC_NAME + "emittedEvents"); } void start() { Preconditions.checkState(!shutdown, "Already shutdown"); if (eventLoopThread == null) { this.eventLoopThread = new Thread("event-distributor") { @Override public void run() { doLoop(); } }; eventLoopThread.setDaemon(true); eventLoopThread.start(); } } void stop(long timeoutMs) { this.shutdown = true; if (eventLoopThread != null) { try { eventLoopThread.interrupt(); try { eventLoopThread.join(timeoutMs); } catch (InterruptedException ignore) { } } finally { eventLoopThread = null; } } } void connectEmitter(Emitter<EVENT> emitter) { String id = UUID.randomUUID().toString(); // That really should not be needed, but it does not hurt to check. while (activeEmitters.containsKey(id)) { id = UUID.randomUUID().toString(); } emitterQueue.add(new EmitterHolder(id, emitter)); } // Called only by the reconciliation framework thread. void connectReconciliationEngine(ReconciliationEngine<EVENT> engine) { EngineHolder holder = new EngineHolder(engine); engineHolders.put(holder.getId(), holder); } // Called only by the reconciliation framework thread. void removeReconciliationEngine(ReconciliationEngine<EVENT> engine) { EngineHolder holder = engineHolders.remove(engine.getReferenceView().getId()); if (holder != null) { holder.unsubscribe(); } } private void doLoop() { long keepAliveTimestamp = 0; while (true) { if (shutdown) { completeEmitters(); return; } Stopwatch start = Stopwatch.createStarted(); // Block on the event queue. It is possible that new emitters will be added to the emitterQueue, but we // have to drain them only when there are actually events to send. long checkpointTimestamp = System.nanoTime(); List<EVENT> events = new ArrayList<>(); try { EVENT event = eventQueue.poll(1, TimeUnit.MILLISECONDS); if (event != null) { events.add(event); } } catch (InterruptedException ignore) { } eventQueue.drainTo(events); long now = System.currentTimeMillis(); if (keepAliveTimestamp + checkpointIntervalMs < now) { keepAliveTimestamp = now; events.add(eventFactory.newCheckpointEvent(checkpointTimestamp)); } eventQueueDepth.accumulateAndGet(events.size(), (current, delta) -> current - delta); removeUnsubscribedAndAddNewEmitters(); processEvents(events); metricEmittedEvents.increment(events.size()); metricLoopExecutionTime.record(start.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); } } private void removeUnsubscribedAndAddNewEmitters() { // First remove emitters that Set<String> cancelled = new HashSet<>(); activeEmitters.forEach((id, holder) -> { if (holder.isCancelled()) { cancelled.add(id); } }); activeEmitters.keySet().removeAll(cancelled); // Now add new emitters ArrayList<EmitterHolder> newEmitters = new ArrayList<>(); emitterQueue.drainTo(newEmitters); newEmitters.forEach(holder -> activeEmitters.put(holder.getId(), holder)); } private void processEvents(List<EVENT> events) { events.forEach(event -> { Set<String> cancelled = new HashSet<>(); activeEmitters.forEach((id, holder) -> { if (!holder.onNext(event)) { cancelled.add(id); } }); activeEmitters.keySet().removeAll(cancelled); }); } private void completeEmitters() { removeUnsubscribedAndAddNewEmitters(); Throwable error = new IllegalStateException("Reconciler framework stream closed"); activeEmitters.forEach((id, holder) -> holder.onError(error)); activeEmitters.clear(); } private class EmitterHolder { private final String id; private final Emitter<EVENT> emitter; private volatile boolean cancelled; private EmitterHolder(String id, Emitter<EVENT> emitter) { this.id = id; this.emitter = emitter; emitter.setCancellation(() -> cancelled = true); } private String getId() { return id; } private boolean isCancelled() { return cancelled; } private boolean onNext(EVENT event) { if (cancelled) { return false; } try { emitter.onNext(event); } catch (Throwable e) { ExceptionExt.silent(() -> emitter.onError(e)); this.cancelled = true; return false; } return true; } private void onError(Throwable error) { try { emitter.onError(error); } catch (Throwable ignore) { } finally { cancelled = true; } } } private class EngineHolder { private final ReconciliationEngine<EVENT> engine; private final Subscription subscription; private EngineHolder(ReconciliationEngine<EVENT> engine) { this.engine = engine; this.subscription = engine.events().subscribe( event -> { eventQueue.add(event); eventQueueDepth.incrementAndGet(); }, error -> logger.error("Event stream broken: id={}, error={}", getId(), error.getMessage()), () -> logger.info("Event stream completed: id={}", getId()) ); } private String getId() { return engine.getReferenceView().getId(); } private void unsubscribe() { subscription.unsubscribe(); } } }
939
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/ModelHolder.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import com.netflix.titus.common.framework.reconciler.EntityHolder; /** */ class ModelHolder { private final EntityHolder reference; private final EntityHolder running; private final EntityHolder store; ModelHolder(EntityHolder reference, EntityHolder running, EntityHolder store) { this.reference = reference; this.running = running; this.store = store; } EntityHolder getReference() { return reference; } EntityHolder getStore() { return store; } EntityHolder getRunning() { return running; } }
940
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/DispatchingDifferenceResolver.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.List; import java.util.function.Function; import com.netflix.titus.common.framework.reconciler.ChangeAction; import com.netflix.titus.common.framework.reconciler.EntityHolder; import com.netflix.titus.common.framework.reconciler.ReconciliationEngine; public class DispatchingDifferenceResolver<EVENT> implements ReconciliationEngine.DifferenceResolver<EVENT> { private final Function<EntityHolder, ReconciliationEngine.DifferenceResolver<EVENT>> dispatcherFun; public DispatchingDifferenceResolver(Function<EntityHolder, ReconciliationEngine.DifferenceResolver<EVENT>> dispatcherFun) { this.dispatcherFun = dispatcherFun; } @Override public List<ChangeAction> apply(ReconciliationEngine<EVENT> engine) { return dispatcherFun.apply(engine.getReferenceView()).apply(engine); } }
941
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/ChangeActionHolder.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import com.netflix.titus.common.framework.reconciler.ChangeAction; import rx.Subscriber; final class ChangeActionHolder { private final String entityHolderId; private final ChangeAction changeAction; private final Subscriber subscriber; private final String transactionId; private final long createTimestamp; ChangeActionHolder(String entityHolderId, ChangeAction changeAction, Subscriber subscriber, String transactionId, long createTimestamp) { this.entityHolderId = entityHolderId; this.changeAction = changeAction; this.subscriber = subscriber; this.transactionId = transactionId; this.createTimestamp = createTimestamp; } public String getEntityHolderId() { return entityHolderId; } ChangeAction getChangeAction() { return changeAction; } Subscriber<Void> getSubscriber() { return subscriber; } String getTransactionId() { return transactionId; } long getCreateTimestamp() { return createTimestamp; } }
942
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/DefaultReconciliationFramework.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; 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.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import com.google.common.base.Preconditions; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.common.framework.reconciler.ChangeAction; import com.netflix.titus.common.framework.reconciler.EntityHolder; import com.netflix.titus.common.framework.reconciler.ModelActionHolder; import com.netflix.titus.common.framework.reconciler.MultiEngineChangeAction; import com.netflix.titus.common.framework.reconciler.ReconcileEventFactory; import com.netflix.titus.common.framework.reconciler.ReconciliationEngine; import com.netflix.titus.common.framework.reconciler.ReconciliationFramework; import com.netflix.titus.common.util.ExceptionExt; import com.netflix.titus.common.util.rx.ObservableExt; import com.netflix.titus.common.util.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; import rx.Emitter; import rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.Subscription; import rx.schedulers.Schedulers; public class DefaultReconciliationFramework<EVENT> implements ReconciliationFramework<EVENT> { private static final Logger logger = LoggerFactory.getLogger(DefaultReconciliationFramework.class); static final String ROOT_METRIC_NAME = "titus.reconciliation.framework."; private static final String LOOP_EXECUTION_TIME_METRIC = ROOT_METRIC_NAME + "executionTime"; private static final String LAST_EXECUTION_TIME_METRIC = ROOT_METRIC_NAME + "lastExecutionTime"; private static final String LAST_FULL_CYCLE_EXECUTION_TIME_METRIC = ROOT_METRIC_NAME + "lastFullCycleExecutionTime"; private final Function<EntityHolder, InternalReconciliationEngine<EVENT>> engineFactory; private final long idleTimeoutMs; private final long activeTimeoutMs; private final ExecutorService executor; private final Scheduler scheduler; private final Set<InternalReconciliationEngine<EVENT>> engines = Collections.newSetFromMap(new ConcurrentHashMap<>()); private final BlockingQueue<Pair<InternalReconciliationEngine<EVENT>, Subscriber<ReconciliationEngine>>> enginesAdded = new LinkedBlockingQueue<>(); private final BlockingQueue<Pair<InternalReconciliationEngine<EVENT>, Subscriber<Void>>> enginesToRemove = new LinkedBlockingQueue<>(); private final AtomicReference<Map<String, InternalReconciliationEngine<EVENT>>> idToEngineMapRef = new AtomicReference<>(Collections.emptyMap()); private IndexSet<EntityHolder> indexSet; private final Scheduler.Worker worker; private volatile boolean runnable = true; private volatile boolean started = false; private final EventDistributor<EVENT> eventDistributor; private final Timer loopExecutionTime; private volatile long lastFullCycleExecutionTimeMs; // Probed by a polled meter. private volatile long lastExecutionTimeMs; // Probed by a polled meter. private final Object multiEngineChangeLock = new Object(); public DefaultReconciliationFramework(List<InternalReconciliationEngine<EVENT>> bootstrapEngines, Function<EntityHolder, InternalReconciliationEngine<EVENT>> engineFactory, long idleTimeoutMs, long activeTimeoutMs, long checkpointIntervalMs, Map<Object, Comparator<EntityHolder>> indexComparators, ReconcileEventFactory<EVENT> eventFactory, Registry registry, Optional<Scheduler> optionalScheduler) { Preconditions.checkArgument(idleTimeoutMs > 0, "idleTimeout <= 0 (%s)", idleTimeoutMs); Preconditions.checkArgument(activeTimeoutMs <= idleTimeoutMs, "activeTimeout(%s) > idleTimeout(%s)", activeTimeoutMs, idleTimeoutMs); this.engineFactory = engineFactory; this.indexSet = IndexSet.newIndexSet(indexComparators); this.idleTimeoutMs = idleTimeoutMs; this.activeTimeoutMs = activeTimeoutMs; if (optionalScheduler.isPresent()) { this.scheduler = optionalScheduler.get(); this.executor = null; } else { this.executor = Executors.newSingleThreadExecutor(runnable -> { Thread thread = new Thread(runnable, "TitusReconciliationFramework"); thread.setDaemon(true); return thread; }); this.scheduler = Schedulers.from(executor); } this.worker = scheduler.createWorker(); this.eventDistributor = new EventDistributor<>(eventFactory, checkpointIntervalMs, registry); this.loopExecutionTime = registry.timer(LOOP_EXECUTION_TIME_METRIC); this.lastFullCycleExecutionTimeMs = scheduler.now() - idleTimeoutMs; this.lastExecutionTimeMs = scheduler.now(); PolledMeter.using(registry).withName(LAST_EXECUTION_TIME_METRIC).monitorValue(this, self -> scheduler.now() - self.lastExecutionTimeMs); PolledMeter.using(registry).withName(LAST_FULL_CYCLE_EXECUTION_TIME_METRIC).monitorValue(this, self -> scheduler.now() - self.lastFullCycleExecutionTimeMs); engines.addAll(bootstrapEngines); bootstrapEngines.forEach(eventDistributor::connectReconciliationEngine); updateIndexSet(); } @Override public void start() { Preconditions.checkArgument(!started, "Framework already started"); eventDistributor.start(); started = true; doSchedule(0); } @Override public boolean stop(long timeoutMs) { runnable = false; // In the test code when we use the TestScheduler we would always block here. One way to solve this is to return // Completable as a result, but this makes the API inconvenient. Instead we chose to look at the worker type, // and handle this differently for TestScheduler. if (worker.getClass().getName().contains("TestScheduler")) { stopEngines(); return true; } // Run this on internal thread, just like other actions. CountDownLatch latch = new CountDownLatch(1); worker.schedule(() -> { stopEngines(); latch.countDown(); }); ExceptionExt.silent(() -> latch.await(timeoutMs, TimeUnit.MILLISECONDS)); eventDistributor.stop(timeoutMs); if (executor != null) { executor.shutdownNow(); } return latch.getCount() == 0; } private void stopEngines() { engines.forEach(e -> { if (e instanceof DefaultReconciliationEngine) { ((DefaultReconciliationEngine) e).shutdown(); } }); engines.clear(); } @Override public Observable<ReconciliationEngine<EVENT>> newEngine(EntityHolder bootstrapModel) { return Observable.unsafeCreate(subscriber -> { if (!runnable) { subscriber.onError(new IllegalStateException("Reconciliation engine is stopped")); return; } InternalReconciliationEngine newEngine = engineFactory.apply(bootstrapModel); enginesAdded.add(Pair.of(newEngine, (Subscriber<ReconciliationEngine>) subscriber)); }); } @Override public Completable removeEngine(ReconciliationEngine engine) { Preconditions.checkArgument(engine instanceof InternalReconciliationEngine, "Unexpected ReconciliationEngine implementation"); return Observable.<Void>unsafeCreate(subscriber -> { if (!runnable) { subscriber.onError(new IllegalStateException("Reconciliation engine is stopped")); return; } enginesToRemove.add(Pair.of((InternalReconciliationEngine<EVENT>) engine, (Subscriber<Void>) subscriber)); }).toCompletable(); } @Override public Observable<Void> changeReferenceModel(MultiEngineChangeAction multiEngineChangeAction, BiFunction<String, Observable<List<ModelActionHolder>>, ChangeAction> engineChangeActionFactory, String... rootEntityHolderIds) { Preconditions.checkArgument(rootEntityHolderIds.length > 1, "Change action for multiple engines requested, but %s root id holders provided", rootEntityHolderIds.length ); return Observable.create(emitter -> { List<ReconciliationEngine<EVENT>> engines = new ArrayList<>(); for (String id : rootEntityHolderIds) { ReconciliationEngine<EVENT> engine = findEngineByRootId(id).orElseThrow(() -> new IllegalArgumentException("Reconciliation engine not found: rootId=" + id)); engines.add(engine); } List<Observable<Map<String, List<ModelActionHolder>>>> outputs = ObservableExt.propagate(multiEngineChangeAction.apply(), engines.size()); List<Observable<Void>> engineActions = new ArrayList<>(); for (int i = 0; i < engines.size(); i++) { ReconciliationEngine<EVENT> engine = engines.get(i); String rootId = engine.getReferenceView().getId(); ChangeAction engineAction = engineChangeActionFactory.apply(rootId, outputs.get(i).map(r -> r.get(rootId))); engineActions.add(engine.changeReferenceModel(engineAction)); } // Synchronize on subscription to make sure that this operation is not interleaved with concurrent // subscriptions for the same set or subset of the reconciliation engines. The interleaving might result // in a deadlock. For example with two engines engineA and engineB: // - multi-engine change action M1 for engineA and engineB is scheduled // - M1/engineA is added to its queue // - another multi-engine change action M2 for engineA and engineB is scheduled // - M2/engineB is added to its queue // - M1/engineB is added to its queue, and next M2/engineA // Executing M1 requires that both M1/engineA and M1/engineB are at the top of the queue, but in this case // M2/engineB is ahead of the M1/engineB. On the other hand, M1/engineA is ahead of M2/engineB. Because // of that we have deadlock. Please, note that we can ignore here the regular (engine scoped) change actions. Subscription subscription; synchronized (multiEngineChangeLock) { subscription = Observable.mergeDelayError(engineActions).subscribe( emitter::onNext, emitter::onError, emitter::onCompleted ); } emitter.setSubscription(subscription); }, Emitter.BackpressureMode.NONE); } @Override public Observable<EVENT> events() { return Observable.create(eventDistributor::connectEmitter, Emitter.BackpressureMode.ERROR); } @Override public Optional<ReconciliationEngine<EVENT>> findEngineByRootId(String id) { InternalReconciliationEngine<EVENT> engine = idToEngineMapRef.get().get(id); if (engine == null) { return Optional.empty(); } return engine.getReferenceView().getId().equals(id) ? Optional.of(engine) : Optional.empty(); } @Override public Optional<Pair<ReconciliationEngine<EVENT>, EntityHolder>> findEngineByChildId(String childId) { InternalReconciliationEngine<EVENT> engine = idToEngineMapRef.get().get(childId); if (engine == null) { return Optional.empty(); } EntityHolder rootHolder = engine.getReferenceView(); if (rootHolder.getId().equals(childId)) { return Optional.empty(); } return rootHolder.findChildById(childId).map(c -> Pair.of(engine, c)); } @Override public <ORDER_BY> List<EntityHolder> orderedView(ORDER_BY orderingCriteria) { return indexSet.getOrdered(orderingCriteria); } private void doSchedule(long delayMs) { if (!runnable) { return; } worker.schedule(() -> { long startTimeMs = worker.now(); try { boolean fullCycle = (startTimeMs - lastFullCycleExecutionTimeMs) >= idleTimeoutMs; if (fullCycle) { lastFullCycleExecutionTimeMs = startTimeMs; } doLoop(fullCycle); doSchedule(activeTimeoutMs); } catch (Exception e) { logger.warn("Unexpected error in the reconciliation loop", e); doSchedule(idleTimeoutMs); } finally { long now = worker.now(); lastExecutionTimeMs = now; loopExecutionTime.record(now - startTimeMs, TimeUnit.MILLISECONDS); } }, delayMs, TimeUnit.MILLISECONDS); } private void doLoop(boolean fullReconciliationCycle) { Set<InternalReconciliationEngine<EVENT>> mustRunEngines = new HashSet<>(); // Apply pending model updates/send events boolean modelUpdates = false; for (InternalReconciliationEngine engine : engines) { try { boolean anyChange = engine.applyModelUpdates(); modelUpdates = modelUpdates || anyChange; } catch (Exception e) { logger.warn("Unexpected error from reconciliation engine 'applyModelUpdates' method", e); } } // Add new engines. List<Pair<InternalReconciliationEngine<EVENT>, Subscriber<ReconciliationEngine>>> recentlyAdded = new ArrayList<>(); enginesAdded.drainTo(recentlyAdded); recentlyAdded.forEach(pair -> { InternalReconciliationEngine<EVENT> newEngine = pair.getLeft(); engines.add(newEngine); mustRunEngines.add(newEngine); eventDistributor.connectReconciliationEngine(newEngine); }); // Remove engines. List<Pair<InternalReconciliationEngine<EVENT>, Subscriber<Void>>> recentlyRemoved = new ArrayList<>(); enginesToRemove.drainTo(recentlyRemoved); shutdownEnginesToRemove(recentlyRemoved); boolean engineSetUpdate = !recentlyAdded.isEmpty() || !recentlyRemoved.isEmpty(); // Update indexes if there are model changes. if (modelUpdates || engineSetUpdate) { updateIndexSet(); } // Complete engine add/remove subscribers. // We want to complete the subscribers that create new engines, before the first event is emitted. // Otherwise the initial event would be emitted immediately, before the subscriber has a chance to subscriber to the event stream. recentlyAdded.forEach(pair -> { Subscriber<ReconciliationEngine> subscriber = pair.getRight(); if (!subscriber.isUnsubscribed()) { subscriber.onNext(pair.getLeft()); subscriber.onCompleted(); } }); recentlyRemoved.forEach(pair -> pair.getRight().onCompleted()); // Emit events for (InternalReconciliationEngine engine : engines) { try { engine.emitEvents(); } catch (Exception e) { logger.warn("Unexpected error from reconciliation engine 'emitEvents' method", e); } } // Complete ChangeAction subscribers for (InternalReconciliationEngine<EVENT> engine : engines) { try { if (engine.closeFinishedTransactions()) { mustRunEngines.add(engine); } } catch (Exception e) { logger.warn("Unexpected error from reconciliation engine 'closeFinishedTransactions' method", e); } } // Trigger actions on engines. for (InternalReconciliationEngine engine : engines) { if (fullReconciliationCycle || engine.hasPendingTransactions() || mustRunEngines.contains(engine)) { try { engine.triggerActions(); } catch (Exception e) { logger.warn("Unexpected error from reconciliation engine 'triggerActions' method", e); } } } } private void shutdownEnginesToRemove(List<Pair<InternalReconciliationEngine<EVENT>, Subscriber<Void>>> toRemove) { toRemove.forEach(pair -> { InternalReconciliationEngine e = pair.getLeft(); if (e instanceof DefaultReconciliationEngine) { ((DefaultReconciliationEngine) e).shutdown(); } engines.remove(e); eventDistributor.removeReconciliationEngine(e); }); } private void updateIndexSet() { Map<String, InternalReconciliationEngine<EVENT>> idToEngineMap = new HashMap<>(); engines.forEach(engine -> engine.getReferenceView().visit(h -> idToEngineMap.put(h.getId(), engine))); this.idToEngineMapRef.set(idToEngineMap); indexSet = indexSet.apply(engines.stream().map(ReconciliationEngine::getReferenceView).collect(Collectors.toList())); } }
943
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/ReconciliationEngineMetrics.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Tag; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.common.framework.reconciler.ChangeAction; import com.netflix.titus.common.util.time.Clock; class ReconciliationEngineMetrics<EVENT> { private static final String ROOT_NAME = "titus.reconciliation.engine."; private static final String EVALUATIONS = ROOT_NAME + "evaluations"; private static final String PENDING_CHANGE_ACTIONS = ROOT_NAME + "pendingChangeActions"; private static final String STARTED_CHANGE_ACTIONS = ROOT_NAME + "startedChangeActions"; private static final String FINISHED_CHANGE_ACTIONS = ROOT_NAME + "finishedChangeActions"; private static final String EMITTED_EVENTS = ROOT_NAME + "emittedEvents"; private final Function<ChangeAction, List<Tag>> extraChangeActionTags; private final Function<EVENT, List<Tag>> extraModelActionTags; private final Registry registry; private final Clock clock; private final Id evaluationId; private final Id startedChangeActionsId; private final Id finishedChangeActionId; private final Id emittedEventId; private final AtomicLong pendingChangeActions = new AtomicLong(); private final Gauge changeActionQueueSize; ReconciliationEngineMetrics(Function<ChangeAction, List<Tag>> extraChangeActionTags, Function<EVENT, List<Tag>> extraModelActionTags, Registry registry, Clock clock) { this.extraChangeActionTags = extraChangeActionTags; this.extraModelActionTags = extraModelActionTags; this.registry = registry; this.clock = clock; List<Tag> commonTags = Collections.emptyList(); this.evaluationId = registry.createId(EVALUATIONS, commonTags); this.startedChangeActionsId = registry.createId(STARTED_CHANGE_ACTIONS, commonTags); this.finishedChangeActionId = registry.createId(FINISHED_CHANGE_ACTIONS, commonTags); this.emittedEventId = registry.createId(EMITTED_EVENTS, commonTags); this.changeActionQueueSize = registry.gauge(registry.createId(ROOT_NAME + "changeActionQueueSize", commonTags)); PolledMeter.using(registry).withName(PENDING_CHANGE_ACTIONS).withTags(commonTags).monitorValue(pendingChangeActions); } void shutdown() { changeActionQueueSize.set(0); pendingChangeActions.set(0); } void evaluated(long executionTimeNs) { registry.timer(evaluationId).record(executionTimeNs, TimeUnit.NANOSECONDS); } void evaluated(long executionTimeNs, Exception error) { registry.timer(evaluationId.withTag("error", error.getClass().getSimpleName())).record(executionTimeNs, TimeUnit.NANOSECONDS); } void updateChangeActionQueueSize(int queueSize) { changeActionQueueSize.set(queueSize); } void changeActionStarted(ChangeAction actionHolder, long createTimeMs, boolean byReconciler) { pendingChangeActions.incrementAndGet(); registry.timer(startedChangeActionsId .withTags(extraChangeActionTags.apply(actionHolder)) .withTag("actionType", toActionType(byReconciler)) ).record(clock.wallTime() - createTimeMs, TimeUnit.MILLISECONDS); } void changeActionFinished(ChangeAction actionHolder, long executionTimeNs, boolean byReconciler) { changeActionFinished(actionHolder, executionTimeNs, false, byReconciler); } void changeActionUnsubscribed(ChangeAction actionHolder, long executionTimeNs, boolean byReconciler) { changeActionFinished(actionHolder, executionTimeNs, true, byReconciler); } void changeActionFinished(ChangeAction actionHolder, long executionTimeNs, Throwable error, boolean byReconciler) { pendingChangeActions.decrementAndGet(); registry.timer(finishedChangeActionId .withTags(extraChangeActionTags.apply(actionHolder)) .withTag("actionType", toActionType(byReconciler)) .withTag("error", error.getClass().getSimpleName()) .withTag("status", "error") ).record(executionTimeNs, TimeUnit.NANOSECONDS); } void emittedEvent(EVENT event, long latencyNs) { registry.timer(emittedEventId .withTags(extraModelActionTags.apply(event)) .withTag("status", "success") ).record(latencyNs, TimeUnit.NANOSECONDS); } void emittedEvent(EVENT event, long latencyNs, Exception error) { registry.timer(emittedEventId .withTags(extraModelActionTags.apply(event)) .withTag("error", error.getClass().getSimpleName()) .withTag("status", "error") ).record(latencyNs, TimeUnit.NANOSECONDS); } private void changeActionFinished(ChangeAction actionHolder, long executionTimeNs, boolean isUnsubscribe, boolean byReconciler) { pendingChangeActions.decrementAndGet(); registry.timer(finishedChangeActionId .withTags(extraChangeActionTags.apply(actionHolder)) .withTag("actionType", toActionType(byReconciler)) .withTag("status", isUnsubscribe ? "unsubscribed" : "success") ).record(executionTimeNs, TimeUnit.NANOSECONDS); } private String toActionType(boolean byReconciler) { return byReconciler ? "reconcile" : "change"; } }
944
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/CompositeTransaction.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.List; import java.util.Optional; class CompositeTransaction implements Transaction { private final List<Transaction> transactions; CompositeTransaction(List<Transaction> transactions) { this.transactions = transactions; } @Override public void close() { transactions.forEach(Transaction::close); } @Override public boolean isClosed() { for (Transaction transaction : transactions) { if (!transaction.isClosed()) { return false; } } return true; } @Override public Optional<ModelHolder> applyModelUpdates(ModelHolder modelHolder) { ModelHolder currentModelHolder = modelHolder; for (Transaction transaction : transactions) { currentModelHolder = transaction.applyModelUpdates(currentModelHolder).orElse(currentModelHolder); } return currentModelHolder == modelHolder ? Optional.empty() : Optional.of(currentModelHolder); } @Override public void emitEvents() { transactions.forEach(Transaction::emitEvents); } @Override public boolean completeSubscribers() { boolean anyChange = false; for (Transaction transaction : transactions) { anyChange = transaction.completeSubscribers() | anyChange; } return anyChange; } }
945
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/EmptyTransaction.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.Optional; class EmptyTransaction implements Transaction { static final Transaction EMPTY = new EmptyTransaction(); @Override public void close() { } @Override public boolean isClosed() { return true; } @Override public Optional<ModelHolder> applyModelUpdates(ModelHolder modelHolder) { return Optional.empty(); } @Override public void emitEvents() { } @Override public boolean completeSubscribers() { return false; } }
946
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/FailedTransaction.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class FailedTransaction<EVENT> implements Transaction { private static final Logger logger = LoggerFactory.getLogger(FailedTransaction.class); enum TransactionStep { ChangeActionFailed, ErrorEventsEmitted, SubscribersCompleted } private final DefaultReconciliationEngine<EVENT> engine; private final ChangeActionHolder changeActionHolder; private final Throwable error; private TransactionStep transactionStep = TransactionStep.ChangeActionFailed; FailedTransaction(DefaultReconciliationEngine<EVENT> engine, ChangeActionHolder changeActionHolder, Throwable error) { this.engine = engine; this.changeActionHolder = changeActionHolder; this.error = error; } @Override public void close() { changeActionHolder.getSubscriber().unsubscribe(); this.transactionStep = TransactionStep.SubscribersCompleted; } @Override public boolean isClosed() { return transactionStep == TransactionStep.SubscribersCompleted; } @Override public Optional<ModelHolder> applyModelUpdates(ModelHolder modelHolder) { return Optional.empty(); } @Override public void emitEvents() { if (transactionStep == TransactionStep.ChangeActionFailed) { this.transactionStep = TransactionStep.ErrorEventsEmitted; long now = engine.getTitusRuntime().getClock().wallTime(); EVENT event = engine.getEventFactory().newChangeErrorEvent(engine, changeActionHolder.getChangeAction(), error, now - changeActionHolder.getCreateTimestamp(), 0, changeActionHolder.getTransactionId()); engine.emitEvent(event); } } @Override public boolean completeSubscribers() { if (transactionStep == TransactionStep.ErrorEventsEmitted) { this.transactionStep = TransactionStep.SubscribersCompleted; try { changeActionHolder.getSubscriber().onError(error); } catch (Exception e) { logger.warn("Client subscriber onError handler threw an exception: rootId={}, error={}", engine.getRunningView().getId(), e.getMessage()); } return true; } return false; } }
947
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/reconciler/internal/Transaction.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.reconciler.internal; import java.util.Optional; interface Transaction { void close(); boolean isClosed(); Optional<ModelHolder> applyModelUpdates(ModelHolder modelHolder); void emitEvents(); boolean completeSubscribers(); }
948
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/EndpointResolver.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http; public interface EndpointResolver { /** * Returns a string that represents an endpoint. Expect an exception to be throw if the implementation is * unable to provide the endpoint. * * @return the endpoint string */ String resolve(); }
949
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/RxHttpClient.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http; import rx.Observable; public interface RxHttpClient { Observable<Response> execute(Request request); Observable<Response> get(String url); Observable<Response> head(String url); Observable<Response> post(String url, Object entity); Observable<Response> delete(String url); Observable<Response> delete(String url, Object entity); Observable<Response> put(String url, Object entity); Observable<Response> patch(String url, Object entity); }
950
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/Response.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http; public class Response { private Request request; private Headers headers; private StatusCode statusCode; private ResponseBody body; private long sentRequestAtMillis; private long receivedResponseAtMillis; Response(Builder builder) { this.request = builder.request; this.headers = builder.headers; this.statusCode = builder.statusCode; this.body = builder.body; this.sentRequestAtMillis = builder.sentRequestAtMillis; this.receivedResponseAtMillis = builder.receivedResponseAtMillis; } public Request getRequest() { return request; } public String getHeader(String name) { return headers.get(name); } public Headers getHeaders() { return headers; } public StatusCode getStatusCode() { return statusCode; } public boolean isSuccessful() { return statusCode.getStatusClass() == StatusCode.StatusClass.SUCCESSFUL; } public boolean hasBody() { return body != null; } public ResponseBody getBody() { return body; } public long getSentRequestAtMillis() { return sentRequestAtMillis; } public long getReceivedResponseAtMillis() { return receivedResponseAtMillis; } public Builder newBuilder() { return new Builder(this); } public static class Builder { Request request; Headers headers; StatusCode statusCode; ResponseBody body; long sentRequestAtMillis; long receivedResponseAtMillis; public Builder() { headers = new Headers(); } Builder(Response response) { this.request = response.getRequest(); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); this.body = response.getBody(); this.sentRequestAtMillis = response.getSentRequestAtMillis(); this.receivedResponseAtMillis = response.getReceivedResponseAtMillis(); } public Builder request(Request request) { this.request = request; return this; } public Builder headers(Headers headers) { this.headers = headers; return this; } public Builder statusCode(StatusCode statusCode) { this.statusCode = statusCode; return this; } public Builder body(ResponseBody body) { this.body = body; return this; } public Builder sentRequestAtMillis(long sentRequestAtMillis) { this.sentRequestAtMillis = sentRequestAtMillis; return this; } public Builder receivedResponseAtMillis(long receivedResponseAtMillis) { this.receivedResponseAtMillis = receivedResponseAtMillis; return this; } public Response build() { return new Response(this); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Response response = (Response) o; if (sentRequestAtMillis != response.sentRequestAtMillis) { return false; } if (receivedResponseAtMillis != response.receivedResponseAtMillis) { return false; } if (request != null ? !request.equals(response.request) : response.request != null) { return false; } if (headers != null ? !headers.equals(response.headers) : response.headers != null) { return false; } if (statusCode != response.statusCode) { return false; } return body != null ? body.equals(response.body) : response.body == null; } @Override public int hashCode() { int result = request != null ? request.hashCode() : 0; result = 31 * result + (headers != null ? headers.hashCode() : 0); result = 31 * result + (statusCode != null ? statusCode.hashCode() : 0); result = 31 * result + (body != null ? body.hashCode() : 0); result = 31 * result + (int) (sentRequestAtMillis ^ (sentRequestAtMillis >>> 32)); result = 31 * result + (int) (receivedResponseAtMillis ^ (receivedResponseAtMillis >>> 32)); return result; } @Override public String toString() { return "Response{" + "request=" + request + ", headers=" + headers + ", statusCode=" + statusCode + ", body=" + body + ", sentRequestAtMillis=" + sentRequestAtMillis + ", receivedResponseAtMillis=" + receivedResponseAtMillis + '}'; } }
951
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/ResponseBody.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http; public abstract class ResponseBody { public abstract <T> T get(Class<T> type); public abstract long getContentLength(); public abstract void close(); }
952
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/Headers.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; public class Headers { Multimap<String, String> delegate; public Headers() { this.delegate = ArrayListMultimap.create(); } public String get(String name) { Collection<String> values = delegate.get(name); if (values.size() > 0) { Iterables.getLast(values); } return null; } public Set<String> names() { return delegate.keySet(); } public List<String> values(String name) { return ImmutableList.copyOf(delegate.get(name)); } public void put(String name, String value) { delegate.put(name, value); } public void set(String name, String value) { set(name, Collections.singletonList(value)); } public void set(String name, List values) { delegate.replaceValues(name, values); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Headers headers1 = (Headers) o; return delegate != null ? delegate.equals(headers1.delegate) : headers1.delegate == null; } @Override public int hashCode() { return delegate != null ? delegate.hashCode() : 0; } @Override public String toString() { return delegate.toString(); } }
953
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/Methods.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http; public class Methods { public static final String GET = "GET"; public static final String HEAD = "HEAD"; public static final String POST = "POST"; public static final String DELETE = "DELETE"; public static final String PUT = "PUT"; public static final String PATCH = "PATCH"; public static final String OPTIONS = "OPTIONS"; public static boolean isBodyAllowed(String method) { return method.equalsIgnoreCase(POST) || method.equalsIgnoreCase(DELETE) || method.equalsIgnoreCase(PUT) || method.equalsIgnoreCase(PATCH); } }
954
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/StatusCode.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http; /** * Commonly used status codes defined by HTTP, see * {@link <a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes">List of Http status codes</a>} * for the complete list. */ public enum StatusCode { /** * 200 OK */ OK(200, "OK", false), /** * 201 Created */ CREATED(201, "Created", false), /** * 202 Accepted */ ACCEPTED(202, "Accepted", false), /** * 204 No Content */ NO_CONTENT(204, "No Content", false), /** * 301 Moved Permanently */ MOVED_PERMANENTLY(301, "Moved Permanently", false), /** * 303 See Other */ SEE_OTHER(303, "See Other", false), /** * 304 Not Modified */ NOT_MODIFIED(304, "Not Modified", false), /** * 307 Temporary Redirect */ TEMPORARY_REDIRECT(307, "Temporary Redirect", false), /** * 400 Bad Request */ BAD_REQUEST(400, "Bad Request", false), /** * 401 Unauthorized */ UNAUTHORIZED(401, "Unauthorized", false), /** * 403 Forbidden */ FORBIDDEN(403, "Forbidden", false), /** * 404 Not Found */ NOT_FOUND(404, "Not Found", false), /** * 406 Not Acceptable */ NOT_ACCEPTABLE(406, "Not Acceptable", false), /** * 409 Conflict */ CONFLICT(409, "Conflict", false), /** * 410 Gone */ GONE(410, "Gone", false), /** * 412 Precondition Failed */ PRECONDITION_FAILED(412, "Precondition Failed", false), /** * 415 Unsupported Media Type */ UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type", false), /** * 429 Too Many Requests */ TOO_MANY_REQUESTS(429, "Too Many Requests", true), /** * 500 Internal Server Error */ INTERNAL_SERVER_ERROR(500, "Internal Server Error", true), /** * 503 Service Unavailable */ SERVICE_UNAVAILABLE(503, "Service Unavailable", true); private final int code; private final String description; private StatusClass statusClass; private boolean retryable; /** * An enumeration representing the class of status code. Family is used * here since class is overloaded in Java. */ public enum StatusClass { INFORMATIONAL, SUCCESSFUL, REDIRECTION, CLIENT_ERROR, SERVER_ERROR, OTHER } StatusCode(final int code, final String description, final boolean retryable) { this.code = code; this.description = description; this.retryable = retryable; switch (code / 100) { case 1: this.statusClass = StatusClass.INFORMATIONAL; break; case 2: this.statusClass = StatusClass.SUCCESSFUL; break; case 3: this.statusClass = StatusClass.REDIRECTION; break; case 4: this.statusClass = StatusClass.CLIENT_ERROR; break; case 5: this.statusClass = StatusClass.SERVER_ERROR; break; default: this.statusClass = StatusClass.OTHER; break; } } /** * Get the class of status code * * @return the class of status code */ public StatusClass getStatusClass() { return statusClass; } /** * Get the associated status code * * @return the status code */ public int getCode() { return code; } /** * Get the description * * @return the description */ public String getDescription() { return description; } /** * Whether or not this status code should be retried * * @return true if this status code should be retried */ public boolean isRetryable() { return retryable; } /** * The string representation * * @return the string representation */ @Override public String toString() { return "[" + code + "] " + description; } /** * Convert a numerical status code into the corresponding Status * * @param code the numerical status code * @return the matching Status or null is no matching Status is defined */ public static StatusCode fromCode(final int code) { for (StatusCode s : StatusCode.values()) { if (s.code == code) { return s; } } return null; } }
955
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/RequestBody.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http; public abstract class RequestBody { public abstract Object get(); public static <T> RequestBody create(T value) { return new RequestBody() { @Override public Object get() { return value; } }; } }
956
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/HttpClient.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http; public interface HttpClient { Response execute(Request request); Response get(String url); Response head(String url); Response post(String url, Object entity); Response delete(String url); Response delete(String url, Object entity); Response put(String url, Object entity); Response patch(String url, Object entity); }
957
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/Request.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http; import java.util.List; public final class Request { private String url; private String method; private Headers headers; private RequestBody body; Request(Builder builder) { this.url = builder.url; this.method = builder.method; this.headers = builder.headers; this.body = builder.body; } public String getUrl() { return url; } public String getMethod() { return method; } public Headers getHeaders() { return headers; } public String getHeader(String name) { return headers.get(name); } public List<String> getHeaders(String name) { return headers.values(name); } public RequestBody getBody() { return body; } public Builder newBuilder() { return new Builder(this); } public static class Builder { String url; String method; Headers headers; RequestBody body; public Builder() { this.method = Methods.GET; this.headers = new Headers(); } public Builder(Request request) { this.url = request.getUrl(); this.method = request.getMethod(); this.headers = request.getHeaders(); this.body = request.getBody(); } public Builder url(String url) { this.url = url; return this; } public Builder method(String method) { this.method = method; return this; } public Builder get() { this.method = Methods.GET; return this; } public Builder head() { this.method = Methods.HEAD; return this; } public Builder post() { this.method = Methods.POST; return this; } public Builder delete() { this.method = Methods.DELETE; return this; } public Builder put() { this.method = Methods.PUT; return this; } public Builder patch() { this.method = Methods.PATCH; return this; } public Builder header(String name, String value) { this.headers.put(name, value); return this; } public Builder headers(Headers headers) { this.headers = headers; return this; } public Builder body(RequestBody body) { this.body = body; return this; } public Request build() { return new Request(this); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Request request = (Request) o; if (url != null ? !url.equals(request.url) : request.url != null) { return false; } if (method != null ? !method.equals(request.method) : request.method != null) { return false; } if (headers != null ? !headers.equals(request.headers) : request.headers != null) { return false; } return body != null ? body.equals(request.body) : request.body == null; } @Override public int hashCode() { int result = url != null ? url.hashCode() : 0; result = 31 * result + (method != null ? method.hashCode() : 0); result = 31 * result + (headers != null ? headers.hashCode() : 0); result = 31 * result + (body != null ? body.hashCode() : 0); return result; } @Override public String toString() { return "Request{" + "url='" + url + '\'' + ", method='" + method + '\'' + ", headers=" + headers + ", body=" + body + '}'; } }
958
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal/RoundRobinEndpointResolver.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http.internal; import java.util.Collections; import java.util.List; import com.netflix.titus.common.network.http.EndpointResolver; public class RoundRobinEndpointResolver implements EndpointResolver { private List<String> endpoints; private volatile int position; public RoundRobinEndpointResolver(String endpoint) { this(Collections.singletonList(endpoint)); } public RoundRobinEndpointResolver(List<String> endpoints) { this.endpoints = endpoints; } @Override public String resolve() { int index = getNextPosition(); return endpoints.get(index); } private int getNextPosition() { if (endpoints.size() <= 1) { return 0; } else { int index = position; position++; if (position >= endpoints.size()) { position = 0; } return index; } } }
959
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal/okhttp/PassthroughInterceptor.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http.internal.okhttp; import java.io.IOException; import okhttp3.Interceptor; public class PassthroughInterceptor implements Interceptor { @Override public okhttp3.Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request()); } }
960
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal/okhttp/OkHttpConverters.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http.internal.okhttp; import java.io.IOException; import java.io.InputStream; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.titus.common.network.http.Headers; import com.netflix.titus.common.network.http.Request; import com.netflix.titus.common.network.http.RequestBody; import com.netflix.titus.common.network.http.Response; import com.netflix.titus.common.network.http.ResponseBody; import com.netflix.titus.common.network.http.StatusCode; import okhttp3.MediaType; import okhttp3.internal.Util; import okio.BufferedSink; import okio.BufferedSource; import okio.Okio; import okio.Source; import static okhttp3.Protocol.HTTP_1_1; class OkHttpConverters { private static ObjectMapper objectMapper = new ObjectMapper(); static okhttp3.Request toOkHttpRequest(Request request) { okhttp3.RequestBody requestBody = request.getBody() == null ? null : toOkHttpRequestBody(request.getBody()); okhttp3.Request.Builder builder = new okhttp3.Request.Builder() .url(request.getUrl()) .method(request.getMethod(), requestBody) .headers(toOkHttpHeaders(request.getHeaders())); return builder.build(); } static Request fromOkHttpRequest(okhttp3.Request request) { Request.Builder builder = new Request.Builder() .url(request.url().toString()) .method(request.method()) .headers(fromOkHttpHeaders(request.headers())); if (request.body() != null) { builder.body(RequestBody.create(request.body())); } return builder.build(); } static okhttp3.Response toOkHttpResponse(Response response) { okhttp3.Response.Builder builder = new okhttp3.Response.Builder() .code(response.getStatusCode().getCode()) .headers(toOkHttpHeaders(response.getHeaders())) .protocol(HTTP_1_1); if (response.getRequest() != null) { builder.request(toOkHttpRequest(response.getRequest())); } if (response.hasBody()) { builder.body(toOkHttpResponseBody(response.getBody())); } return builder.build(); } static Response fromOkHttpResponse(okhttp3.Response response) { Response.Builder builder = new Response.Builder() .headers(fromOkHttpHeaders(response.headers())) .statusCode(StatusCode.fromCode(response.code())) .body(fromOkHttpResponseBody(response.body())) .sentRequestAtMillis(response.sentRequestAtMillis()) .receivedResponseAtMillis(response.receivedResponseAtMillis()); if (response.request() != null) { builder.request(fromOkHttpRequest(response.request())); } return builder.build(); } static okhttp3.Headers toOkHttpHeaders(Headers headers) { okhttp3.Headers.Builder builder = new okhttp3.Headers.Builder(); headers.names().forEach(name -> { List<String> values = headers.values(name); if (values != null) { values.forEach(value -> builder.add(name, value)); } }); return builder.build(); } static Headers fromOkHttpHeaders(okhttp3.Headers headers) { Headers newHeaders = new Headers(); headers.names().forEach(name -> { List<String> values = headers.values(name); if (values != null && !values.isEmpty()) { newHeaders.set(name, values); } }); return newHeaders; } static okhttp3.RequestBody toOkHttpRequestBody(RequestBody body) { Object object = body.get(); if (object instanceof InputStream) { InputStream inputStream = (InputStream) object; return new okhttp3.RequestBody() { @Override public MediaType contentType() { return null; } @Override public long contentLength() { return -1L; } @Override public void writeTo(BufferedSink sink) throws IOException { Source source = null; try { source = Okio.source(inputStream); sink.writeAll(source); } finally { Util.closeQuietly(source); } } }; } else if (object instanceof String) { String string = (String) object; return okhttp3.RequestBody.create(null, string); } else { return null; } } static okhttp3.ResponseBody toOkHttpResponseBody(ResponseBody body) { BufferedSource bufferedSource = Okio.buffer(Okio.source(body.get(InputStream.class))); return okhttp3.ResponseBody.create(null, -1L, bufferedSource); } static ResponseBody fromOkHttpResponseBody(okhttp3.ResponseBody body) { return new ResponseBody() { @Override public <T> T get(Class<T> type) { if (type.isAssignableFrom(InputStream.class)) { return type.cast(body.byteStream()); } else if (type.isAssignableFrom(String.class)) { try { return type.cast(body.string()); } catch (Exception e) { throw new RuntimeException(e); } } else { try { return objectMapper.readValue(body.byteStream(), type); } catch (IOException e) { throw new RuntimeException(e); } finally { body.close(); } } } @Override public long getContentLength() { return body.contentLength(); } @Override public void close() { body.close(); } }; } }
961
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal/okhttp/CompositeRetryInterceptor.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http.internal.okhttp; import java.io.IOException; import java.util.List; import com.google.common.base.Preconditions; import com.netflix.titus.common.network.http.Methods; import com.netflix.titus.common.network.http.StatusCode; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; public class CompositeRetryInterceptor implements Interceptor { private final List<Interceptor> interceptors; private final int attempts; public CompositeRetryInterceptor(List<Interceptor> interceptors, int numberOfRetries) { Preconditions.checkNotNull(interceptors); Preconditions.checkArgument(interceptors.size() > 0, "There must be at least 1 intercepor"); this.interceptors = interceptors; this.attempts = numberOfRetries + 1; } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = null; boolean shouldRetry = true; int maxAttempts = Methods.isBodyAllowed(request.method()) ? 1 : this.attempts; int attempts = 0; while (shouldRetry) { boolean lastAttempt = attempts >= maxAttempts - 1; try { for (Interceptor interceptor : interceptors) { response = interceptor.intercept(chain); } if (response != null) { StatusCode statusCode = StatusCode.fromCode(response.code()); shouldRetry = statusCode != null && statusCode.isRetryable(); } } catch (Exception e) { if (lastAttempt) { throw e; } } finally { attempts++; shouldRetry = shouldRetry && !lastAttempt; if (response != null && shouldRetry) { response.close(); } } } return response; } }
962
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal/okhttp/OkHttpClient.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http.internal.okhttp; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; import com.netflix.titus.common.network.http.HttpClient; import com.netflix.titus.common.network.http.Request; import com.netflix.titus.common.network.http.RequestBody; import com.netflix.titus.common.network.http.Response; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.Protocol; public class OkHttpClient implements HttpClient { private static final String EMPTY_ENDPOINT = "http://<empty>"; private static final int DEFAULT_CONNECT_TIMEOUT = 5_000; private static final int DEFAULT_READ_TIMEOUT = 5_000; private static final int DEFAULT_WRITE_TIMEOUT = 5_000; private final long connectTimeout; private final long readTimeout; private final long writeTimeout; private final SSLContext sslContext; private final X509TrustManager trustManager; private final List<Interceptor> interceptors; private okhttp3.OkHttpClient client; OkHttpClient(Builder builder) { this.connectTimeout = builder.connectTimeout; this.readTimeout = builder.readTimeout; this.writeTimeout = builder.writeTimeout; this.sslContext = builder.sslContext; this.trustManager = builder.trustManager; this.interceptors = builder.interceptors; okhttp3.OkHttpClient.Builder clientBuilder = new okhttp3.OkHttpClient.Builder() .connectTimeout(this.connectTimeout, TimeUnit.MILLISECONDS) .readTimeout(this.readTimeout, TimeUnit.MILLISECONDS) .writeTimeout(this.writeTimeout, TimeUnit.MILLISECONDS) .protocols(Collections.singletonList(Protocol.HTTP_1_1)); if (sslContext != null && trustManager != null) { clientBuilder.sslSocketFactory(sslContext.getSocketFactory(), trustManager) .hostnameVerifier((s, sslSession) -> true); } if (interceptors != null) { for (Interceptor interceptor : interceptors) { clientBuilder.addInterceptor(interceptor); } } this.client = clientBuilder.build(); } @Override public Response execute(Request request) { if (!request.getUrl().startsWith("http")) { request = request.newBuilder() .url(HttpUrl.parse(EMPTY_ENDPOINT + request.getUrl()).toString()) .build(); } okhttp3.Request okHttpRequest = OkHttpConverters.toOkHttpRequest(request); try { okhttp3.Response okHttpResponse = client.newCall(okHttpRequest).execute(); return OkHttpConverters.fromOkHttpResponse(okHttpResponse); } catch (IOException e) { throw new RuntimeException(e); } } @Override public Response get(String url) { Request request = new Request.Builder() .url(url) .get() .build(); return execute(request); } @Override public Response head(String url) { Request request = new Request.Builder() .url(url) .head() .build(); return execute(request); } @Override public Response post(String url, Object entity) { Request request = new Request.Builder() .url(url) .post() .body(RequestBody.create(entity)) .build(); return execute(request); } @Override public Response delete(String url) { Request request = new Request.Builder() .url(url) .delete() .build(); return execute(request); } @Override public Response delete(String url, Object entity) { Request request = new Request.Builder() .url(url) .delete() .body(RequestBody.create(entity)) .build(); return execute(request); } @Override public Response put(String url, Object entity) { Request request = new Request.Builder() .url(url) .put() .body(RequestBody.create(entity)) .build(); return execute(request); } @Override public Response patch(String url, Object entity) { Request request = new Request.Builder() .url(url) .patch() .body(RequestBody.create(entity)) .build(); return execute(request); } public SSLContext sslContext() { return sslContext; } public X509TrustManager trustManager() { return trustManager; } public List<Interceptor> interceptors() { return interceptors; } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(OkHttpClient okHttpClient) { return new Builder(okHttpClient); } public static class Builder { long connectTimeout = -1; long readTimeout = -1; long writeTimeout = -1; SSLContext sslContext; X509TrustManager trustManager; List<Interceptor> interceptors = new ArrayList<>(); public Builder() { } Builder(OkHttpClient client) { this.connectTimeout = client.connectTimeout; this.readTimeout = client.readTimeout; this.writeTimeout = client.writeTimeout; this.sslContext = client.sslContext; this.trustManager = client.trustManager(); this.interceptors = client.interceptors; } public Builder connectTimeout(long connectTimeout) { this.connectTimeout = connectTimeout; return this; } public Builder readTimeout(long readTimeout) { this.readTimeout = readTimeout; return this; } public Builder writeTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; return this; } public Builder sslContext(SSLContext sslContext) { this.sslContext = sslContext; return this; } public Builder trustManager(X509TrustManager trustManager) { this.trustManager = trustManager; return this; } public Builder interceptor(Interceptor interceptor) { this.interceptors.add(interceptor); return this; } public Builder interceptors(List<Interceptor> interceptors) { this.interceptors = interceptors; return this; } public OkHttpClient build() { if (connectTimeout < 0) { connectTimeout = DEFAULT_CONNECT_TIMEOUT; } if (readTimeout < 0) { readTimeout = DEFAULT_READ_TIMEOUT; } if (writeTimeout < 0) { writeTimeout = DEFAULT_WRITE_TIMEOUT; } return new OkHttpClient(this); } } }
963
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal/okhttp/EndpointResolverInterceptor.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http.internal.okhttp; import java.io.IOException; import com.netflix.titus.common.network.http.EndpointResolver; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; public class EndpointResolverInterceptor implements Interceptor { private static final String EMPTY_ENDPOINT = "http://<empty>"; private final EndpointResolver endpointResolver; public EndpointResolverInterceptor(EndpointResolver endpointResolver) { this.endpointResolver = endpointResolver; } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if (request.url().toString().startsWith(EMPTY_ENDPOINT)) { String endpoint = endpointResolver.resolve(); String newUrl = request.url().toString().replaceAll(EMPTY_ENDPOINT, endpoint); request = request.newBuilder().url(newUrl).build(); } return chain.proceed(request); } }
964
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/http/internal/okhttp/RxOkHttpClient.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.http.internal.okhttp; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; import com.netflix.titus.common.network.http.Request; import com.netflix.titus.common.network.http.RequestBody; import com.netflix.titus.common.network.http.Response; import com.netflix.titus.common.network.http.RxHttpClient; import okhttp3.Call; import okhttp3.Callback; import okhttp3.HttpUrl; import okhttp3.Interceptor; import rx.Emitter; import rx.Observable; public class RxOkHttpClient implements RxHttpClient { private static final String EMPTY_ENDPOINT = "http://<empty>"; private static final int DEFAULT_CONNECT_TIMEOUT = 5_000; private static final int DEFAULT_READ_TIMEOUT = 5_000; private static final int DEFAULT_WRITE_TIMEOUT = 5_000; private final long connectTimeout; private final long readTimeout; private final long writeTimeout; private final SSLContext sslContext; private final X509TrustManager trustManager; private final List<Interceptor> interceptors; private okhttp3.OkHttpClient client; RxOkHttpClient(Builder builder) { this.connectTimeout = builder.connectTimeout; this.readTimeout = builder.readTimeout; this.writeTimeout = builder.writeTimeout; this.sslContext = builder.sslContext; this.trustManager = builder.trustManager; this.interceptors = builder.interceptors; okhttp3.OkHttpClient.Builder clientBuilder = new okhttp3.OkHttpClient.Builder() .connectTimeout(this.connectTimeout, TimeUnit.MILLISECONDS) .readTimeout(this.readTimeout, TimeUnit.MILLISECONDS) .writeTimeout(this.writeTimeout, TimeUnit.MILLISECONDS); if (sslContext != null && trustManager != null) { clientBuilder.sslSocketFactory(sslContext.getSocketFactory(), trustManager) .hostnameVerifier((s, sslSession) -> true); } if (interceptors != null) { for (Interceptor interceptor : interceptors) { clientBuilder.addInterceptor(interceptor); } } this.client = clientBuilder.build(); } @Override public Observable<Response> execute(Request request) { return Observable.create(emitter -> { Request newRequest = request; if (!request.getUrl().startsWith("http")) { newRequest = request.newBuilder() .url(HttpUrl.parse(EMPTY_ENDPOINT + newRequest.getUrl()).toString()) .build(); } okhttp3.Request okHttpRequest = OkHttpConverters.toOkHttpRequest(newRequest); client.newCall(okHttpRequest).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { emitter.onError(e); } @Override public void onResponse(Call call, okhttp3.Response response) throws IOException { emitter.onNext(OkHttpConverters.fromOkHttpResponse(response)); } }); }, Emitter.BackpressureMode.NONE); } @Override public Observable<Response> get(String url) { Request request = new Request.Builder() .url(url) .get() .build(); return execute(request); } @Override public Observable<Response> head(String url) { Request request = new Request.Builder() .url(url) .head() .build(); return execute(request); } @Override public Observable<Response> post(String url, Object entity) { Request request = new Request.Builder() .url(url) .post() .body(RequestBody.create(entity)) .build(); return execute(request); } @Override public Observable<Response> delete(String url) { Request request = new Request.Builder() .url(url) .delete() .build(); return execute(request); } @Override public Observable<Response> delete(String url, Object entity) { Request request = new Request.Builder() .url(url) .delete() .body(RequestBody.create(entity)) .build(); return execute(request); } @Override public Observable<Response> put(String url, Object entity) { Request request = new Request.Builder() .url(url) .put() .body(RequestBody.create(entity)) .build(); return execute(request); } @Override public Observable<Response> patch(String url, Object entity) { Request request = new Request.Builder() .url(url) .patch() .body(RequestBody.create(entity)) .build(); return execute(request); } public SSLContext sslContext() { return sslContext; } public X509TrustManager trustManager() { return trustManager; } public List<Interceptor> interceptors() { return interceptors; } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(RxOkHttpClient rxOkHttpClient) { return new Builder(rxOkHttpClient); } public static class Builder { long connectTimeout = -1; long readTimeout = -1; long writeTimeout = -1; SSLContext sslContext; X509TrustManager trustManager; List<Interceptor> interceptors = new ArrayList<>(); public Builder() { } Builder(RxOkHttpClient client) { this.connectTimeout = client.connectTimeout; this.readTimeout = client.readTimeout; this.writeTimeout = client.writeTimeout; this.sslContext = client.sslContext; this.trustManager = client.trustManager(); this.interceptors = client.interceptors; } public Builder connectTimeout(long connectTimeout) { this.connectTimeout = connectTimeout; return this; } public Builder readTimeout(long readTimeout) { this.readTimeout = readTimeout; return this; } public Builder writeTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; return this; } public Builder sslContext(SSLContext sslContext) { this.sslContext = sslContext; return this; } public Builder trustManager(X509TrustManager trustManager) { this.trustManager = trustManager; return this; } public Builder interceptor(Interceptor interceptor) { this.interceptors.add(interceptor); return this; } public Builder interceptors(List<Interceptor> interceptors) { this.interceptors = interceptors; return this; } public RxOkHttpClient build() { if (connectTimeout < 0) { connectTimeout = DEFAULT_CONNECT_TIMEOUT; } if (readTimeout < 0) { readTimeout = DEFAULT_READ_TIMEOUT; } if (writeTimeout < 0) { writeTimeout = DEFAULT_WRITE_TIMEOUT; } return new RxOkHttpClient(this); } } }
965
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/client/LatencyRecorder.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.client; import java.time.Duration; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import com.google.common.base.Preconditions; import com.netflix.titus.common.network.client.internal.WebClientMetric; import com.netflix.titus.common.util.time.Clock; import org.springframework.http.HttpMethod; import reactor.core.CoreSubscriber; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoOperator; // TODO: same operator for Flux when needed class LatencyRecorder<T> extends MonoOperator<T, T> { private final Clock clock; private final WebClientMetric metrics; private final HttpMethod method; private final Optional<String> path; LatencyRecorder(Clock clock, Mono<T> source, WebClientMetric metrics, HttpMethod method) { super(source); this.clock = clock; this.metrics = metrics; this.method = method; this.path = Optional.empty(); } LatencyRecorder(Clock clock, Mono<T> source, WebClientMetric metrics, HttpMethod method, String path) { super(source); this.clock = clock; this.metrics = metrics; this.method = method; this.path = Optional.of(path); } @Override public void subscribe(CoreSubscriber<? super T> actual) { AtomicLong startTimeMsHolder = new AtomicLong(); source.subscribe( actual::onNext, error -> { long startTimeMs = startTimeMsHolder.get(); Preconditions.checkState(startTimeMs > 0, "onError() called before onSubscribe()"); Duration elapsed = Duration.ofMillis(clock.wallTime() - startTimeMs); if (path.isPresent()) { metrics.registerOnErrorLatency(method, path.get(), elapsed); } else { metrics.registerOnErrorLatency(method, elapsed); } actual.onError(error); }, () -> { long startTimeMs = startTimeMsHolder.get(); Preconditions.checkState(startTimeMs > 0, "onComplete() called before onSubscribe()"); Duration elapsed = Duration.ofMillis(clock.wallTime() - startTimeMs); if (path.isPresent()) { metrics.registerOnSuccessLatency(method, path.get(), elapsed); } else { metrics.registerOnSuccessLatency(method, elapsed); } actual.onComplete(); }, subscription -> { startTimeMsHolder.set(clock.wallTime()); actual.onSubscribe(subscription); } ); } }
966
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/client/WebClientExt.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.client; import java.util.function.Function; import com.netflix.titus.common.network.client.internal.WebClientMetric; import com.netflix.titus.common.util.time.Clock; import org.reactivestreams.Publisher; import org.springframework.http.HttpMethod; import reactor.core.publisher.Mono; public final class WebClientExt { /** * A {@link Mono} operator that records latency of completion (success or error), use with * {@link Mono#compose(Function)}. */ public static <T> Function<Mono<T>, Publisher<T>> latencyMonoOperator(Clock clock, WebClientMetric metrics, HttpMethod method) { return source -> new LatencyRecorder<>(clock, source, metrics, method); } /** * A {@link Mono} operator that records latency of completion (success or error), use with * {@link Mono#compose(Function)}. */ public static <T> Function<Mono<T>, Publisher<T>> latencyMonoOperator(Clock clock, WebClientMetric metrics, HttpMethod method, String path) { return source -> new LatencyRecorder<>(clock, source, metrics, method, path); } }
967
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/client/ClientMetrics.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.client; import java.time.Duration; import java.util.concurrent.TimeUnit; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.util.StringExt; public class ClientMetrics { private static final String CLIENT_REQUEST = "request"; private static final String CLIENT_LATENCY = "latency"; private static final String CLIENT_ENDPOINT_TAG = "endpoint"; private static final String CLIENT_METHOD_TAG = "method"; private static final String CLIENT_PATH_TAG = "path"; private static final String CLIENT_RESPONSE_STATUS_TAG = "status"; private static final String CLIENT_RESPONSE_STATUS_SUCCESS = "success"; private static final String CLIENT_RESPONSE_STATUS_FAILURE = "failure"; private final Registry registry; private final Id requestId; private final Id latencyId; public ClientMetrics(String metricNamePrefix, String endpointName, Registry registry) { String updatedMetricNamePrefix = StringExt.appendToEndIfMissing(metricNamePrefix, "."); this.registry = registry; requestId = registry.createId(updatedMetricNamePrefix + CLIENT_REQUEST) .withTag(CLIENT_ENDPOINT_TAG, endpointName); latencyId = registry.createId(updatedMetricNamePrefix + CLIENT_LATENCY) .withTag(CLIENT_ENDPOINT_TAG, endpointName); } /** * Register a success latency metric based on how much time elapsed from when a request was sent. */ public void registerOnSuccessLatency(String methodName, Duration elapsed) { recordTimer(latencyId .withTag(CLIENT_METHOD_TAG, methodName) .withTag(CLIENT_RESPONSE_STATUS_TAG, CLIENT_RESPONSE_STATUS_SUCCESS), elapsed ); } /** * Register a success latency metric based on how much time elapsed from when a request was sent. */ public void registerOnSuccessLatency(String methodName, String path, Duration elapsed) { recordTimer(latencyId .withTag(CLIENT_METHOD_TAG, methodName) .withTag(CLIENT_PATH_TAG, path) .withTag(CLIENT_RESPONSE_STATUS_TAG, CLIENT_RESPONSE_STATUS_SUCCESS), elapsed ); } /** * Register an error latency metric based on how much time elapsed from when a request was sent. */ public void registerOnErrorLatency(String methodName, Duration elapsed) { recordTimer(latencyId .withTag(CLIENT_METHOD_TAG, methodName) .withTag(CLIENT_RESPONSE_STATUS_TAG, CLIENT_RESPONSE_STATUS_FAILURE), elapsed ); } /** * Register an error latency metric based on how much time elapsed from when a request was sent. */ public void registerOnErrorLatency(String methodName, String path, Duration elapsed) { recordTimer(latencyId .withTag(CLIENT_METHOD_TAG, methodName) .withTag(CLIENT_PATH_TAG, path) .withTag(CLIENT_RESPONSE_STATUS_TAG, CLIENT_RESPONSE_STATUS_FAILURE), elapsed ); } private void recordTimer(Id id, Duration elapsed) { registry.timer(id).record(elapsed.toMillis(), TimeUnit.MILLISECONDS); } public void incrementOnSuccess(String methodName, String path, String status) { registry.counter(requestId .withTag(CLIENT_METHOD_TAG, methodName) .withTag(CLIENT_PATH_TAG, path) .withTag("statusCode", status) ).increment(); } public void incrementOnError(String methodName, String path, Throwable throwable) { registry.counter(requestId .withTag(CLIENT_METHOD_TAG, methodName) .withTag(CLIENT_PATH_TAG, path) .withTag("error", throwable.getClass().getSimpleName()) ).increment(); } }
968
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/client/TitusWebClientAddOns.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.client; import java.net.InetSocketAddress; import java.time.Duration; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import javax.net.ssl.SSLException; import com.netflix.titus.common.network.client.internal.WebClientMetric; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import org.reactivestreams.Publisher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Flux; import reactor.netty.http.HttpOperations; import reactor.netty.http.client.HttpClient; import reactor.netty.http.client.HttpClientResponse; import reactor.util.retry.Retry; /** * A collection of add-ons for Spring {@link WebClient}. * <p> */ public final class TitusWebClientAddOns { private static final Logger logger = LoggerFactory.getLogger(TitusWebClientAddOns.class); private static final Logger requestLogger = LoggerFactory.getLogger("WebClientRequestLogger"); public static WebClient.Builder addTitusDefaults(WebClient.Builder clientBuilder, HttpClient httpClient, WebClientMetric webClientMetric) { HttpClient updatedHttpClient = addMetricCallbacks( addLoggingCallbacks(httpClient), webClientMetric ); return clientBuilder.clientConnector(new ReactorClientHttpConnector(updatedHttpClient)); } public static WebClient.Builder addTitusDefaults(WebClient.Builder clientBuilder, boolean secure, WebClientMetric webClientMetric) { HttpClient httpClient = HttpClient.create(); // SSL if (secure) { try { SslContext sslContext = SslContextBuilder.forClient().build(); httpClient = httpClient.secure(spec -> spec.sslContext(sslContext)); } catch (SSLException e) { logger.error("Unable configure Docker registry client SSL context: {}", e.getMessage()); throw new RuntimeException("Error configuring SSL context", e); } } return addTitusDefaults(clientBuilder, httpClient, webClientMetric); } public static Retry retryer(Duration interval, int retryLimit, Function<Throwable, Boolean> retryPredicate, Logger callerLogger) { return new Retry() { @Override public Publisher<?> generateCompanion(Flux<RetrySignal> retrySignals) { return Flux.defer(() -> { AtomicInteger remaining = new AtomicInteger(retryLimit); return retrySignals.flatMap(retrySignal -> { Throwable error = retrySignal.failure() == null ? new IllegalStateException("retry called without a failure") : retrySignal.failure(); if (!retryPredicate.apply(error)) { return Flux.error(error); } if (remaining.get() <= 0) { callerLogger.warn("Retry limit reached. Returning error to the client", error); return Flux.error(error); } remaining.getAndDecrement(); logger.info("Retrying failed HTTP request in {}ms", interval.toMillis()); return Flux.interval(interval).take(1); }); }); } }; } private static HttpClient addLoggingCallbacks(HttpClient httpClient) { return httpClient .doOnRequestError((request, error) -> requestLogger.info(String.format( "%10s %10s %64s %8s %s", request.method(), "NOT_SENT", request.uri(), 0, error.getMessage() ))) .doOnResponse((response, connection) -> requestLogger.info(String.format( "%10s %10s %64s", response.method(), response.status().reasonPhrase(), buildFullUri(response) ))) .doOnResponseError((response, error) -> requestLogger.info(String.format( "%10s %10s %64s %s", response.method(), response.status().reasonPhrase(), buildFullUri(response), error.getMessage() ))); } /** * {@link HttpClientResponse#uri()} is incomplete, and contains only URL path. We have to reconstruct full URL * from pieces available. It is still not complete, as there is no way to find out if this is plain text or * TLS connection. */ private static String buildFullUri(HttpClientResponse response) { if (response instanceof HttpOperations) { HttpOperations httpOperations = (HttpOperations) response; StringBuilder sb = new StringBuilder("http://"); InetSocketAddress address = (InetSocketAddress) httpOperations.address(); sb.append(address.getHostString()); sb.append(':').append(address.getPort()); String path = response.path(); if (!path.startsWith("/")) { sb.append('/'); } sb.append(path); return sb.toString(); } return response.path(); } private static HttpClient addMetricCallbacks(HttpClient httpClient, WebClientMetric webClientMetric) { return httpClient .doAfterResponseSuccess(webClientMetric::incrementOnSuccess) .doOnResponseError(webClientMetric::incrementOnError); } }
969
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/client
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/client/internal/WebClientMetric.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.client.internal; import java.time.Duration; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.network.client.ClientMetrics; import org.springframework.http.HttpMethod; import reactor.netty.Connection; import reactor.netty.http.client.HttpClientResponse; public class WebClientMetric { private static final String WEB_CLIENT_METRICS = "titus.webClient."; private final ClientMetrics delegate; public WebClientMetric(String endpointName, Registry registry) { delegate = new ClientMetrics(WEB_CLIENT_METRICS, endpointName, registry); } public void registerOnSuccessLatency(HttpMethod method, Duration elapsed) { delegate.registerOnSuccessLatency(method.name(), elapsed); } public void registerOnSuccessLatency(HttpMethod method, String path, Duration elapsed) { delegate.registerOnSuccessLatency(method.name(), path, elapsed); } public void registerOnErrorLatency(HttpMethod method, Duration elapsed) { delegate.registerOnErrorLatency(method.name(), elapsed); } public void registerOnErrorLatency(HttpMethod method, String path, Duration elapsed) { delegate.registerOnErrorLatency(method.name(), path, elapsed); } public void incrementOnSuccess(HttpClientResponse response, Connection connection) { delegate.incrementOnSuccess(response.method().name(), response.path(), response.status().toString()); } public void incrementOnError(HttpClientResponse response, Throwable throwable) { delegate.incrementOnError(response.method().name(), response.path(), throwable); } }
970
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/socket/UnusedSocketPortAllocator.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.socket; import java.io.IOException; import java.net.ServerSocket; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.netflix.titus.common.util.ExceptionExt; import com.netflix.titus.common.util.NetworkExt; import com.netflix.titus.common.util.ReflectionExt; import com.netflix.titus.common.util.StringExt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UnusedSocketPortAllocator implements SocketPortAllocator { private static final Logger logger = LoggerFactory.getLogger(UnusedSocketPortAllocator.class); private static final UnusedSocketPortAllocator INSTANCE = new UnusedSocketPortAllocator(); /** * For JVM running concurrently (integration tests), we want to place their port allocation in different pools. */ private static final int PARTITION = 100; private static final int HISTORY_SIZE = PARTITION / 2; private static final int PID = getPid(); private final int offset; // We use list not set, as the order is important private final List<Integer> recentAllocations = new ArrayList<>(); private int next; private UnusedSocketPortAllocator() { this.offset = NetworkExt.findUnusedPort() + (PID % 10) * PARTITION; } @Override public int allocate() { synchronized (recentAllocations) { for (int i = 0; i < PARTITION; i++) { int port = offset + next; next = (next + 1) % PARTITION; if (!isRecentlyUsed(port) && isAvailable(port)) { recentAllocations.add(port); while (recentAllocations.size() > HISTORY_SIZE) { recentAllocations.remove(0); } logger.info("Allocated port: port={} caller={}", port, ReflectionExt.findCallerStackTrace().map(StackTraceElement::toString).orElse("unknown") ); return port; } } } throw new IllegalStateException("No free sockets available"); } public static UnusedSocketPortAllocator global() { return INSTANCE; } private boolean isRecentlyUsed(int port) { for (int used : recentAllocations) { if (used == port) { return true; } } return false; } private boolean isAvailable(int port) { try { ServerSocket serverSocket = new ServerSocket(port); serverSocket.close(); return true; } catch (IOException e) { return false; } } private static int getPid() { int pid; // Try sun system property first String property = System.getProperty("sun.java.launcher.pid"); if (property != null) { pid = ExceptionExt.doTry(() -> Integer.parseInt(property)).orElse(-1); if (pid >= 0) { return pid; } } // Now JMX String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName(); if (StringExt.isNotEmpty(processName)) { StringBuilder digitsOnly = new StringBuilder(); for (char c : processName.toCharArray()) { if (Character.isDigit(c)) { digitsOnly.append(c); } } if (digitsOnly.length() > 0) { String digits = digitsOnly.substring(0, Math.min(8, digitsOnly.length())); return Integer.parseInt(digits); } } // Final fallback - a random number. return new Random().nextInt(10); } }
971
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/socket/SocketPortAllocator.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.socket; public interface SocketPortAllocator { int allocate(); }
972
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/network/socket/DirectSocketPortAllocator.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.network.socket; import java.util.function.Supplier; import com.google.common.base.Preconditions; public class DirectSocketPortAllocator implements SocketPortAllocator { private final Supplier<Integer> portSupplier; public DirectSocketPortAllocator(Supplier<Integer> portSupplier) { this.portSupplier = portSupplier; } @Override public int allocate() { int port = portSupplier.get(); Preconditions.checkState(port > 0, "Allocated server socket port is <= 0: %s", port); return port; } }
973
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime/SystemLogEvent.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.runtime; import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Set; import static com.netflix.titus.common.util.Evaluators.getOrDefault; /** * System logger event (see {@link SystemLogService}). */ public class SystemLogEvent { /** * The criticality level of the log event. */ public enum Priority { /** * Use when system operates normally, to log information about an important system change. For example * becoming a new leader, an important configuration change, etc. */ Info, /** * Use when erroneous but non-critical things happens. For example, invariant violations that can be fixed, but * indicate potential issues either in the code or the user provided data. */ Warn, /** * Use when the system's ability to make progress with its work is impaired or a major invariant violation is * discovered. For example, prolonged lack of connectivity with AWS service, corrupted data detected in a * core system component, etc. */ Error, /** * Use for major issues, which may result in incorrect system behavior or forced system shutdown. */ Fatal } /** * High level classifier for the event, that can be used as a key aggregator by an event processing system. * For example, by classifying all external connectivity errors as {@link Category#ConnectivityError}, it easy * to filter them out and detect common connectivity issues. */ public enum Category { /** * A transient error. */ Transient, /** * Permanent error. System is not able to recover from it without help from an administrator. */ Permanent, /** * Connectivity issues with an external system (database, AWS, etc). */ ConnectivityError, /** * System invariant violations (for example corrupted data discovered in the core processing logic). */ InvariantViolation, /** * Use when none of the existing categories are applicable. */ Other } /** * Event category (see {@link Category}). */ private final Category category; /** * Event category (see {@link Priority}). */ private final Priority priority; /** * Name of a component that creates the event. */ private final String component; /** * A short description of an event. */ private final String message; /** * A collection of tags for further event classification. */ private final Set<String> tags; /** * Additional information giving more insight into what happened. For example, if corrupted task data are found, * the context may include the job and task ids. */ private final Map<String, String> context; private SystemLogEvent(Category category, Priority priority, String component, String message, Set<String> tags, Map<String, String> context) { this.category = category; this.priority = priority; this.component = component; this.message = message; this.tags = tags; this.context = context; } public Category getCategory() { return category; } public Priority getPriority() { return priority; } public String getComponent() { return component; } public String getMessage() { return message; } public Set<String> getTags() { return tags; } public Map<String, String> getContext() { return context; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SystemLogEvent that = (SystemLogEvent) o; return category == that.category && priority == that.priority && Objects.equals(component, that.component) && Objects.equals(message, that.message) && Objects.equals(tags, that.tags) && Objects.equals(context, that.context); } @Override public int hashCode() { return Objects.hash(category, priority, component, message, tags, context); } @Override public String toString() { return "SystemLogEvent{" + "category=" + category + ", priority=" + priority + ", component='" + component + '\'' + ", message='" + message + '\'' + ", tags=" + tags + ", context=" + context + '}'; } public Builder toBuilder() { return newBuilder().withCategory(category).withPriority(priority).withComponent(component).withMessage(message).withTags(tags).withContext(context); } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private Category category; private Priority priority; private String component; private String message; private Set<String> tags; private Map<String, String> context; private Builder() { } public Builder withCategory(Category category) { this.category = category; return this; } public Builder withPriority(Priority priority) { this.priority = priority; return this; } public Builder withComponent(String component) { this.component = component; return this; } public Builder withMessage(String message) { this.message = message; return this; } public Builder withTags(Set<String> tags) { this.tags = tags; return this; } public Builder withContext(Map<String, String> context) { this.context = context; return this; } public Builder but() { return newBuilder().withCategory(category).withPriority(priority).withComponent(component).withMessage(message).withTags(tags).withContext(context); } public SystemLogEvent build() { return new SystemLogEvent( getOrDefault(category, Category.Other), getOrDefault(priority, Priority.Info), getOrDefault(component, "not_set"), getOrDefault(message, "not_set"), getOrDefault(tags, Collections.emptySet()), getOrDefault(context, Collections.emptyMap()) ); } } }
974
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime/SystemAbortListener.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.runtime; /** * A callback API for notifying listeners about a fatal event in the system, resulting in the immediate Titus shutdown. */ public interface SystemAbortListener { void onSystemAbortEvent(SystemAbortEvent event); }
975
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime/InternalRuntimeComponent.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.runtime; import com.netflix.spectator.api.Registry; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; /** * {@link TitusRuntime} component for test deployments. */ @Component public class InternalRuntimeComponent { private final TitusRuntime titusRuntime = TitusRuntimes.internal(true); @Bean public TitusRuntime getTitusRuntime() { return titusRuntime; } @Bean public Registry getRegistry(TitusRuntime titusRuntime) { return titusRuntime.getRegistry(); } }
976
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime/TitusRuntime.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.runtime; import java.time.Duration; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.environment.MyEnvironment; import com.netflix.titus.common.framework.fit.FitFramework; import com.netflix.titus.common.framework.scheduler.LocalScheduler; import com.netflix.titus.common.util.code.CodeInvariants; import com.netflix.titus.common.util.code.CodePointTracker; import com.netflix.titus.common.util.time.Clock; import rx.Observable; /** * Collection of core services used by all Titus components. */ public interface TitusRuntime { /** * Returns the configured {@link MyEnvironment} instance. */ MyEnvironment getMyEnvironment(); /** * Returns the configured {@link CodePointTracker} instance. */ CodePointTracker getCodePointTracker(); /** * Returns the configured {@link CodeInvariants} instance. */ CodeInvariants getCodeInvariants(); /** * Returns the configured {@link SystemLogService}. */ SystemLogService getSystemLogService(); /** * Returns the configured Spectator registry. */ Registry getRegistry(); /** * Instruments the given observable with metrics, and applies default retry strategy if the observable completes * with an error. Its primary purpose is to use for tracking inter-component subscriptions, which should exist * for the full lifetime of the process. */ <T> Observable<T> persistentStream(Observable<T> source); /** * Returns the configured clock. */ Clock getClock(); /** * Returns FIT framework. */ FitFramework getFitFramework(); /** * Simple in JVM task scheduler. */ LocalScheduler getLocalScheduler(); /** * If true, fatal errors cause JVM termination via System.exit. */ boolean isSystemExitOnFailure(); /** * In a few places in TitusMaster a component may decide to break the bootstrap process or terminate the JVM process * abruptly. This method should be called before that happens, so the {@link SystemAbortListener} implementation can * send a signal/alert to an administrator about the incident. */ void beforeAbort(SystemAbortEvent event); interface Builder { Builder withMyEnvironment(MyEnvironment myEnvironment); Builder withCodePointTracker(CodePointTracker codePointTracker); Builder withCodeInvariants(CodeInvariants codeInvariants); Builder withSystemLogService(SystemLogService systemLogService); Builder withSystemExitOnFailure(boolean systemExitOnFailure); Builder withSystemAbortListener(SystemAbortListener systemAbortListener); Builder withRegistry(Registry registry); Builder withClock(Clock clock); Builder withFitFramework(boolean fitEnabled); Builder withLocalSchedulerLoopInterval(Duration localSchedulerLoopInterval); TitusRuntime build(); } }
977
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime/SystemLogService.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.runtime; /** * An API for processing system events (errors, exceptions, invariant violations, important configuration changes, etc) * with supplementary metadata information. Those events are sent to external system(s) for further processing * and automated analysis and reporting. */ public interface SystemLogService { /** * Write an event to an external system for further processing. * * @return true if the event was accepted, false otherwise. Accepting an event does not mean that it was or will be * successfully delivered to an external event store. False result means that the event consumer is overloaded. * {@link SystemLogService} implementation may choose in the latter case to accept higher priority events over * the lower priority ones. */ boolean submit(SystemLogEvent event); }
978
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime/TitusRuntimes.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.runtime; import java.time.Duration; import com.netflix.titus.common.environment.MyEnvironment; import com.netflix.titus.common.environment.MyEnvironments; import com.netflix.titus.common.runtime.internal.DefaultTitusRuntime; import com.netflix.titus.common.util.code.RecordingCodeInvariants; import com.netflix.titus.common.util.time.Clocks; import com.netflix.titus.common.util.time.TestClock; import org.springframework.core.env.Environment; import rx.schedulers.TestScheduler; public final class TitusRuntimes { private TitusRuntimes() { } public static TitusRuntime internal(MyEnvironment environment) { return DefaultTitusRuntime.newBuilder() .withMyEnvironment(environment) .build(); } public static TitusRuntime internal(Environment environment) { return DefaultTitusRuntime.newBuilder() .withMyEnvironment(MyEnvironments.newSpring(environment)) .build(); } public static TitusRuntime internal(Duration localSchedulerLoopInterval) { return DefaultTitusRuntime.newBuilder() .withLocalSchedulerLoopInterval(localSchedulerLoopInterval) .build(); } public static TitusRuntime internal() { return DefaultTitusRuntime.newBuilder().build(); } public static TitusRuntime internal(boolean fitEnabled) { return DefaultTitusRuntime.newBuilder().withFitFramework(fitEnabled).build(); } public static TitusRuntime test() { return DefaultTitusRuntime.newBuilder() .withClock(Clocks.test()) .withCodeInvariants(new RecordingCodeInvariants()) .withFitFramework(true) .build(); } public static TitusRuntime test(TestClock clock) { return DefaultTitusRuntime.newBuilder() .withClock(clock) .withCodeInvariants(new RecordingCodeInvariants()) .withFitFramework(true) .build(); } public static TitusRuntime test(TestScheduler testScheduler) { return DefaultTitusRuntime.newBuilder() .withClock(Clocks.testScheduler(testScheduler)) .withCodeInvariants(new RecordingCodeInvariants()) .withFitFramework(true) .build(); } }
979
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime/SystemAbortEvent.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.runtime; import java.util.Objects; /** * System abort event. */ public class SystemAbortEvent { public enum FailureType { /** * There is an error requiring system restart, but the system is expected to recover without human intervention. */ Recoverable, /** * There is a non-recoverable system error, which requires direct involvement of the system administrator. */ Nonrecoverable } private final String failureId; private final FailureType failureType; private final String reason; private final long timestamp; public SystemAbortEvent(String failureId, FailureType failureType, String reason, long timestamp) { this.failureId = failureId; this.failureType = failureType; this.reason = reason; this.timestamp = timestamp; } public String getFailureId() { return failureId; } public FailureType getFailureType() { return failureType; } public String getReason() { return reason; } public long getTimestamp() { return timestamp; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SystemAbortEvent that = (SystemAbortEvent) o; return timestamp == that.timestamp && Objects.equals(failureId, that.failureId) && failureType == that.failureType && Objects.equals(reason, that.reason); } @Override public int hashCode() { return Objects.hash(failureId, failureType, reason, timestamp); } @Override public String toString() { return "SystemAbortEvent{" + "failureId='" + failureId + '\'' + ", failureType=" + failureType + ", reason='" + reason + '\'' + ", timestamp=" + timestamp + '}'; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private String failureId; private FailureType failureType; private String reason; private long timestamp; private Builder() { } public Builder withFailureId(String failureId) { this.failureId = failureId; return this; } public Builder withFailureType(FailureType failureType) { this.failureType = failureType; return this; } public Builder withReason(String reason) { this.reason = reason; return this; } public Builder withTimestamp(long timestamp) { this.timestamp = timestamp; return this; } public Builder but() { return newBuilder().withFailureId(failureId).withFailureType(failureType).withReason(reason).withTimestamp(timestamp); } public SystemAbortEvent build() { return new SystemAbortEvent(failureId, failureType, reason, timestamp); } } }
980
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime/internal/AggregatingSystemLogService.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.runtime.internal; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.common.runtime.SystemLogEvent; import com.netflix.titus.common.runtime.SystemLogService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class AggregatingSystemLogService implements SystemLogService { private static final Logger logger = LoggerFactory.getLogger(AggregatingSystemLogService.class); private final Set<SystemLogService> delegates; @Inject public AggregatingSystemLogService(Set<SystemLogService> delegates) { this.delegates = delegates; } @Override public boolean submit(SystemLogEvent event) { boolean result = true; for (SystemLogService delegate : delegates) { try { result = result && delegate.submit(event); } catch (Exception e) { logger.warn("Logging error in delegate {}: {}", delegate.getClass().getSimpleName(), e.getMessage()); result = false; } } return result; } }
981
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime/internal/DefaultTitusRuntime.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.runtime.internal; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Tag; import com.netflix.titus.common.environment.MyEnvironment; import com.netflix.titus.common.environment.MyEnvironments; import com.netflix.titus.common.framework.fit.FitFramework; import com.netflix.titus.common.framework.scheduler.LocalScheduler; import com.netflix.titus.common.framework.scheduler.internal.DefaultLocalScheduler; import com.netflix.titus.common.runtime.SystemAbortEvent; import com.netflix.titus.common.runtime.SystemAbortListener; import com.netflix.titus.common.runtime.SystemLogService; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.ReflectionExt; import com.netflix.titus.common.util.code.CodeInvariants; import com.netflix.titus.common.util.code.CodePointTracker; import com.netflix.titus.common.util.code.LoggingCodeInvariants; import com.netflix.titus.common.util.code.LoggingCodePointTracker; import com.netflix.titus.common.util.code.SpectatorCodePointTracker; import com.netflix.titus.common.util.rx.RetryHandlerBuilder; import com.netflix.titus.common.util.spectator.SpectatorExt; import com.netflix.titus.common.util.time.Clock; import com.netflix.titus.common.util.time.Clocks; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.scheduler.Schedulers; import rx.Observable; @Singleton public class DefaultTitusRuntime implements TitusRuntime { static final Duration LOCAL_SCHEDULER_LOOP_INTERVAL_MS = Duration.ofMillis(100); public static final String SYSTEM_EXIT_ON_FAILURE = "systemExitOnFailure"; private static final Logger logger = LoggerFactory.getLogger(DefaultTitusRuntime.class); public static final String FIT_ACTIVATION_PROPERTY = "titus.runtime.fit.enabled"; private static final String METRICS_RUNTIME_ROOT = "titus.system."; private static final String METRICS_PERSISTENT_STREAM = METRICS_RUNTIME_ROOT + "persistentStream"; private static final String UNKNOWN = "UNKNOWN"; private static final long INITIAL_RETRY_DELAY_MS = 10; private static final long MAX_RETRY_DELAY_MS = 10_000; private static final Duration LOCAL_SCHEDULER_LOOP_INTERVAL = Duration.ofMillis(100); private final MyEnvironment myEnvironment; private final CodePointTracker codePointTracker; private final CodeInvariants codeInvariants; private final SystemLogService systemLogService; private final boolean systemExitOnFailure; private final SystemAbortListener systemAbortListener; private final Registry registry; private final Clock clock; private final FitFramework fitFramework; private final DefaultLocalScheduler localScheduler; @Inject public DefaultTitusRuntime(MyEnvironment myEnvironment, CodeInvariants codeInvariants, SystemLogService systemLogService, @Named(SYSTEM_EXIT_ON_FAILURE) boolean systemExitOnFailure, SystemAbortListener systemAbortListener, Registry registry) { this( myEnvironment, new SpectatorCodePointTracker(registry), codeInvariants, systemLogService, systemExitOnFailure, systemAbortListener, LOCAL_SCHEDULER_LOOP_INTERVAL, registry, Clocks.system(), "true".equals(System.getProperty(FIT_ACTIVATION_PROPERTY, "false")) ); } public DefaultTitusRuntime(MyEnvironment myEnvironment, CodePointTracker codePointTracker, CodeInvariants codeInvariants, SystemLogService systemLogService, boolean systemExitOnFailure, SystemAbortListener systemAbortListener, Duration localSchedulerLoopInterval, Registry registry, Clock clock, boolean isFitEnabled) { this.myEnvironment = myEnvironment; this.codePointTracker = codePointTracker; this.codeInvariants = codeInvariants; this.systemLogService = systemLogService; this.systemExitOnFailure = systemExitOnFailure; this.systemAbortListener = systemAbortListener; this.registry = registry; this.clock = clock; this.fitFramework = isFitEnabled ? FitFramework.newFitFramework() : FitFramework.inactiveFitFramework(); this.localScheduler = new DefaultLocalScheduler(localSchedulerLoopInterval, Schedulers.parallel(), clock, registry); } @Override public MyEnvironment getMyEnvironment() { return myEnvironment; } @Override public <T> Observable<T> persistentStream(Observable<T> source) { String callerName; List<Tag> commonTags; Optional<StackTraceElement> callerStackTraceOpt = ReflectionExt.findCallerStackTrace(); if (callerStackTraceOpt.isPresent()) { StackTraceElement callerStackTrace = callerStackTraceOpt.get(); commonTags = Arrays.asList( new BasicTag("class", callerStackTrace.getClassName()), new BasicTag("method", callerStackTrace.getMethodName()), new BasicTag("line", Integer.toString(callerStackTrace.getLineNumber())) ); callerName = callerStackTrace.getClassName() + '.' + callerStackTrace.getMethodName() + '@' + callerStackTrace.getLineNumber(); } else { callerName = UNKNOWN; commonTags = Arrays.asList( new BasicTag("class", UNKNOWN), new BasicTag("method", UNKNOWN), new BasicTag("line", UNKNOWN) ); } return source .compose(SpectatorExt.subscriptionMetrics(METRICS_PERSISTENT_STREAM, commonTags, registry)) .retryWhen(RetryHandlerBuilder.retryHandler() .withUnlimitedRetries() .withDelay(INITIAL_RETRY_DELAY_MS, MAX_RETRY_DELAY_MS, TimeUnit.MILLISECONDS) .withTitle("Auto-retry for " + callerName) .buildExponentialBackoff() ); } @Override public Clock getClock() { return clock; } @Override public CodePointTracker getCodePointTracker() { return codePointTracker; } @Override public CodeInvariants getCodeInvariants() { return codeInvariants; } @Override public SystemLogService getSystemLogService() { return systemLogService; } @Override public Registry getRegistry() { return registry; } @Override public FitFramework getFitFramework() { return fitFramework; } @Override public LocalScheduler getLocalScheduler() { return localScheduler; } @Override public boolean isSystemExitOnFailure() { return systemExitOnFailure; } @Override public void beforeAbort(SystemAbortEvent event) { logger.error("System abort requested: {}", event); try { systemAbortListener.onSystemAbortEvent(event); } catch (Exception e) { logger.error("Unexpected exception from the system abort listener", e); } } public static Builder newBuilder() { return new DefaultBuilder(); } public static final class DefaultBuilder implements Builder { private MyEnvironment myEnvironment; private CodePointTracker codePointTracker; private CodeInvariants codeInvariants; private SystemLogService systemLogService; private boolean systemExitOnFailure; private SystemAbortListener systemAbortListener; private Registry registry; private Clock clock; private boolean fitEnabled; private Duration localSchedulerLoopInterval; private DefaultBuilder() { } public Builder withMyEnvironment(MyEnvironment myEnvironment) { this.myEnvironment = myEnvironment; return this; } public Builder withCodePointTracker(CodePointTracker codePointTracker) { this.codePointTracker = codePointTracker; return this; } public Builder withCodeInvariants(CodeInvariants codeInvariants) { this.codeInvariants = codeInvariants; return this; } public Builder withSystemLogService(SystemLogService systemLogService) { this.systemLogService = systemLogService; return this; } public Builder withSystemExitOnFailure(boolean systemExitOnFailure) { this.systemExitOnFailure = systemExitOnFailure; return this; } public Builder withSystemAbortListener(SystemAbortListener systemAbortListener) { this.systemAbortListener = systemAbortListener; return this; } public Builder withRegistry(Registry registry) { this.registry = registry; return this; } public Builder withClock(Clock clock) { this.clock = clock; return this; } public Builder withFitFramework(boolean fitEnabled) { this.fitEnabled = fitEnabled; return this; } public Builder withLocalSchedulerLoopInterval(Duration localSchedulerLoopInterval) { this.localSchedulerLoopInterval = localSchedulerLoopInterval; return this; } public DefaultTitusRuntime build() { if (myEnvironment == null) { myEnvironment = MyEnvironments.empty(); } if (codePointTracker == null) { codePointTracker = new LoggingCodePointTracker(); } if (codeInvariants == null) { codeInvariants = LoggingCodeInvariants.getDefault(); } if (systemLogService == null) { systemLogService = LoggingSystemLogService.getInstance(); } if (systemAbortListener == null) { systemAbortListener = LoggingSystemAbortListener.getDefault(); } if (localSchedulerLoopInterval == null) { localSchedulerLoopInterval = LOCAL_SCHEDULER_LOOP_INTERVAL_MS; } if (registry == null) { registry = new DefaultRegistry(); } if (clock == null) { clock = Clocks.system(); } return new DefaultTitusRuntime( myEnvironment, codePointTracker, codeInvariants, systemLogService, systemExitOnFailure, systemAbortListener, localSchedulerLoopInterval, registry, clock, fitEnabled ); } } }
982
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime/internal/LoggingSystemLogService.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.runtime.internal; import com.netflix.titus.common.runtime.SystemLogEvent; import com.netflix.titus.common.runtime.SystemLogService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoggingSystemLogService implements SystemLogService { private static final Logger logger = LoggerFactory.getLogger(LoggingSystemLogService.class); private static final LoggingSystemLogService INSTANCE = new LoggingSystemLogService(); public static LoggingSystemLogService getInstance() { return INSTANCE; } @Override public boolean submit(SystemLogEvent event) { switch (event.getPriority()) { case Info: logger.info("System event: {}", event); break; case Warn: logger.warn("System event: {}", event); break; case Error: case Fatal: logger.error("System event: {}", event); break; } return true; } }
983
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/runtime/internal/LoggingSystemAbortListener.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.runtime.internal; import com.netflix.titus.common.runtime.SystemAbortEvent; import com.netflix.titus.common.runtime.SystemAbortListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoggingSystemAbortListener implements SystemAbortListener { private static final Logger logger = LoggerFactory.getLogger(LoggingSystemAbortListener.class); private static final LoggingSystemAbortListener INSTANCE = new LoggingSystemAbortListener(); @Override public void onSystemAbortEvent(SystemAbortEvent event) { logger.error("JVM abort requested: {}", event); } public static LoggingSystemAbortListener getDefault() { return INSTANCE; } }
984
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/annotation/Internal.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks class, interface, etc as internal, not part of public API. */ @Retention(RetentionPolicy.CLASS) @Target({ ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) @Documented public @interface Internal { String purpose() default ""; }
985
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/annotation/Experimental.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * As there is no standard annotation of this kind, we repeat the implementation here, rather than depending * on some external library providing it. * <p> * Signifies that a public API (public class, method or field) is will almost certainly * be changed or removed in a future release. An API bearing this annotation should not * be used or relied upon in production code. APIs exposed with this annotation exist * to allow broad testing and feedback on experimental features. **/ @Retention(RetentionPolicy.CLASS) @Target({ ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) @Documented public @interface Experimental { String detail() default ""; String deadline(); }
986
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/admission/AdmissionSanitizer.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.common.model.admission; import java.util.function.Function; import java.util.function.UnaryOperator; import reactor.core.publisher.Mono; /** * Sanitizers have a MapReduce-like interface, and are executed concurrently in two phases: * <p> * 1. <tt>sanitize(input)</tt> is called on all registered {@link AdmissionSanitizer sanitizers} concurrently. The input * parameter may or may not have passed through other sanitizers, no assumptions on what data has been already changed * during the sanitization process can be made. It is safer to assume no other sanitizers should touch the same data, * and the input is the original value sent to the system. The behavior with multiple sanitizers with overlapping * updates is unspecified. * <p> * 2. The previous call returns a {@link Function} that applies a partial update, and partial updates are chained * through all sanitizers sequentially. Each sanitizer adds its partial update to the entity modified by its * predecessor in the chain. The final result includes all partial updates from all sanitizers. No assumptions should be * made on the order in which sanitizers will be called. * * @param <T> entity being sanitized */ public interface AdmissionSanitizer<T> { /** * Async method that produces clean and missing data elements to an entity. Its return should be a synchronous * function (closure) that applies all necessary updates. All heavy lifting should be done asynchronously, with the * returned <tt>apply</tt> function being cheap and only responsible for merging sanitized data back into the * entity. * * @return a closure that applies necessary changes to the entity. It may be a {@link Mono#empty()} when no changes * are to be made, or a {@link Mono#error(Throwable)} when the entity is invalid */ Mono<UnaryOperator<T>> sanitize(T entity); /** * Helper to be used when there are no multiple sanitizers to be executed concurrently. */ default Mono<T> sanitizeAndApply(T entity) { return sanitize(entity).map(update -> update.apply(entity)); } }
987
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/admission/AdmissionValidatorConfiguration.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.model.admission; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.titus.common.model.sanitizer.ValidationError; public interface AdmissionValidatorConfiguration { @DefaultValue("SOFT") String getErrorType(); default ValidationError.Type toValidatorErrorType() { return ValidationError.Type.valueOf(getErrorType().trim().toUpperCase()); } }
988
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/admission/AdmissionValidator.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.common.model.admission; import java.util.Set; import com.netflix.titus.common.model.sanitizer.ValidationError; import reactor.core.publisher.Mono; /** * An <tt>AdmissionValidator</tt> determines whether an object of the parameterized type is valid. If it finds an * object to be invalid it returns a non-empty set of {@link ValidationError}s. * * @param <T> The type of object this AdmissionValidator validates. */ public interface AdmissionValidator<T> { Mono<Set<ValidationError>> validate(T entity); /** * Returns the error type this validator will produce in the {@link AdmissionValidator#validate(Object)} method. */ ValidationError.Type getErrorType(); }
989
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/admission/ValidatorMetrics.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.common.model.admission; import java.util.Collections; import java.util.Map; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; public class ValidatorMetrics { // // Common validation codes. // public static final String REASON_DISABLED = "validationDisabled"; public static final String REASON_NOT_APPLICABLE = "notApplicable"; private static final String VALIDATOR_METRICS_ROOT = "titus.validation."; private static final String VALIDATION_RESULT_TAG = "result"; private static final String VALIDATION_RESOURCE_TAG = "resource"; private static final String VALIDATION_ERROR_TAG = "error"; private final Registry registry; private final Id validationResultId; public ValidatorMetrics(String validationName, Registry registry) { this.registry = registry; validationResultId = registry.createId(VALIDATOR_METRICS_ROOT + validationName); } public void incrementValidationSuccess(String resourceName) { registry.counter(validationResultId .withTag(VALIDATION_RESULT_TAG, "success") .withTag(VALIDATION_RESOURCE_TAG, resourceName) ).increment(); } public void incrementValidationError(String resourceName, String errorReason) { incrementValidationError(resourceName, errorReason, Collections.emptyMap()); } public void incrementValidationError(String resourceName, String errorReason, Map<String, String> ts) { registry.counter(validationResultId .withTags(ts) .withTag(VALIDATION_RESULT_TAG, "failure") .withTag(VALIDATION_RESOURCE_TAG, resourceName) .withTag(VALIDATION_ERROR_TAG, errorReason) ).increment(); } public void incrementValidationSkipped(String resourceName, String reason) { registry.counter(validationResultId .withTag(VALIDATION_RESULT_TAG, "skipped") .withTag(VALIDATION_RESOURCE_TAG, resourceName) .withTag(VALIDATION_ERROR_TAG, reason) ).increment(); } public void incrementValidationSkipped(String reason) { registry.counter(validationResultId .withTag(VALIDATION_RESULT_TAG, "skipped") .withTag(VALIDATION_ERROR_TAG, reason) ).increment(); } }
990
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/admission/TitusValidatorConfiguration.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.model.admission; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titus.validate.job") public interface TitusValidatorConfiguration extends AdmissionValidatorConfiguration { @DefaultValue("5000") int getTimeoutMs(); }
991
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/FieldSanitizer.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.model.sanitizer; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Optional; import java.util.function.Function; /** */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FieldSanitizer { /** * For a field holding an integer/long number, set this value if the field value is smaller. */ long atLeast() default Long.MIN_VALUE; /** * For a field holding an integer/long number, set this value if the field value is larger. */ long atMost() default Long.MAX_VALUE; /** * SpEL expression that should output adjusted value of the same type. */ String adjuster() default ""; /** * Instantiate sanitizer of this type, and apply it to the annotated field. */ Class<? extends Function<Object, Optional<Object>>> sanitizer() default EmptySanitizer.class; class EmptySanitizer implements Function<Object, Optional<Object>> { @Override public Optional<Object> apply(Object value) { return Optional.empty(); } } }
992
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/ClassInvariant.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.model.sanitizer; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import com.netflix.titus.common.model.sanitizer.internal.SpELClassValidator; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Annotation for expressing class level invariants written in Spring SpEL language. */ @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint(validatedBy = {SpELClassValidator.class}) public @interface ClassInvariant { /** * Condition should evaluate to true or false. */ String condition() default ""; /** * Expression that should return a map of string key/values describing fields for which validation failed. * Empty map indicates that the data are valid. */ String expr() default ""; VerifierMode mode() default VerifierMode.Permissive; String message() default "{ClassInvariant.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; /** * Defines several {@link ClassInvariant} annotations on the same element. * * @see ClassInvariant */ @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) @Retention(RUNTIME) @Documented @interface List { ClassInvariant[] value(); } }
993
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/VerifierMode.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.model.sanitizer; /** * Enum type for {@link EntitySanitizer} validation modes. Each {@link EntitySanitizer} instance runs either * in strict or permissive mode. Each {@link ClassInvariant}, and {@link FieldInvariant} validation rule is * configured with the validation mode as well, with the permissive mode as a default. For example, * if the {@link EntitySanitizer} is configured as permissive, and there is a filed with {@link ClassInvariant} annotation * with the {@link #Strict} mode, it will not be checked during the validation process. It would be however checked * if the {@link EntitySanitizer} was in the {@link #Strict} mode. */ public enum VerifierMode { /** * Most restrictive mode. Validation rules annotated as 'Strict' are only checked in the strict mode. */ Strict { @Override public boolean includes(VerifierMode mode) { return true; } }, /** * Default validation mode. Checks non strict validation rules only. */ Permissive { @Override public boolean includes(VerifierMode mode) { return mode == Permissive; } }; public abstract boolean includes(VerifierMode mode); }
994
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/EntitySanitizerUtil.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.model.sanitizer; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Collection of helper functions. */ public final class EntitySanitizerUtil { private EntitySanitizerUtil() { } public static Map<String, String> toStringMap(Collection<ValidationError> violations) { if (violations == null) { return Collections.emptyMap(); } Map<String, String> violationsMap = new HashMap<>(); for (ValidationError violation : violations) { Object message = violation.getDescription(); if (message != null) { violationsMap.put(violation.getField(), message.toString()); } } return violationsMap; } }
995
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/EntitySanitizer.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.model.sanitizer; import java.util.Optional; import java.util.Set; /** * Whenever data is exchanged with an external entity (REST, database), there is a risk, that the entity * invariants are violated. This may have adverse impact on system availability and correctness of execution. * For example, bad one entity data stored in a database, may affect all operations operating on entity collection. * <h1>Constraints</h1> * Validated/sanitized entities must be JavaBean types with single constructor. */ public interface EntitySanitizer { /** * Validate an entity and report constraint violations. * * @return validation errors or empty set if entity is valid */ <T> Set<ValidationError> validate(T entity); /** * Cleans and adds missing data elements to an entity. * * @return {@link Optional#empty()} if the entity does not require any updates, or a new, cleaned up version */ <T> Optional<T> sanitize(T entity); }
996
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/CollectionInvariants.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.model.sanitizer; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import com.netflix.titus.common.model.sanitizer.internal.CollectionValidator; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Annotation for specifying constraint(s) on collection types (lists, sets, maps, etc). */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint(validatedBy = {CollectionValidator.class}) public @interface CollectionInvariants { boolean allowNullKeys() default false; /** * Only for keys with {@link String} type. This property is ignored for other key types. */ boolean allowEmptyKeys() default true; boolean allowNullValues() default false; boolean allowDuplicateValues() default true; String message() default "{CollectionInvariants.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; /** * Defines several {@link FieldInvariant} annotations on the same element. * * @see ClassInvariant */ @Target({ElementType.FIELD}) @Retention(RUNTIME) @Documented @interface List { CollectionInvariants[] value(); } }
997
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/EntitySanitizers.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.model.sanitizer; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * A collection of predefined sanitizers. */ public class EntitySanitizers { private static final EntitySanitizer ALWAYS_VALID = new EntitySanitizer() { @Override public <T> Set<ValidationError> validate(T entity) { return Collections.emptySet(); } @Override public <T> Optional<T> sanitize(T entity) { return Optional.empty(); } }; /** * Sanitizer that accepts all data as valid, and performs no sanitization. */ public static EntitySanitizer alwaysValid() { return ALWAYS_VALID; } }
998
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/EntitySanitizerBuilder.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.model.sanitizer; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import javax.validation.ConstraintValidator; import com.netflix.titus.common.model.sanitizer.internal.DefaultEntitySanitizer; /** * {@link EntitySanitizer} builder. */ public class EntitySanitizerBuilder { public interface SanitizationFunction<T> extends Function<T, Optional<Object>> { } private Function<Class<?>, Optional<ConstraintValidator<?, ?>>> applicationValidatorFactory = type -> Optional.empty(); private VerifierMode verifierMode = VerifierMode.Permissive; private final List<Function<Object, Optional<Object>>> sanitizers = new ArrayList<>(); private Function<String, Optional<Object>> templateResolver = path -> Optional.empty(); private boolean annotationSanitizersEnabled; private boolean stdValueSanitizersEnabled; private Function<Class<?>, Boolean> includesPredicate = type -> false; private final Map<String, Method> registeredFunctions = new HashMap<>(); private final Map<String, Object> registeredBeans = new HashMap<>(); private EntitySanitizerBuilder() { } public EntitySanitizerBuilder verifierMode(VerifierMode verifierMode) { this.verifierMode = verifierMode; return this; } /** * For nested objects to be validated recursively they must be explicitly registered with the {@link EntitySanitizer}. * This is accomplished by registering one or more predicate functions. A predicate function returns true * if an entity should be validated, false otherwise. Multiple predicates are joined by logical 'or' operator. */ public EntitySanitizerBuilder processEntities(Function<Class<?>, Boolean> includesPredicate) { final Function<Class<?>, Boolean> previous = includesPredicate; this.includesPredicate = type -> previous.apply(type) || includesPredicate.apply(type); return this; } public EntitySanitizerBuilder addValidatorFactory(Function<Class<?>, Optional<ConstraintValidator<?, ?>>> newValidatorFactory) { Function<Class<?>, Optional<ConstraintValidator<?, ?>>> previous = applicationValidatorFactory; this.applicationValidatorFactory = type -> { Optional<ConstraintValidator<?, ?>> result = previous.apply(type); if (!result.isPresent()) { return newValidatorFactory.apply(type); } return result; }; return this; } /** * Add a new data sanitizer. Sanitizers are executed in the same order as they are added. */ public EntitySanitizerBuilder addSanitizer(SanitizationFunction<Object> sanitizer) { sanitizers.add(entity -> Optional.of(sanitizer.apply(entity))); return this; } /** * Add a new data sanitizer for a specific data type. */ public <T> EntitySanitizerBuilder addSanitizer(Class<T> type, SanitizationFunction<T> typeSanitizer) { sanitizers.add(entity -> entity.getClass().isAssignableFrom(type) ? typeSanitizer.apply((T) entity) : Optional.empty() ); return this; } public EntitySanitizerBuilder enableAnnotationSanitizers() { this.annotationSanitizersEnabled = true; return this; } /** * Enables basic data type sanitization: * <ul> * <li>string - trim or replace null with empty string</li> * </ul> */ public EntitySanitizerBuilder enableStdValueSanitizers() { this.stdValueSanitizersEnabled = true; return this; } /** * Adding template objects, implicitly enables template based sanitization. If a sanitized entity misses a value, the * value will be copied from its corresponding template. */ public EntitySanitizerBuilder addTemplateResolver(Function<String, Optional<Object>> templateResolver) { Function<String, Optional<Object>> previous = templateResolver; this.templateResolver = path -> { Optional<Object> result = previous.apply(path); if (!result.isPresent()) { return templateResolver.apply(path); } return result; }; return this; } /** * Make the function available via the provided alias. */ public EntitySanitizerBuilder registerFunction(String alias, Method function) { registeredFunctions.put(alias, function); return this; } /** * Make the JavaBean available via the provided alias. */ public EntitySanitizerBuilder registerBean(String alias, Object object) { registeredBeans.put(alias, object); return this; } public EntitySanitizer build() { return new DefaultEntitySanitizer(verifierMode, sanitizers, annotationSanitizersEnabled, stdValueSanitizersEnabled, includesPredicate, templateResolver, registeredFunctions, registeredBeans, applicationValidatorFactory); } /** * Empty {@link EntitySanitizerBuilder}. */ public static EntitySanitizerBuilder newBuilder() { return new EntitySanitizerBuilder(); } /** * Pre-initialized {@link EntitySanitizerBuilder} with all standard features enabled. */ public static EntitySanitizerBuilder stdBuilder() { return new EntitySanitizerBuilder() .enableStdValueSanitizers() .enableAnnotationSanitizers(); } }
999