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/util/collections
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections/index/Group.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.util.collections.index; import java.util.Map; /** * Grouping of a collection values by an arbitrary grouping key. * {@link Group} object is immutable. Changes to a group produce new copies of it. */ public interface Group<GROUP_KEY, PRIMARY_KEY, VALUE> { /** * @return immutable collection */ Map<GROUP_KEY, Map<PRIMARY_KEY, VALUE>> get(); }
800
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections/index/DefaultGroup.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.util.collections.index; import java.util.Collection; import java.util.Map; import java.util.function.Predicate; import com.netflix.titus.common.util.CollectionsExt; import org.pcollections.HashTreePMap; import org.pcollections.PMap; class DefaultGroup<GROUP_KEY, PRIMARY_KEY, INPUT, OUTPUT> implements Group<GROUP_KEY, PRIMARY_KEY, OUTPUT> { private final IndexSpec<GROUP_KEY, PRIMARY_KEY, INPUT, OUTPUT> spec; private final PMap<PRIMARY_KEY, GROUP_KEY> primaryKeyToGroupKey; private final PMap<GROUP_KEY, PMap<PRIMARY_KEY, OUTPUT>> indexedValues; DefaultGroup(IndexSpec<GROUP_KEY, PRIMARY_KEY, INPUT, OUTPUT> spec, PMap<PRIMARY_KEY, GROUP_KEY> primaryKeyToGroupKey, PMap<GROUP_KEY, PMap<PRIMARY_KEY, OUTPUT>> indexedValues) { this.spec = spec; this.primaryKeyToGroupKey = primaryKeyToGroupKey; this.indexedValues = indexedValues; } static <GROUP_KEY, PRIMARY_KEY, INPUT, OUTPUT> DefaultGroup<GROUP_KEY, PRIMARY_KEY, INPUT, OUTPUT> newEmpty(IndexSpec<GROUP_KEY, PRIMARY_KEY, INPUT, OUTPUT> spec) { return new DefaultGroup<>(spec, HashTreePMap.empty(), HashTreePMap.empty()); } @Override public Map<GROUP_KEY, Map<PRIMARY_KEY, OUTPUT>> get() { Map raw = indexedValues; return raw; } DefaultGroup<GROUP_KEY, PRIMARY_KEY, INPUT, OUTPUT> add(Collection<INPUT> values) { if (CollectionsExt.isNullOrEmpty(values)) { return this; } PMap<GROUP_KEY, PMap<PRIMARY_KEY, OUTPUT>> newIndexedValues = indexedValues; PMap<PRIMARY_KEY, GROUP_KEY> newPrimaryKeyToGroupKey = primaryKeyToGroupKey; for (INPUT value : values) { Predicate<INPUT> filter = spec.getFilter(); if (!filter.test(value)) { continue; } GROUP_KEY indexKey = spec.getIndexKeyExtractor().apply(value); PRIMARY_KEY primaryKey = spec.getPrimaryKeyExtractor().apply(value); OUTPUT output = spec.getTransformer().apply(indexKey, value); if (indexKey != null && primaryKey != null) { PMap<PRIMARY_KEY, OUTPUT> byIndexKey = newIndexedValues.get(indexKey); if (byIndexKey == null) { newIndexedValues = newIndexedValues.plus(indexKey, HashTreePMap.singleton(primaryKey, output)); } else { newIndexedValues = newIndexedValues.plus(indexKey, byIndexKey.plus(primaryKey, output)); } newPrimaryKeyToGroupKey = newPrimaryKeyToGroupKey.plus(primaryKey, indexKey); } } return new DefaultGroup<>(spec, newPrimaryKeyToGroupKey, newIndexedValues); } DefaultGroup<GROUP_KEY, PRIMARY_KEY, INPUT, OUTPUT> remove(Collection<PRIMARY_KEY> keys) { if (CollectionsExt.isNullOrEmpty(keys)) { return this; } PMap<GROUP_KEY, PMap<PRIMARY_KEY, OUTPUT>> newIndexedValues = indexedValues; PMap<PRIMARY_KEY, GROUP_KEY> newPrimaryKeyToGroupKey = primaryKeyToGroupKey; for (PRIMARY_KEY primaryKey : keys) { GROUP_KEY indexKey = primaryKeyToGroupKey.get(primaryKey); if (indexKey != null) { PMap<PRIMARY_KEY, OUTPUT> byIndexKey = newIndexedValues.get(indexKey); if (byIndexKey != null && byIndexKey.containsKey(primaryKey)) { PMap<PRIMARY_KEY, OUTPUT> byPrimaryKey = byIndexKey.minus(primaryKey); if (byPrimaryKey.isEmpty()) { newIndexedValues = newIndexedValues.minus(indexKey); } else { newIndexedValues = newIndexedValues.plus(indexKey, byPrimaryKey); } newPrimaryKeyToGroupKey = newPrimaryKeyToGroupKey.minus(primaryKey); } } } // If nothing changed, return this the some object. if (newPrimaryKeyToGroupKey == primaryKeyToGroupKey) { return this; } return new DefaultGroup<>(spec, newPrimaryKeyToGroupKey, newIndexedValues); } }
801
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections/index/IndexSetMetrics.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.io.Closeable; import java.util.ArrayList; import java.util.List; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.patterns.PolledMeter; /** * {@link IndexSet} metrics collector. */ class IndexSetMetrics implements Closeable { private final Registry registry; private final List<Id> ids; IndexSetMetrics(Id root, IndexSetHolder<?, ?> indexSetHolder, Registry registry) { this.registry = registry; List<Id> ids = new ArrayList<>(); // Groups indexSetHolder.getIndexSet().getGroups().forEach((id, group) -> { Id metricId = root.withTags("kind", "group", "indexId", id); ids.add(metricId); PolledMeter.using(registry).withId(metricId).monitorValue(indexSetHolder, h -> { Group<?, ?, ?> g = h.getIndexSet().getGroup(id); return g != null ? g.get().size() : 0; }); }); // Indexes indexSetHolder.getIndexSet().getOrders().forEach((id, index) -> { Id metricId = root.withTags("kind", "index", "indexId", id); ids.add(metricId); PolledMeter.using(registry).withId(metricId).monitorValue(indexSetHolder, h -> { Order<Object> i = h.getIndexSet().getOrder(id); return i != null ? i.orderedList().size() : 0; }); }); this.ids = ids; } @Override public void close() { ids.forEach(id -> PolledMeter.remove(registry, id)); } }
802
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections/index/DefaultIndex.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import com.netflix.titus.common.util.CollectionsExt; import org.pcollections.HashTreePMap; import org.pcollections.HashTreePSet; import org.pcollections.PMap; import org.pcollections.PSet; public class DefaultIndex<UNIQUE_INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> implements Index<UNIQUE_INDEX_KEY, OUTPUT> { private final IndexSpec<UNIQUE_INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> spec; private final PMap<PRIMARY_KEY, PSet<UNIQUE_INDEX_KEY>> primaryKeyToIndexKeys; private final PMap<UNIQUE_INDEX_KEY, OUTPUT> indexedValues; DefaultIndex(IndexSpec<UNIQUE_INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> spec, PMap<PRIMARY_KEY, PSet<UNIQUE_INDEX_KEY>> primaryKeyToIndexKeys, PMap<UNIQUE_INDEX_KEY, OUTPUT> indexedValues) { this.spec = spec; this.primaryKeyToIndexKeys = primaryKeyToIndexKeys; this.indexedValues = indexedValues; } static <UNIQUE_INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> DefaultIndex<UNIQUE_INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> newEmpty(IndexSpec<UNIQUE_INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> spec) { return new DefaultIndex<>(spec, HashTreePMap.empty(), HashTreePMap.empty()); } @Override public Map<UNIQUE_INDEX_KEY, OUTPUT> get() { return indexedValues; } DefaultIndex<UNIQUE_INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> add(Collection<INPUT> values) { if (CollectionsExt.isNullOrEmpty(values)) { return this; } PMap<PRIMARY_KEY, PSet<UNIQUE_INDEX_KEY>> newPrimaryKeyToIndexKeys = primaryKeyToIndexKeys; PMap<UNIQUE_INDEX_KEY, OUTPUT> newIndexedValues = indexedValues; for (INPUT value : values) { Predicate<INPUT> filter = spec.getFilter(); if (!filter.test(value)) { continue; } Set<UNIQUE_INDEX_KEY> indexKeys = spec.getIndexKeysExtractor().apply(value); PRIMARY_KEY primaryKey = spec.getPrimaryKeyExtractor().apply(value); if (primaryKey != null) { PSet<UNIQUE_INDEX_KEY> currentKeys = primaryKeyToIndexKeys.get(primaryKey); if (CollectionsExt.isNullOrEmpty(indexKeys)) { if (!CollectionsExt.isNullOrEmpty(currentKeys)) { newPrimaryKeyToIndexKeys = newPrimaryKeyToIndexKeys.plus(primaryKey, HashTreePSet.empty()); newIndexedValues = newIndexedValues.minusAll(currentKeys); } } else { newPrimaryKeyToIndexKeys = newPrimaryKeyToIndexKeys.plus(primaryKey, HashTreePSet.from(indexKeys)); for (UNIQUE_INDEX_KEY key : indexKeys) { newIndexedValues = newIndexedValues.plus(key, spec.getTransformer().apply(key, value)); } if (!CollectionsExt.isNullOrEmpty(currentKeys)) { for (UNIQUE_INDEX_KEY key : currentKeys) { if (!indexKeys.contains(key)) { newIndexedValues = newIndexedValues.minus(key); } } } } } } return new DefaultIndex<>(spec, newPrimaryKeyToIndexKeys, newIndexedValues); } DefaultIndex<UNIQUE_INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> remove(Collection<PRIMARY_KEY> keys) { if (CollectionsExt.isNullOrEmpty(keys)) { return this; } PMap<PRIMARY_KEY, PSet<UNIQUE_INDEX_KEY>> newPrimaryKeyToIndexKeys = primaryKeyToIndexKeys; PMap<UNIQUE_INDEX_KEY, OUTPUT> newIndexedValues = indexedValues; for (PRIMARY_KEY primaryKey : keys) { PSet<UNIQUE_INDEX_KEY> indexKeys = newPrimaryKeyToIndexKeys.get(primaryKey); newPrimaryKeyToIndexKeys = newPrimaryKeyToIndexKeys.minus(primaryKey); if (indexKeys != null) { newIndexedValues = newIndexedValues.minusAll(indexKeys); } } return new DefaultIndex<>(spec, newPrimaryKeyToIndexKeys, newIndexedValues); } }
803
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections/index/IndexSpec.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.util.collections.index; import java.util.Comparator; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import com.google.common.base.Preconditions; import com.netflix.titus.common.util.FunctionExt; /** * A descriptor for a single {@link Group} or {@link Order} instance. */ public class IndexSpec<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> { private final BiFunction<INDEX_KEY, INPUT, OUTPUT> transformer; private final Function<INPUT, INDEX_KEY> indexKeyExtractor; private final Function<INPUT, Set<INDEX_KEY>> indexKeysExtractor; private final Function<INPUT, PRIMARY_KEY> primaryKeyExtractor; private final Comparator<INDEX_KEY> indexKeyComparator; private final Comparator<PRIMARY_KEY> primaryKeyComparator; private final Predicate<INPUT> filter; IndexSpec(BiFunction<INDEX_KEY, INPUT, OUTPUT> transformer, Function<INPUT, INDEX_KEY> indexKeyExtractor, Function<INPUT, Set<INDEX_KEY>> indexKeysExtractor, Function<INPUT, PRIMARY_KEY> primaryKeyExtractor, Comparator<INDEX_KEY> indexKeyComparator, Comparator<PRIMARY_KEY> primaryKeyComparator, Predicate<INPUT> filter) { this.transformer = transformer; this.indexKeyExtractor = indexKeyExtractor; this.indexKeysExtractor = indexKeysExtractor; this.primaryKeyExtractor = primaryKeyExtractor; this.indexKeyComparator = indexKeyComparator; this.primaryKeyComparator = primaryKeyComparator; this.filter = filter; } public BiFunction<INDEX_KEY, INPUT, OUTPUT> getTransformer() { return transformer; } Function<INPUT, INDEX_KEY> getIndexKeyExtractor() { return indexKeyExtractor; } Function<INPUT, Set<INDEX_KEY>> getIndexKeysExtractor() { return indexKeysExtractor; } Function<INPUT, PRIMARY_KEY> getPrimaryKeyExtractor() { return primaryKeyExtractor; } public Comparator<INDEX_KEY> getIndexKeyComparator() { return indexKeyComparator; } public Comparator<PRIMARY_KEY> getPrimaryKeyComparator() { return primaryKeyComparator; } public Predicate<INPUT> getFilter() { return filter; } public static <INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> Builder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> newBuilder() { return new Builder<>(); } public static final class Builder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> { private BiFunction<INDEX_KEY, INPUT, OUTPUT> transformer; private Function<INPUT, INDEX_KEY> indexKeyExtractor; private Function<INPUT, Set<INDEX_KEY>> indexKeysExtractor; private Function<INPUT, PRIMARY_KEY> primaryKeyExtractor; private Comparator<INDEX_KEY> indexKeyComparator; private Comparator<PRIMARY_KEY> primaryKeyComparator; private Predicate<INPUT> filter; private Builder() { } public Builder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> withTransformer(BiFunction<INDEX_KEY, INPUT, OUTPUT> transformer) { this.transformer = transformer; return this; } public Builder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> withIndexKeyExtractor(Function<INPUT, INDEX_KEY> indexKeyExtractor) { this.indexKeyExtractor = indexKeyExtractor; return this; } public Builder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> withIndexKeysExtractor(Function<INPUT, Set<INDEX_KEY>> indexKeysExtractor) { this.indexKeysExtractor = indexKeysExtractor; return this; } public Builder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> withPrimaryKeyExtractor(Function<INPUT, PRIMARY_KEY> primaryKeyExtractor) { this.primaryKeyExtractor = primaryKeyExtractor; return this; } public Builder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> withIndexKeyComparator(Comparator<INDEX_KEY> indexKeyComparator) { this.indexKeyComparator = indexKeyComparator; return this; } public Builder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> withPrimaryKeyComparator(Comparator<PRIMARY_KEY> primaryKeyComparator) { this.primaryKeyComparator = primaryKeyComparator; return this; } public Builder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> withFilter(Predicate<INPUT> filter) { this.filter = filter; return this; } public IndexSpec<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> build() { Preconditions.checkState(indexKeyExtractor != null || indexKeysExtractor != null, "Both index key and index keys extractors not set"); Preconditions.checkNotNull(primaryKeyExtractor, "Primary key extractor not set"); Preconditions.checkNotNull(indexKeyComparator, "Index key comparator not set"); Preconditions.checkNotNull(primaryKeyComparator, "Primary key comparator not set"); if (transformer == null) { transformer = (key, input) -> (OUTPUT) input; } if (filter == null) { filter = FunctionExt.alwaysTrue(); } return new IndexSpec<>(transformer, indexKeyExtractor, indexKeysExtractor, primaryKeyExtractor, indexKeyComparator, primaryKeyComparator, filter); } } }
804
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections/index/DefaultOrder.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.util.collections.index; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.netflix.titus.common.util.CollectionsExt; import org.pcollections.HashTreePMap; import org.pcollections.PMap; import org.pcollections.PVector; import org.pcollections.TreePVector; public class DefaultOrder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> implements Order<OUTPUT> { private final IndexSpec<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> spec; private final PMap<PRIMARY_KEY, INDEX_KEY> primaryKeyToIndexKey; private final PVector<ListItem<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT>> sorted; private final List<OUTPUT> result; private final ListItemComparator<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> listItemComparator; DefaultOrder(IndexSpec<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> spec, ListItemComparator<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> listItemComparator, PMap<PRIMARY_KEY, INDEX_KEY> primaryKeyToIndexKey, PVector<ListItem<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT>> sorted) { this.spec = spec; this.listItemComparator = listItemComparator; this.primaryKeyToIndexKey = primaryKeyToIndexKey; this.sorted = sorted; this.result = new AbstractList<OUTPUT>() { @Override public OUTPUT get(int index) { ListItem<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> item = sorted.get(index); return item == null ? null : item.getOutput(); } @Override public int size() { return sorted.size(); } }; } static <INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> DefaultOrder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> newEmpty(IndexSpec<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> spec) { return new DefaultOrder<>(spec, new ListItemComparator<>(spec), HashTreePMap.empty(), TreePVector.empty()); } @Override public List<OUTPUT> orderedList() { return result; } DefaultOrder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> add(Collection<INPUT> values) { List<INPUT> filtered = filter(values); if (CollectionsExt.isNullOrEmpty(filtered)) { return this; } PVector<ListItem<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT>> newSorted = sorted; PMap<PRIMARY_KEY, INDEX_KEY> newPrimaryKeyToIndexKey = primaryKeyToIndexKey; for (INPUT input : filtered) { INDEX_KEY indexKey = spec.getIndexKeyExtractor().apply(input); PRIMARY_KEY primaryKey = spec.getPrimaryKeyExtractor().apply(input); int pos = findKeyPosition(indexKey, primaryKey, newSorted); OUTPUT output = spec.getTransformer().apply(indexKey, input); ListItem<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> newItem = new ListItem<>(indexKey, primaryKey, input, output); if (pos >= 0) { // Override existing item. newSorted = newSorted.minus(pos).plus(pos, newItem); } else { int insertionPoint = -(pos + 1); newSorted = newSorted.plus(insertionPoint, newItem); } newPrimaryKeyToIndexKey = newPrimaryKeyToIndexKey.plus(primaryKey, indexKey); } return new DefaultOrder<>(spec, listItemComparator, newPrimaryKeyToIndexKey, newSorted); } DefaultOrder<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> remove(Collection<PRIMARY_KEY> primaryKeys) { if (CollectionsExt.isNullOrEmpty(primaryKeys)) { return this; } PVector<ListItem<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT>> newSorted = sorted; PMap<PRIMARY_KEY, INDEX_KEY> newPrimaryKeyToIndexKey = primaryKeyToIndexKey; for (PRIMARY_KEY primaryKey : primaryKeys) { INDEX_KEY indexKey = primaryKeyToIndexKey.get(primaryKey); if (indexKey != null) { int pos = findKeyPosition(indexKey, primaryKey, newSorted); if (pos >= 0) { // Remove existing item. newSorted = newSorted.minus(pos); newPrimaryKeyToIndexKey = newPrimaryKeyToIndexKey.minus(primaryKey); } } } return new DefaultOrder<>(spec, listItemComparator, newPrimaryKeyToIndexKey, newSorted); } private int findKeyPosition(INDEX_KEY indexKey, PRIMARY_KEY primaryKey, PVector<ListItem<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT>> sorted) { return PCollectionUtil.binarySearch(sorted, new ListItem<>(indexKey, primaryKey, null, null), listItemComparator); } private List<INPUT> filter(Collection<INPUT> values) { if (CollectionsExt.isNullOrEmpty(values)) { return Collections.emptyList(); } // Filter List<INPUT> filtered = new ArrayList<>(); for (INPUT value : values) { if (spec.getFilter().test(value)) { filtered.add(value); } } return filtered; } private static class ListItem<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> { private final INDEX_KEY indexKey; private final PRIMARY_KEY primaryKey; private final INPUT input; private final OUTPUT output; private ListItem(INDEX_KEY indexKey, PRIMARY_KEY primaryKey, INPUT input, OUTPUT output) { this.indexKey = indexKey; this.primaryKey = primaryKey; this.input = input; this.output = output; } private INDEX_KEY getIndexKey() { return indexKey; } private PRIMARY_KEY getPrimaryKey() { return primaryKey; } private INPUT getInput() { return input; } private OUTPUT getOutput() { return output; } } private static class ListItemComparator<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> implements Comparator<ListItem<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT>> { private final IndexSpec<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> spec; public ListItemComparator(IndexSpec<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> spec) { this.spec = spec; } @Override public int compare(ListItem<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> o1, ListItem<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> o2) { if (o1 == o2) { return 0; } int r = spec.getIndexKeyComparator().compare(o1.getIndexKey(), o2.getIndexKey()); if (r != 0) { return r; } return spec.getPrimaryKeyComparator().compare(o1.getPrimaryKey(), o2.getPrimaryKey()); } } }
805
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections/index/IndexSetHolder.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.util.Collection; /** * {@link IndexSet} is immutable. {@link IndexSetHolder} provides a wrapper that keep the last version of the index. */ public interface IndexSetHolder<PRIMARY_KEY, INPUT> { IndexSet<PRIMARY_KEY, INPUT> getIndexSet(); void add(Collection<INPUT> values); void remove(Collection<PRIMARY_KEY> values); }
806
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections/index/IndexSet.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.util.collections.index; import java.util.Collection; import java.util.Map; public interface IndexSet<PRIMARY_KEY, INPUT> { Map<String, Group<?, PRIMARY_KEY, ?>> getGroups(); <GROUP_KEY, OUTPUT> Group<GROUP_KEY, PRIMARY_KEY, OUTPUT> getGroup(String groupId); Map<String, Index<?, ?>> getIndexes(); <UNIQUE_INDEX_KEY, OUTPUT> Index<UNIQUE_INDEX_KEY, OUTPUT> getIndex(String indexId); Map<String, Order<?>> getOrders(); <OUTPUT> Order<OUTPUT> getOrder(String orderId); IndexSet<PRIMARY_KEY, INPUT> add(Collection<INPUT> values); IndexSet<PRIMARY_KEY, INPUT> remove(Collection<PRIMARY_KEY> values); }
807
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections/index/DefaultIndexSet.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.util.collections.index; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; class DefaultIndexSet<PRIMARY_KEY, INPUT> implements IndexSet<PRIMARY_KEY, INPUT> { private final Map<String, DefaultGroup<?, PRIMARY_KEY, INPUT, ?>> groups; private final Map<String, DefaultIndex<?, PRIMARY_KEY, INPUT, ?>> indexes; private final Map<String, DefaultOrder<?, PRIMARY_KEY, INPUT, ?>> orders; DefaultIndexSet(Map<String, DefaultGroup<?, PRIMARY_KEY, INPUT, ?>> groups, Map<String, DefaultIndex<?, PRIMARY_KEY, INPUT, ?>> indexes, Map<String, DefaultOrder<?, PRIMARY_KEY, INPUT, ?>> orders) { this.groups = groups; this.indexes = indexes; this.orders = orders; } @Override public Map<String, Group<?, PRIMARY_KEY, ?>> getGroups() { return (Map) groups; } @Override public <INDEX_KEY, OUTPUT> Group<INDEX_KEY, PRIMARY_KEY, OUTPUT> getGroup(String groupId) { return (Group<INDEX_KEY, PRIMARY_KEY, OUTPUT>) groups.get(groupId); } @Override public Map<String, Index<?, ?>> getIndexes() { return (Map) indexes; } @Override public <UNIQUE_INDEX_KEY, OUTPUT> Index<UNIQUE_INDEX_KEY, OUTPUT> getIndex(String indexId) { return (Index<UNIQUE_INDEX_KEY, OUTPUT>) indexes.get(indexId); } @Override public Map<String, Order<?>> getOrders() { return (Map) orders; } @Override public <OUTPUT> Order<OUTPUT> getOrder(String orderId) { return (Order<OUTPUT>) orders.get(orderId); } @Override public IndexSet<PRIMARY_KEY, INPUT> add(Collection<INPUT> values) { Map<String, DefaultGroup<?, PRIMARY_KEY, INPUT, ?>> newGroups; if (groups.isEmpty()) { newGroups = Collections.emptyMap(); } else { newGroups = new HashMap<>(); groups.forEach((groupId, group) -> newGroups.put(groupId, group.add(values))); } Map<String, DefaultIndex<?, PRIMARY_KEY, INPUT, ?>> newIndexes; if (indexes.isEmpty()) { newIndexes = Collections.emptyMap(); } else { newIndexes = new HashMap<>(); indexes.forEach((indexId, index) -> newIndexes.put(indexId, index.add(values))); } Map<String, DefaultOrder<?, PRIMARY_KEY, INPUT, ?>> newOrders; if (orders.isEmpty()) { newOrders = Collections.emptyMap(); } else { newOrders = new HashMap<>(); orders.forEach((indexId, index) -> newOrders.put(indexId, index.add(values))); } return new DefaultIndexSet<>(newGroups, newIndexes, newOrders); } @Override public IndexSet<PRIMARY_KEY, INPUT> remove(Collection<PRIMARY_KEY> primaryKeys) { Map<String, DefaultGroup<?, PRIMARY_KEY, INPUT, ?>> newGroups; if (groups.isEmpty()) { newGroups = Collections.emptyMap(); } else { newGroups = new HashMap<>(); groups.forEach((groupId, group) -> newGroups.put(groupId, group.remove(primaryKeys))); } Map<String, DefaultIndex<?, PRIMARY_KEY, INPUT, ?>> newIndexes; if (indexes.isEmpty()) { newIndexes = Collections.emptyMap(); } else { newIndexes = new HashMap<>(); indexes.forEach((indexId, index) -> newIndexes.put(indexId, index.remove(primaryKeys))); } Map<String, DefaultOrder<?, PRIMARY_KEY, INPUT, ?>> newOrders; if (orders.isEmpty()) { newOrders = Collections.emptyMap(); } else { newOrders = new HashMap<>(); orders.forEach((indexId, index) -> newOrders.put(indexId, index.remove(primaryKeys))); } return new DefaultIndexSet<>(newGroups, newIndexes, newOrders); } }
808
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections/index/IndexSetHolderConcurrent.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.collections.index; import java.util.Collection; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.atomic.AtomicLong; /** * Thread safe implementation of {@link IndexSetHolder}, where updates may happen concurrently. * <p> * Based on: https://akarnokd.blogspot.com/2015/05/operator-concurrency-primitives_9.html */ public class IndexSetHolderConcurrent<PRIMARY_KEY, INPUT> implements IndexSetHolder<PRIMARY_KEY, INPUT> { private volatile IndexSet<PRIMARY_KEY, INPUT> indexSet; private final BlockingQueue<Runnable> queue = new LinkedBlockingDeque<>(); private final AtomicLong wip = new AtomicLong(); public IndexSetHolderConcurrent(IndexSet<PRIMARY_KEY, INPUT> indexSet) { this.indexSet = indexSet; } @Override public IndexSet<PRIMARY_KEY, INPUT> getIndexSet() { return indexSet; } @Override public void add(Collection<INPUT> values) { queue.add(() -> indexSet = indexSet.add(values)); drain(); } @Override public void remove(Collection<PRIMARY_KEY> values) { queue.add(() -> indexSet = indexSet.remove(values)); drain(); } private void drain() { if (wip.getAndIncrement() == 0) { do { wip.lazySet(1); Runnable action; while ((action = queue.poll()) != null) { action.run(); } } while (wip.decrementAndGet() != 0); } } }
809
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/collections/index/PCollectionUtil.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.util.collections.index; import java.util.Comparator; import java.util.List; import com.netflix.titus.common.util.CollectionsExt; class PCollectionUtil { /** * {@link java.util.Collections#binarySearch(List, Object)} expects the provided collection to implement * {@link java.util.RandomAccess} for non-iterator implementation. Otherwise it does linear scan. * We reimplement it here for {@link org.pcollections.PVector} which has log(n) time for value retrieval at an index * (see https://en.wikipedia.org/wiki/Binary_search_algorithm). */ public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> comparator) { if (CollectionsExt.isNullOrEmpty(list)) { return -1; } int left = 0; int right = list.size() - 1; while (left <= right) { int pos = (left + right) / 2; T value = list.get(pos); int c = comparator.compare(value, key); if (c < 0) { left = pos + 1; } else if (c > 0) { right = pos - 1; } else { return pos; } } return -(left + 1); } }
810
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/event/EventPropagationUtil.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.util.event; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.StringExt; /** * Event propagation tracking over many channels. Sever side and client side timestamps are recorded in pairs. * After snapshot example for TJC event with updateTimestamp=1 send to a client connected to Federation endpoint: <br/> * <code> * event.propagation.stages: before=10,after=30;before=50,after=70;before=100,after=120</li> * </code> * Latencies: * <ul> * <li>TJC processing latency = 10 - 1 = 9ms</li> * <li>TJC -> Gateway latency = 30 - 10 = 20ms</li> * <li>Gateway processing latency = 50 - 30 = 20ms</li> * <li>Gateway -> Federation latency = 70 - 50 = 20ms</li> * <li>Federation processing latency = 100 - 70 = 30ms</li> * <li>Federation -> client latency = 100 - 120 = 20ms</li> * </ul> * Total event propagation latency = 119ms * <p> * For events generated before the snapshot marker, we cannot use lastUpdateTimestamp as a starting point. These * events will miss the TJC processing latency. */ public class EventPropagationUtil { public static final String EVENT_ATTRIBUTE_PROPAGATION_STAGES = "event.propagation.stages"; public static final int MAX_LENGTH_EVENT_PROPAGATION_STAGE = 500; public static String buildNextStage(String id, Map<String, String> attributes, long beforeTimestamp, long afterTimestamp) { String stages = attributes.get(EVENT_ATTRIBUTE_PROPAGATION_STAGES); long delaysMs = afterTimestamp - beforeTimestamp; String nextStagePayload = id + "(" + delaysMs + "ms):" + "before=" + beforeTimestamp + ",after=" + afterTimestamp; if (stages != null && stages.length() < MAX_LENGTH_EVENT_PROPAGATION_STAGE) { return stages + ";" + nextStagePayload; } return nextStagePayload; } public static Map<String, String> copyAndAddNextStage(String id, Map<String, String> attributes, long beforeTimestamp, long afterTimestamp) { String nextStages = buildNextStage(id, attributes, beforeTimestamp, afterTimestamp); return CollectionsExt.copyAndAdd(attributes, EVENT_ATTRIBUTE_PROPAGATION_STAGES, nextStages); } /** * Parse the event propagation data stored in {@link #EVENT_ATTRIBUTE_PROPAGATION_STAGES}. * The delay estimation is based on timestamps. As clocks may not be perfectly synchronized between machines, it * is only estimate. */ public static Optional<EventPropagationTrace> parseTrace(Map<String, String> attributes, boolean snapshot, long lastUpdateTimestamp, List<String> labels) { String stages = attributes.get(EVENT_ATTRIBUTE_PROPAGATION_STAGES); if (StringExt.isEmpty(stages)) { return Optional.empty(); } Map<String, Long> stagesMap = new HashMap<>(); int labelPos = 0; long previousTimestamp = lastUpdateTimestamp; try { String[] stagesList = stages.split(";"); for (String beforeAfter : stagesList) { if (labelPos >= labels.size()) { break; } String[] pair = beforeAfter.split(","); if (pair.length != 2) { return Optional.empty(); } String[] before = pair[0].split("="); if (before.length != 2) { return Optional.empty(); } long beforeTimestamp = Long.parseLong(before[1]); String[] after = pair[1].split("="); if (after.length != 2) { return Optional.empty(); } long afterTimestamp = Long.parseLong(after[1]); long internalDelay; if (labelPos == 0) { if (snapshot) { // Snapshot replays pre-existing data so we cannot use lastUpdateTimestamp to asses propagation latency. internalDelay = 0; } else { internalDelay = lastUpdateTimestamp >= 0 ? beforeTimestamp - lastUpdateTimestamp : 0; } } else { internalDelay = beforeTimestamp - previousTimestamp; } // If clocks are not the same, we can get negative delay. The best we can do is to make it is not less than zero. stagesMap.put(labels.get(labelPos++), Math.max(0, internalDelay)); if (labelPos >= labels.size()) { break; } // If clocks are not the same, we can get negative delay. The best we can do is to make it is not less than zero. stagesMap.put(labels.get(labelPos++), Math.max(0, afterTimestamp - beforeTimestamp)); previousTimestamp = afterTimestamp; } } catch (Exception e) { // Catch anything to prevent error propagation return Optional.empty(); } return Optional.of(new EventPropagationTrace(snapshot, stagesMap)); } }
811
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/event/EventPropagationTrace.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.util.event; import java.util.Map; import java.util.Objects; public class EventPropagationTrace { private final boolean snapshot; private final Map<String, Long> stages; private final long totalDelayMs; public EventPropagationTrace(boolean snapshot, Map<String, Long> stages) { this.snapshot = snapshot; this.stages = stages; long total = 0; for(Long value : stages.values()) { total += value; } this.totalDelayMs = total; } public boolean isSnapshot() { return snapshot; } public Map<String, Long> getStages() { return stages; } public long getTotalDelayMs() { return totalDelayMs; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EventPropagationTrace that = (EventPropagationTrace) o; return snapshot == that.snapshot && totalDelayMs == that.totalDelayMs && Objects.equals(stages, that.stages); } @Override public int hashCode() { return Objects.hash(snapshot, stages, totalDelayMs); } @Override public String toString() { return "EventPropagationTrace{" + "snapshot=" + snapshot + ", stages=" + stages + ", totalDelayMs=" + totalDelayMs + '}'; } }
812
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/event/EventPropagationMetrics.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,set * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.event; import java.util.HashMap; import java.util.List; import java.util.Map; import com.netflix.spectator.api.Id; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.spectator.SpectatorExt; import com.netflix.titus.common.util.spectator.ValueRangeCounter; public class EventPropagationMetrics { private static final long[] LEVELS = new long[]{1, 10, 50, 100, 200, 500, 1_000, 2_000, 5_000, 10_000, 20_000, 60_000}; private final List<String> stageNames; private final Map<String, ValueRangeCounter> bucketCounters; private final Map<String, ValueRangeCounter> cumulativeCounters; public EventPropagationMetrics(Id root, List<String> stageNames, TitusRuntime titusRuntime) { this.stageNames = stageNames; this.bucketCounters = buildStageCounterMap(root, stageNames, titusRuntime, "inStage"); this.cumulativeCounters = buildStageCounterMap(root, stageNames, titusRuntime, "toStage"); } public void record(EventPropagationTrace trace) { long sum = 0; for (String name : stageNames) { Long delayMs = trace.getStages().get(name); long recordedDelayMs = delayMs == null ? 0L : delayMs; sum += recordedDelayMs; bucketCounters.get(name).recordLevel(recordedDelayMs); cumulativeCounters.get(name).recordLevel(sum); } } private Map<String, ValueRangeCounter> buildStageCounterMap(Id root, List<String> stageNames, TitusRuntime titusRuntime, String kind) { Map<String, ValueRangeCounter> bucketCounters = new HashMap<>(); for (String name : stageNames) { bucketCounters.put(name, SpectatorExt.newValueRangeCounterSortable( root.withTags("kind", kind, "stage", name), LEVELS, titusRuntime.getRegistry() )); } return bucketCounters; } }
813
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/HeadTransformer.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.Collection; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import rx.Observable; import rx.Subscription; import rx.observers.SerializedSubscriber; import rx.subscriptions.Subscriptions; /** * An operator that combines snapshots state with hot updates. To prevent loss of * any update for a given snapshot, the hot subscriber is subscribed first, and its * values are buffered until the snapshot state is stream to the subscriber. */ class HeadTransformer<T> implements Observable.Transformer<T, T> { private static final Object END_OF_STREAM_MARKER = new Object(); private enum State {Head, HeadDone, Buffer} private final Supplier<Collection<T>> headValueSupplier; public HeadTransformer(Supplier<Collection<T>> headValueSupplier) { this.headValueSupplier = headValueSupplier; } @Override public Observable<T> call(Observable<T> hotObservable) { return Observable.unsafeCreate(subscriber -> { SerializedSubscriber<T> serialized = new SerializedSubscriber<>(subscriber); Queue<T> buffer = new ConcurrentLinkedDeque<>(); AtomicReference<State> state = new AtomicReference<>(State.Head); Subscription hotSubscription = null; try { // Subscribe before we evaluate head values hotSubscription = hotObservable.subscribe( next -> { if (state.get() == State.Buffer || state.compareAndSet(State.HeadDone, State.Buffer)) { drainBuffer(serialized, buffer); serialized.onNext(next); } else { buffer.add(next); } }, serialized::onError, () -> { if (state.get() == State.Buffer || state.compareAndSet(State.HeadDone, State.Buffer)) { drainBuffer(serialized, buffer); serialized.onCompleted(); } else { buffer.add((T) END_OF_STREAM_MARKER); } } ); Subscription finalHotSubscription = hotSubscription; serialized.add(Subscriptions.create(finalHotSubscription::unsubscribe)); // Stream head if (serialized.isUnsubscribed()) { return; } for (T next : headValueSupplier.get()) { if (serialized.isUnsubscribed()) { return; } serialized.onNext(next); } do { boolean endOfStream = !drainBuffer(serialized, buffer); if (endOfStream) { serialized.onCompleted(); break; } state.set(State.HeadDone); } while (!serialized.isUnsubscribed() && !buffer.isEmpty() && state.compareAndSet(State.HeadDone, State.Head)); } catch (Throwable e) { serialized.onError(e); if (hotSubscription != null) { hotSubscription.unsubscribe(); } } }); } private boolean drainBuffer(SerializedSubscriber<T> serialized, Queue<T> buffer) { for (T next = buffer.poll(); !serialized.isUnsubscribed() && next != null; next = buffer.poll()) { if (next == END_OF_STREAM_MARKER) { return false; } serialized.onNext(next); } return true; } }
814
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/Propagator.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.ExceptionExt; import rx.Emitter; import rx.Observable; import rx.Subscription; /** * See {@link ObservableExt#propagate(Observable, int)} for more information. */ class Propagator<T> { private final Observable<T> source; private final AtomicInteger remainingSubscriptions; private final ConcurrentMap<Integer, Emitter<T>> emittersByOutputIdx = new ConcurrentHashMap<>(); private final List<Observable<T>> outputs; private volatile Subscription sourceSubscription; private volatile boolean sourceTerminated; private Propagator(Observable<T> source, int outputs) { this.source = source; this.remainingSubscriptions = new AtomicInteger(outputs); this.outputs = Evaluators.evaluateTimes(outputs, this::newOutput); } private List<Observable<T>> getOutputs() { return outputs; } private Observable<T> newOutput(int index) { return Observable.create(emitter -> { if (emittersByOutputIdx.putIfAbsent(index, emitter) != null) { emitter.onError(new IllegalStateException(String.format("Propagator output %s already subscribed to", index))); return; } emitter.setCancellation(this::cancelAll); if (remainingSubscriptions.decrementAndGet() == 0) { this.sourceSubscription = source.subscribe(this::emitOnNext, this::emitOnError, this::emitOnCompleted); } }, Emitter.BackpressureMode.NONE); } private void emitOnNext(T next) { try { emittersByOutputIdx.values().forEach(emitter -> emitter.onNext(next)); } catch (Exception e) { emitOnError(e); } } private void emitOnError(Throwable e) { this.sourceTerminated = true; emittersByOutputIdx.values().forEach(emitter -> ExceptionExt.silent(() -> emitter.onError(e))); } private void emitOnCompleted() { this.sourceTerminated = true; emittersByOutputIdx.values().forEach(emitter -> ExceptionExt.silent(emitter::onCompleted)); } private void cancelAll() { if (!sourceTerminated) { ObservableExt.safeUnsubscribe(sourceSubscription); emitOnError(new IllegalStateException("Cancelled")); } } public static <T> List<Observable<T>> create(Observable<T> source, int outputs) { return new Propagator<>(source, outputs).getOutputs(); } }
815
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/ReactorMergeOperations.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import com.netflix.titus.common.util.tuple.Pair; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.SignalType; import reactor.core.scheduler.Scheduler; class ReactorMergeOperations { public static <K> Mono<Map<K, Optional<Throwable>>> merge(Map<K, Mono<Void>> monos, int concurrencyLimit, Scheduler scheduler) { List<Flux<Pair<K, Optional<Throwable>>>> m2 = new ArrayList<>(); monos.forEach((key, mono) -> { Flux<Pair<K, Optional<Throwable>>> x = mono.toProcessor().ignoreElement().materialize().map(result -> { Optional<Throwable> error = result.getType() == SignalType.ON_ERROR ? Optional.of(result.getThrowable()) : Optional.empty(); return Pair.of(key, error); } ).flux(); m2.add(x); }); return Flux.merge(Flux.fromIterable(m2), concurrencyLimit) .subscribeOn(scheduler) .collectList() .map(list -> list.stream().collect(Collectors.toMap(Pair::getLeft, Pair::getRight))); } }
816
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/InContextOnSubscribe.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.function.Function; import java.util.function.Supplier; import rx.Observable; import rx.Subscriber; class InContextOnSubscribe<CONTEXT, T> implements Observable.OnSubscribe<T> { private final Supplier<CONTEXT> contextProvider; private final Function<CONTEXT, Observable<T>> factory; InContextOnSubscribe(Supplier<CONTEXT> contextProvider, Function<CONTEXT, Observable<T>> factory) { this.contextProvider = contextProvider; this.factory = factory; } @Override public void call(Subscriber<? super T> subscriber) { CONTEXT context; try { context = contextProvider.get(); } catch (Exception e) { subscriber.onError(e); return; } Observable<T> result; try { result = factory.apply(context); } catch (Exception e) { subscriber.onError(e); return; } subscriber.add(result.subscribe(subscriber)); } }
817
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/RetryHandlerBuilder.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.io.IOException; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import com.google.common.base.Preconditions; import com.netflix.titus.common.util.ExceptionExt; import org.reactivestreams.Publisher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.util.retry.Retry; import rx.Observable; import rx.Scheduler; import rx.functions.Action1; import rx.functions.Func1; import rx.functions.Func2; import rx.schedulers.Schedulers; /** * Rx retry functions (see {@link Observable#retry(Func2)}). */ public final class RetryHandlerBuilder { private static final Logger logger = LoggerFactory.getLogger(RetryHandlerBuilder.class); private Scheduler scheduler = Schedulers.computation(); private reactor.core.scheduler.Scheduler reactorScheduler; private int retryCount = -1; private long retryDelayMs = -1; private long maxDelay = Long.MAX_VALUE; private String title = "observable"; private Action1<Throwable> onErrorHook = e -> { }; private Supplier<Boolean> retryWhenCondition; private Predicate<Throwable> retryOnThrowableCondition; private RetryHandlerBuilder() { } public RetryHandlerBuilder withScheduler(Scheduler scheduler) { Preconditions.checkNotNull(scheduler); this.scheduler = scheduler; return this; } public RetryHandlerBuilder withReactorScheduler(reactor.core.scheduler.Scheduler scheduler) { Preconditions.checkNotNull(scheduler); this.reactorScheduler = scheduler; return this; } public RetryHandlerBuilder withRetryCount(int retryCount) { Preconditions.checkArgument(retryCount > 0, "Retry count must be >0"); this.retryCount = retryCount; return this; } public RetryHandlerBuilder withUnlimitedRetries() { this.retryCount = Integer.MAX_VALUE / 2; return this; } public RetryHandlerBuilder withRetryDelay(long retryDelay, TimeUnit timeUnit) { Preconditions.checkArgument(retryDelay > 0, "Retry delay must be >0"); Preconditions.checkArgument(retryDelay < Integer.MAX_VALUE, "Retry delay should be < Integer.MAX_VALUE"); this.retryDelayMs = timeUnit.toMillis(retryDelay); return this; } public RetryHandlerBuilder withMaxDelay(long maxDelay, TimeUnit timeUnit) { Preconditions.checkArgument(maxDelay > 0, "Max delay must be >0"); this.maxDelay = timeUnit.toMillis(maxDelay); return this; } public RetryHandlerBuilder withDelay(long initial, long max, TimeUnit timeUnit) { withRetryDelay(initial, timeUnit); withMaxDelay(max, timeUnit); return this; } public RetryHandlerBuilder withTitle(String title) { Preconditions.checkNotNull(title); this.title = title; return this; } public RetryHandlerBuilder withOnErrorHook(Consumer<Throwable> hook) { Preconditions.checkNotNull(title); this.onErrorHook = hook::accept; return this; } public RetryHandlerBuilder withRetryWhen(Supplier<Boolean> retryWhenCondition) { this.retryWhenCondition = retryWhenCondition; return this; } public RetryHandlerBuilder withRetryOnThrowable(Predicate<Throwable> retryOnThrowable) { this.retryOnThrowableCondition = retryOnThrowable; return this; } public RetryHandlerBuilder but() { RetryHandlerBuilder newInstance = new RetryHandlerBuilder(); newInstance.retryCount = retryCount; newInstance.scheduler = scheduler; newInstance.retryDelayMs = retryDelayMs; newInstance.maxDelay = maxDelay; newInstance.title = title; newInstance.onErrorHook = onErrorHook; return newInstance; } public Func1<Observable<? extends Throwable>, Observable<?>> buildExponentialBackoff() { Preconditions.checkState(retryCount > 0, "Retry count not defined"); Preconditions.checkState(retryDelayMs > 0, "Retry delay not defined"); return failedAttempts -> failedAttempts .doOnNext(error -> onErrorHook.call(error)) .zipWith(Observable.range(0, retryCount + 1), RetryItem::new) .flatMap(retryItem -> { if (retryWhenCondition != null && !retryWhenCondition.get()) { String errorMessage = String.format( "Retry condition not met for %s. Last error: %s. Returning an error to the caller", title, retryItem.cause.getMessage() ); return Observable.error(new IOException(errorMessage, retryItem.cause)); } if (retryOnThrowableCondition != null && !retryOnThrowableCondition.test(retryItem.cause)) { String errorMessage = String.format( "Retry condition for the last error not met for %s. Last error: %s. Returning an error to the caller", title, retryItem.cause.getMessage() ); return Observable.error(new IOException(errorMessage, retryItem.cause)); } if (retryItem.retry == retryCount) { String errorMessage = String.format( "Retry limit reached for %s. Last error: %s. Returning an error to the caller", title, retryItem.cause.getMessage() ); return Observable.error(new IOException(errorMessage, retryItem.cause)); } long expDelay = buildDelay(retryItem.retry); if (retryItem.cause instanceof TimeoutException) { logger.info("Delaying timed-out {} retry by {}[ms]", title, expDelay); } else { logger.info("Delaying failed {} retry by {}[ms]: {}", title, expDelay, ExceptionExt.toMessageChain(retryItem.cause)); logger.debug("Exception", retryItem.cause); } return Observable.timer(expDelay, TimeUnit.MILLISECONDS, scheduler); }); } public Function<Flux<Throwable>, Publisher<?>> buildReactorExponentialBackoff() { Preconditions.checkState(retryCount > 0, "Retry count not defined"); Preconditions.checkState(retryDelayMs > 0, "Retry delay not defined"); Preconditions.checkNotNull(reactorScheduler, "Reactor scheduler not set"); return failedAttempts -> failedAttempts .doOnError(error -> onErrorHook.call(error)) .zipWith(Flux.range(0, retryCount + 1), RetryItem::new) .flatMap(retryItem -> { if (retryWhenCondition != null && !retryWhenCondition.get()) { String errorMessage = String.format( "Retry condition not met for %s. Last error: %s. Returning an error to the caller", title, retryItem.cause.getMessage() ); return Flux.error(new IOException(errorMessage, retryItem.cause)); } if (retryOnThrowableCondition != null && !retryOnThrowableCondition.test(retryItem.cause)) { String errorMessage = String.format( "Retry condition for the last error not met for %s. Last error: %s. Returning an error to the caller", title, retryItem.cause.getMessage() ); return Flux.error(new IOException(errorMessage, retryItem.cause)); } if (retryItem.retry == retryCount) { String errorMessage = String.format( "Retry limit reached for %s. Last error: %s. Returning an error to the caller", title, retryItem.cause.getMessage() ); return Flux.error(new IOException(errorMessage, retryItem.cause)); } long expDelay = buildDelay(retryItem.retry); if (retryItem.cause instanceof TimeoutException) { logger.info("Delaying timed-out {} retry by {}[ms]", title, expDelay); } else { logger.info("Delaying failed {} retry by {}[ms]: {}", title, expDelay, ExceptionExt.toMessageChain(retryItem.cause)); logger.debug("Exception", retryItem.cause); } return Flux.interval(Duration.ofMillis(expDelay), reactorScheduler).take(1); }); } public Retry buildRetryExponentialBackoff() { return new Retry() { @Override public Publisher<?> generateCompanion(Flux<RetrySignal> retrySignals) { return buildReactorExponentialBackoff().apply(retrySignals.map(RetrySignal::failure)); } }; } private long buildDelay(int retry) { // at retry == 31, delay expression [ (1 << retry) * retryDelayMs ] causes overflows for long value // hence we fall back to maxDelay for subsequent retries if (retry > 30) { return maxDelay; } final long backOffTime = (1 << retry) * retryDelayMs; return Math.min(maxDelay, backOffTime); } public static RetryHandlerBuilder retryHandler() { return new RetryHandlerBuilder(); } static class RetryItem { private Throwable cause; private int retry; RetryItem(Throwable cause, int retry) { this.cause = cause; this.retry = retry; } } }
818
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/PeriodicGenerator.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import rx.Observable; import rx.Producer; import rx.Scheduler; import rx.Subscriber; import rx.Subscription; import rx.subscriptions.Subscriptions; /** * See {@link ObservableExt#generatorFrom(Supplier)} (Observable, long, long, TimeUnit, Scheduler)}. */ class PeriodicGenerator<T> { private final Observable<T> sourceObservable; private final Scheduler scheduler; private final long initialDelayMs; private final long intervalMs; PeriodicGenerator(Observable<T> sourceObservable, long initialDelay, long interval, TimeUnit timeUnit, Scheduler scheduler) { this.sourceObservable = sourceObservable; this.scheduler = scheduler; this.initialDelayMs = timeUnit.toMillis(initialDelay); this.intervalMs = timeUnit.toMillis(interval); } Observable<List<T>> doMany() { return Observable.unsafeCreate(subscriber -> { Subscription subscription = ObservableExt.generatorFrom(index -> doOne(index == 0), scheduler) .flatMap(d -> d, 1) .subscribe(new Subscriber<List<T>>() { private Producer producer; @Override public void setProducer(Producer p) { super.setProducer(p); this.producer = p; p.request(1); } @Override public void onNext(List<T> item) { subscriber.onNext(item); producer.request(1); } @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { subscriber.onError(e); } } ); subscriber.add(Subscriptions.create(subscription::unsubscribe)); }); } private Observable<List<T>> doOne(boolean firstEmit) { long delayMs = firstEmit ? initialDelayMs : intervalMs; return Observable.timer(delayMs, TimeUnit.MILLISECONDS, scheduler).flatMap(tick -> sourceObservable).toList(); } static <T> Observable<List<T>> from(Observable<T> sourceObservable, long initialDelay, long interval, TimeUnit timeUnit, Scheduler scheduler) { return new PeriodicGenerator<>(sourceObservable, initialDelay, interval, timeUnit, scheduler).doMany(); } }
819
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/CombineTransformer.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.function.Supplier; import com.netflix.titus.common.util.tuple.Pair; import rx.Observable; /** */ class CombineTransformer<T, S> implements Observable.Transformer<T, Pair<T, S>> { private final Supplier<S> stateFactory; CombineTransformer(Supplier<S> stateFactory) { this.stateFactory = stateFactory; } @Override public Observable<Pair<T, S>> call(Observable<T> source) { return Observable.unsafeCreate(subscriber -> { S state = stateFactory.get(); source.map(v -> Pair.of(v, state)).subscribe(subscriber); }); } }
820
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/MapWithStateTransformer.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import com.netflix.titus.common.util.tuple.Either; import com.netflix.titus.common.util.tuple.Pair; import rx.Observable; import rx.Subscription; /** * See {@link ObservableExt#mapWithState(Object, BiFunction)}. */ class MapWithStateTransformer<T, R, S> implements Observable.Transformer<T, R> { private final Supplier<S> zeroSupplier; private final BiFunction<T, S, Pair<R, S>> transformer; private final Observable<Function<S, Pair<R, S>>> cleanupActions; MapWithStateTransformer(Supplier<S> zeroSupplier, BiFunction<T, S, Pair<R, S>> transformer, Observable<Function<S, Pair<R, S>>> cleanupActions) { this.zeroSupplier = zeroSupplier; this.transformer = transformer; this.cleanupActions = cleanupActions; } @Override public Observable<R> call(Observable<T> source) { return Observable.unsafeCreate(subscriber -> { AtomicReference<S> lastState = new AtomicReference<>(zeroSupplier.get()); Observable<Either<T, Function<S, Pair<R, S>>>> sourceEither = source.map(Either::ofValue); Observable<Either<T, Function<S, Pair<R, S>>>> cleanupEither = cleanupActions.map(Either::ofError); Subscription subscription = Observable.merge(sourceEither, cleanupEither).subscribe( next -> { Pair<R, S> result; if (next.hasValue()) { try { result = transformer.apply(next.getValue(), lastState.get()); } catch (Throwable e) { subscriber.onError(e); return; } } else { try { Function<S, Pair<R, S>> action = next.getError(); result = action.apply(lastState.get()); } catch (Throwable e) { subscriber.onError(e); return; } } lastState.set(result.getRight()); subscriber.onNext(result.getLeft()); }, subscriber::onError, subscriber::onCompleted ); subscriber.add(subscription); }); } }
821
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/ReactorHedgedTransformer.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.annotation.Nullable; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.tuple.Either; 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.Mono; import reactor.core.scheduler.Scheduler; class ReactorHedgedTransformer<T> implements Function<Mono<T>, Mono<T>> { private static final Logger logger = LoggerFactory.getLogger(ReactorHedgedTransformer.class); private static final String METRICS_ROOT = "titus.reactor.hedged"; private final List<Pair<Duration, Long>> thresholdSteps; private final Predicate<Throwable> retryableErrorPredicate; private final Map<String, String> context; private final Registry registry; private final Scheduler scheduler; private final Id metricsId; private ReactorHedgedTransformer(List<Pair<Duration, Long>> thresholdSteps, Predicate<Throwable> retryableErrorPredicate, Map<String, String> context, Registry registry, Scheduler scheduler) { this.thresholdSteps = thresholdSteps; this.retryableErrorPredicate = retryableErrorPredicate; this.context = context; this.registry = registry; this.scheduler = scheduler; this.metricsId = registry.createId( METRICS_ROOT, context.entrySet().stream().map(e -> new BasicTag(e.getKey(), e.getValue())).collect(Collectors.toList()) ); } @Override public Mono<T> apply(Mono<T> source) { if (thresholdSteps.isEmpty()) { return source; } // Wrap results as optionals, to capture Mono<Void> sources, which do not provide any value. Flux<Optional<Either<T, Throwable>>> fluxAction = source.transformDeferred(ReactorExt.either()) .map(Optional::of) .switchIfEmpty(Mono.just(Optional.empty())) .flux(); List<Flux<Optional<Either<T, Throwable>>>> all = new ArrayList<>(); all.add(fluxAction); thresholdSteps.forEach(thresholdStep -> { Flux<Optional<Either<T, Throwable>>> action = fluxAction.delaySubscription(thresholdStep.getLeft(), scheduler); for (int i = 0; i < thresholdStep.getRight(); i++) { all.add(action); } }); return Flux.merge(all).subscribeOn(scheduler) .takeUntil(valueOrErrorOpt -> // Optional#empty is a success without a value valueOrErrorOpt .map(valueOrError -> valueOrError.hasValue() || !retryableErrorPredicate.test(valueOrError.getError())) .orElse(true) ) .collectList() .flatMap(results -> { if (results.isEmpty()) { IllegalStateException error = new IllegalStateException("No result or failure"); reportErrors(Collections.singletonList(error)); return Mono.error(error); } List<Throwable> errors = results.stream() .filter(r -> r.map(Either::hasError).orElse(false)) .map(r -> r.get().getError()) .collect(Collectors.toList()); if (results.size() == errors.size()) { reportErrors(errors); // Return last error to a caller, as sending all of them in a composite exception // would require the user to do the exception remapping. Alternatively we could support here // exception aggregator. return Mono.error(CollectionsExt.last(errors)); } Optional<Either<T, Throwable>> lastResult = CollectionsExt.last(results); if (lastResult.isPresent()) { T value = lastResult.get().getValue(); reportSuccess(value, errors); return Mono.just(value); } reportSuccess(null, errors); return Mono.empty(); }); } private void reportSuccess(@Nullable T value, List<Throwable> errors) { if (logger.isDebugEnabled()) { logger.debug("[{}] Request succeeded with {} failed attempts: result={}, errors={}", context, errors.size(), Evaluators.getOrDefault(value, "none"), errors ); } registry.counter(metricsId .withTag("status", "success") .withTag("failedAttempts", "" + errors.size()) ).increment(); } private void reportErrors(List<Throwable> errors) { if (logger.isDebugEnabled()) { logger.debug("[{}] Request failed after {} attempts: errors={}", context, errors.size(), errors); } registry.counter(metricsId .withTag("status", "failure") .withTag("failedAttempts", "" + errors.size()) ).increment(); } static <T> ReactorHedgedTransformer<T> newFromThresholds(List<Duration> thresholds, Predicate<Throwable> retryableErrorPredicate, Map<String, String> context, Registry registry, Scheduler scheduler) { List<Pair<Duration, Long>> thresholdSteps; if (thresholds.isEmpty()) { thresholdSteps = Collections.emptyList(); } else { Map<Duration, Long> grouped = thresholds.stream().collect(Collectors.groupingBy( Function.identity(), Collectors.counting() )); thresholdSteps = grouped.entrySet().stream() .sorted(Comparator.comparing(Map.Entry::getKey)) .map(e -> Pair.of(e.getKey(), e.getValue())) .collect(Collectors.toList()); } return new ReactorHedgedTransformer<>(thresholdSteps, retryableErrorPredicate, context, registry, scheduler); } }
822
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/SubscriptionTimeout.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Supplier; import rx.Observable; import rx.Producer; import rx.Scheduler; import rx.Scheduler.Worker; import rx.Subscriber; import rx.Subscription; import rx.internal.producers.ProducerArbiter; import rx.observers.SerializedSubscriber; /** * Apply a timeout for an entire subscription of a source {@link Observable}. Downstream subscribers will receive an * {@link Subscriber#onError(Throwable) onError} event with a {@link TimeoutException} if a timeout happens before the * source {@link Observable} completes. * <p> * The implementation is inspired by {@link rx.internal.operators.OnSubscribeTimeoutTimedWithFallback}, but it applies a * timeout to the entire subscription, rather than between each {@link Subscriber#onNext(Object) onNext emission}. * <p> * All onNext, onError and onCompleted calls from the source {@link Observable} will be serialized to prevent any races, * otherwise the {@link TimeoutException} generated internally would race with external events. * * @see rx.internal.operators.OnSubscribeTimeoutTimedWithFallback * @see Observable#timeout(long, TimeUnit, Scheduler) */ class SubscriptionTimeout<T> implements Observable.Operator<T, T> { private final Supplier<Long> timeout; private final TimeUnit unit; private final Scheduler scheduler; SubscriptionTimeout(Supplier<Long> timeout, TimeUnit unit, Scheduler scheduler) { this.timeout = timeout; this.unit = unit; this.scheduler = scheduler; } @Override public Subscriber<? super T> call(Subscriber<? super T> downstream) { TimeoutSubscriber<T> upstream = new TimeoutSubscriber<T>(downstream, timeout.get(), unit); downstream.add(upstream); downstream.setProducer(upstream.arbiter); // prevent all races and serialize onNext, onError, and onCompleted calls final Worker worker = scheduler.createWorker(); final SerializedSubscriber<T> safeUpstream = new SerializedSubscriber<>(upstream, true); upstream.add(worker); Subscription task = worker.schedule(() -> safeUpstream.onError(new TimeoutException()), timeout.get(), unit); upstream.add(task); return safeUpstream; } private static final class TimeoutSubscriber<T> extends Subscriber<T> { private final Subscriber<? super T> actual; private final ProducerArbiter arbiter; private TimeoutSubscriber(Subscriber<? super T> actual, long timeout, TimeUnit unit) { this.actual = actual; this.arbiter = new ProducerArbiter(); } @Override public void onNext(T t) { actual.onNext(t); } @Override public void onError(Throwable e) { unsubscribe(); actual.onError(e); } @Override public void onCompleted() { unsubscribe(); actual.onCompleted(); } @Override public void setProducer(Producer p) { arbiter.setProducer(p); } } }
823
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/EmitterWithMultipleSubscriptions.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.Collection; import java.util.concurrent.ConcurrentLinkedQueue; import javax.annotation.Nullable; import rx.Emitter; import rx.Observer; import rx.Subscription; import rx.functions.Cancellable; import rx.internal.subscriptions.CancellableSubscription; import rx.observers.SerializedObserver; import rx.subscriptions.Subscriptions; /** * Emitter implementation that accumulates {@link Subscription subscriptions} and {@link Cancellable cancellations} * instead of replacing the existing one(s). * <p> * Current subscriptions and cancellations can be reset by passing <tt>null</tt> to {@link EmitterWithMultipleSubscriptions#setCancellation(Cancellable)} * and {@link EmitterWithMultipleSubscriptions#setSubscription(Subscription)}. */ public class EmitterWithMultipleSubscriptions<T> implements Emitter<T> { // only kept for requested() delegation private final Emitter<T> actual; private final Observer<T> delegate; private final Collection<Subscription> subscriptions = new ConcurrentLinkedQueue<>(); public EmitterWithMultipleSubscriptions(Emitter<T> delegate) { this.actual = delegate; this.delegate = new SerializedObserver<>(delegate); Subscription composedSubscription = Subscriptions.create(() -> subscriptions.forEach(Subscription::unsubscribe)); actual.setSubscription(composedSubscription); } /** * Add a new subscription while keeping the previous one(s). Note that this is different from the original contract * defined by {@link Emitter#setSubscription(Subscription)}. * * @param s will reset all subscriptions and cancellations when <tt>null</tt> */ @Override public void setSubscription(@Nullable Subscription s) { if (s == null) { subscriptions.clear(); return; } subscriptions.add(s); } /** * Add a new cancellation while keeping the previous one(s). Note that this is different from the original contract * defined by {@link Emitter#setCancellation(Cancellable)}. * * @param c will reset all cancellations and subscriptions when <tt>null</tt> */ @Override public final void setCancellation(@Nullable Cancellable c) { if (c == null) { subscriptions.clear(); return; } subscriptions.add(new CancellableSubscription(c)); } @Override public long requested() { return actual.requested(); } @Override public void onCompleted() { delegate.onCompleted(); } @Override public void onError(Throwable e) { delegate.onError(e); } @Override public void onNext(T t) { delegate.onNext(t); } }
824
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/SchedulerExt.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.titus.common.util.ExecutorsExt; import rx.Scheduler; import rx.schedulers.Schedulers; public class SchedulerExt { /** * Create a {@link Scheduler} from a single (non-daemon) threaded {@link ScheduledExecutorService} with a name pattern. * * @param name the thread name pattern * @return the scheduler */ public static Scheduler createSingleThreadScheduler(String name) { return Schedulers.from(ExecutorsExt.namedSingleThreadExecutor(name)); } }
825
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/ComputationTaskInvoker.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observer; import rx.Scheduler; import rx.functions.Action1; import rx.subjects.AsyncSubject; /** * A computation task invoker with the following properties: * <ul> * <li>Each computation is represented as an {@link Observable} emitting one or more elements, that ultimately completes</li> * <li>Only one computation runs at a time. Only when it completes another one is started.</li> * <li>If a computation is running, and new recompute requests are submitted, they are queued, until the running computation completes</li> * <li>For a backlog of computation requests in the queue, a single computation is performed</li> * </ul> * This invoker is useful if computations mustn't be done in parallel, and its result depends on point in time * (give me result created no later than when the request was submitted). The latter property allows for computation * result sharing across queued requests. */ public class ComputationTaskInvoker<O> { private static final Logger logger = LoggerFactory.getLogger(ComputationTaskInvoker.class); private final Scheduler.Worker worker; private final Observable<O> computation; private final BlockingQueue<Observer<? super O>> waitingObservers = new LinkedBlockingDeque<>(); private final AtomicReference<Observable<Void>> pendingComputation = new AtomicReference<>(); public ComputationTaskInvoker(Observable<O> computation, Scheduler scheduler) { this.worker = scheduler.createWorker(); this.computation = computation; } public Observable<O> recompute() { return Observable.create(subscriber -> { waitingObservers.add(subscriber); worker.schedule(this::drain); }); } private void drain() { if (waitingObservers.isEmpty()) { return; } AsyncSubject<Void> subject = AsyncSubject.create(); Observable<Void> pending = pendingComputation.get(); while (pending == null) { if (pendingComputation.compareAndSet(null, subject)) { pending = subject; } else { pending = pendingComputation.get(); } } if (pending == subject) { List<Observer<? super O>> available = new ArrayList<>(); waitingObservers.drainTo(available); computation .doOnTerminate(() -> { pendingComputation.set(null); subject.onCompleted(); }) .subscribe( next -> doSafely(available, o -> o.onNext(next)), e -> doSafely(available, o -> o.onError(e)), () -> doSafely(available, Observer::onCompleted) ); } else { pending.doOnTerminate(() -> worker.schedule(this::drain)).subscribe(); } } private void doSafely(List<Observer<? super O>> observers, Action1<Observer<? super O>> action) { observers.forEach(o -> { try { action.call(o); } catch (Throwable e) { logger.debug("Observable invocation failure", e); } }); } }
826
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/ReactorRetriers.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.time.Duration; import java.util.function.Function; import java.util.function.Predicate; import org.reactivestreams.Publisher; import org.slf4j.Logger; import reactor.core.publisher.Flux; import reactor.util.retry.Retry; public class ReactorRetriers { public static Retry instrumentedReactorRetryer(String name, Duration retryInterval, Logger logger) { return new Retry() { @Override public Publisher<?> generateCompanion(Flux<RetrySignal> retrySignals) { return retrySignals.flatMap(rs -> { logger.warn("Retrying subscription for {} after {}ms due to an error: error={}", name, retryInterval.toMillis(), rs.failure().getMessage()); return Flux.interval(retryInterval).take(1); }); } }; } public static <T> Function<Flux<T>, Publisher<T>> instrumentedRetryer(String name, Duration retryInterval, Logger logger) { return source -> source.retryWhen(instrumentedReactorRetryer(name, retryInterval, logger)); } public static Retry reactorRetryer(Function<? super Throwable, ? extends Publisher<?>> fn) { return new Retry() { @Override public Publisher<?> generateCompanion(Flux<RetrySignal> retrySignals) { return retrySignals .map(RetrySignal::failure) .flatMap(fn); } }; } public static Retry rectorPredicateRetryer(Predicate<Throwable> predicate) { return Retry.from(companion -> companion.handle((retrySignal, sink) -> { if (retrySignal.failure() != null && predicate.test(retrySignal.failure())) { sink.next(1); } else { sink.error(retrySignal.failure()); } })); } }
827
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/InstrumentedEventLoop.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.common.util.spectator.ActionMetrics; import com.netflix.titus.common.util.spectator.SpectatorExt; import rx.Scheduler; import rx.functions.Action0; /** * This is an instrumented event loop that takes actions and runs them sequentially on the given scheduler. */ public class InstrumentedEventLoop { private final String metricNameRoot; private final Registry registry; private final Scheduler.Worker worker; private final Map<String, ActionMetrics> actionMetrics; private final AtomicLong actionsRemaining; private final Id actionsRemainingId; public InstrumentedEventLoop(String metricNameRoot, Registry registry, Scheduler scheduler) { this.metricNameRoot = metricNameRoot; this.registry = registry; this.worker = scheduler.createWorker(); this.actionMetrics = new ConcurrentHashMap<>(); this.actionsRemaining = new AtomicLong(0); this.actionsRemainingId = registry.createId(metricNameRoot + ".eventLoop.actionsRemaining"); PolledMeter.using(registry) .withId(this.actionsRemainingId) .monitorValue(this.actionsRemaining); } public void schedule(String actionName, Action0 action) { worker.schedule(instrumentedAction(actionName, action)); actionsRemaining.incrementAndGet(); } public void schedule(String actionName, Action0 action, long delayTime, TimeUnit unit) { worker.schedule(instrumentedAction(actionName, action), delayTime, unit); actionsRemaining.incrementAndGet(); } public void shutdown() { if (!worker.isUnsubscribed()) { worker.unsubscribe(); } actionMetrics.values().forEach(ActionMetrics::close); actionMetrics.clear(); PolledMeter.remove(registry, actionsRemainingId); } private Action0 instrumentedAction(String actionName, Action0 action) { return () -> { ActionMetrics actionMetrics = this.actionMetrics.computeIfAbsent(actionName, k -> { String rootName = metricNameRoot + ".eventLoop." + actionName; return SpectatorExt.actionMetrics(rootName, Collections.emptyList(), registry); }); long start = actionMetrics.start(); try { action.call(); actionMetrics.success(); } catch (Exception e) { actionMetrics.failure(e); } finally { actionMetrics.finish(start); actionsRemaining.decrementAndGet(); } }; } }
828
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/ReactorReEmitterOperator.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import org.reactivestreams.Publisher; import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.scheduler.Scheduler; class ReactorReEmitterOperator<T> implements Function<Flux<T>, Publisher<T>> { private final Function<T, T> transformer; private final Duration interval; private final Scheduler scheduler; ReactorReEmitterOperator(Function<T, T> transformer, Duration interval, Scheduler scheduler) { this.transformer = transformer; this.interval = interval; this.scheduler = scheduler; } @Override public Publisher<T> apply(Flux<T> source) { return Flux.create(emitter -> { AtomicReference<T> lastItemRef = new AtomicReference<>(); AtomicReference<Long> reemmitDeadlineRef = new AtomicReference<>(); Flux<T> reemiter = Flux.interval(interval, interval, scheduler) .flatMap(tick -> { if (lastItemRef.get() != null && reemmitDeadlineRef.get() <= scheduler.now(TimeUnit.MILLISECONDS)) { return Flux.just(transformer.apply(lastItemRef.get())); } return Flux.empty(); }); Disposable disposable = Flux.merge( source.doOnNext(next -> { lastItemRef.set(next); reemmitDeadlineRef.set(scheduler.now(TimeUnit.MILLISECONDS) + interval.toMillis()); }), reemiter ).subscribe(emitter::next, emitter::error, emitter::complete); emitter.onCancel(disposable::dispose); }); } }
829
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/ValueGenerator.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import java.util.function.Supplier; import rx.Observable; import rx.Producer; import rx.Scheduler; import rx.Subscriber; import rx.internal.operators.BackpressureUtils; import rx.subscriptions.Subscriptions; class ValueGenerator<T> implements Producer { private final Function<Long, T> source; private final Subscriber<? super T> subscriber; private final Scheduler.Worker worker; private final AtomicLong nextIndex = new AtomicLong(); private final AtomicLong requested = new AtomicLong(); ValueGenerator(Function<Long, T> source, Subscriber<? super T> subscriber, Scheduler scheduler) { this.source = source; this.subscriber = subscriber; this.worker = scheduler.createWorker(); subscriber.add(Subscriptions.create(worker::unsubscribe)); worker.schedule(() -> subscriber.setProducer(this)); } @Override public void request(long n) { if (n > 0) { BackpressureUtils.getAndAddRequest(requested, n); worker.schedule(this::drain); } } private void drain() { while (!subscriber.isUnsubscribed() && requested.get() > 0 && doOne()) { requested.decrementAndGet(); } } private boolean doOne() { try { subscriber.onNext(source.apply(nextIndex.getAndIncrement())); } catch (Exception e) { subscriber.onError(e); return false; } return true; } static <T> Observable<T> from(Supplier<T> source, Scheduler scheduler) { return Observable.unsafeCreate(subscriber -> new ValueGenerator<>(idx -> source.get(), subscriber, scheduler)); } static <T> Observable<T> from(Function<Long, T> source, Scheduler scheduler) { return Observable.unsafeCreate(subscriber -> new ValueGenerator<>(source, subscriber, scheduler)); } }
830
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/ReactorHeadTransformer.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.Collection; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.function.Supplier; import org.reactivestreams.Publisher; import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; /** * An operator that combines snapshots state with hot updates. To prevent loss of * any update for a given snapshot, the hot subscriber is subscribed first, and its * values are buffered until the snapshot state is streamed to the subscriber. */ class ReactorHeadTransformer<T> implements Function<Flux<T>, Publisher<T>> { private static final Object END_OF_STREAM_MARKER = new Object(); private enum State {Head, HeadDone, Buffer} private final Supplier<Collection<T>> headValueSupplier; ReactorHeadTransformer(Supplier<Collection<T>> headValueSupplier) { this.headValueSupplier = headValueSupplier; } @Override public Publisher<T> apply(Flux<T> tFlux) { return Flux.create(emitter -> { Queue<Object> buffer = new ConcurrentLinkedDeque<>(); AtomicReference<State> state = new AtomicReference<>(State.Head); Disposable hotSubscription = null; try { // Subscribe before we evaluate head values hotSubscription = tFlux.subscribe( next -> { if (state.get() == State.Buffer || state.compareAndSet(State.HeadDone, State.Buffer)) { drainBuffer(emitter, buffer); emitter.next(next); } else { buffer.add(next); } }, e -> { if (state.get() == State.Buffer || state.compareAndSet(State.HeadDone, State.Buffer)) { drainBuffer(emitter, buffer); emitter.error(e); } else { buffer.add(new ErrorWrapper(e)); } }, () -> { if (state.get() == State.Buffer || state.compareAndSet(State.HeadDone, State.Buffer)) { drainBuffer(emitter, buffer); emitter.complete(); } else { buffer.add(END_OF_STREAM_MARKER); } } ); emitter.onDispose(hotSubscription); // Stream head if (emitter.isCancelled()) { return; } for (T next : headValueSupplier.get()) { if (emitter.isCancelled()) { return; } emitter.next(next); } do { boolean endOfStream = !drainBuffer(emitter, buffer); if (endOfStream) { emitter.complete(); break; } state.set(State.HeadDone); } while (!emitter.isCancelled() && !buffer.isEmpty() && state.compareAndSet(State.HeadDone, State.Head)); } catch (Throwable e) { emitter.error(e); ReactorExt.safeDispose(hotSubscription); } }); } private boolean drainBuffer(FluxSink<T> emitter, Queue<Object> buffer) { for (Object next = buffer.poll(); !emitter.isCancelled() && next != null; next = buffer.poll()) { if (next == END_OF_STREAM_MARKER) { return false; } if (next instanceof ErrorWrapper) { emitter.error(((ErrorWrapper) next).cause); return false; } emitter.next((T) next); } return true; } private static class ErrorWrapper { private final Throwable cause; private ErrorWrapper(Throwable cause) { this.cause = cause; } } }
831
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/FluxObservableEmitter.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.function.Consumer; import reactor.core.publisher.FluxSink; import rx.Observable; import rx.Subscription; class FluxObservableEmitter<T> implements Consumer<FluxSink<T>> { private Observable<T> source; FluxObservableEmitter(Observable<T> source) { this.source = source; } @Override public void accept(FluxSink<T> sink) { Subscription subscription = source.subscribe(sink::next, sink::error, sink::complete); sink.onCancel(subscription::unsubscribe); } }
832
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/FluxListenerInvocationHandler.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.function.Consumer; import reactor.core.publisher.Flux; class FluxListenerInvocationHandler<T> implements InvocationHandler { private final Class<?> listenerType; private final Consumer<T> delegate; private FluxListenerInvocationHandler(Class<?> listenerType, Consumer<T> delegate) { this.listenerType = listenerType; this.delegate = delegate; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass().equals(listenerType)) { delegate.accept((T) args[0]); return null; } return method.invoke(this, args); } static <L, T> Flux<T> adapt(Class<L> listenerType, Consumer<L> register, Consumer<L> unregister) { return Flux.create(emitter -> { L callbackHandler = (L) Proxy.newProxyInstance( listenerType.getClassLoader(), new Class[]{listenerType}, new FluxListenerInvocationHandler<>(listenerType, emitter::next) ); register.accept(callbackHandler); emitter.onDispose(() -> unregister.accept(callbackHandler)); }); } }
833
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/ObservableExt.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Tag; import com.netflix.titus.common.util.rx.batch.Batch; import com.netflix.titus.common.util.rx.batch.Batchable; import com.netflix.titus.common.util.rx.batch.RateLimitedBatcher; import com.netflix.titus.common.util.spectator.SpectatorExt; import com.netflix.titus.common.util.tuple.Pair; import org.slf4j.Logger; import rx.BackpressureOverflow; import rx.Completable; import rx.Notification; import rx.Observable; import rx.Scheduler; import rx.Single; import rx.Subscriber; import rx.Subscription; import rx.schedulers.Schedulers; /** * Supplementary Rx operators. */ public class ObservableExt { /** * {@link Observable#fromCallable(Callable)} variant, which emits individual collection values. */ public static <T> Observable<T> fromCallable(Supplier<Collection<T>> supplier) { return Observable.fromCallable(supplier::get).flatMapIterable(v -> v); } /** * Invokes the completable supplier on each subscription, and connects a client subscription to it. */ public static Completable fromCallableSupplier(Callable<Completable> completableSupplier) { return Observable.fromCallable(completableSupplier).flatMap(Completable::toObservable).toCompletable(); } /** * Default RxJava future wrapper is blocking. Here we provide polling version. */ public static <T> Observable<T> toObservable(Future<T> future, Scheduler scheduler) { return Observable.unsafeCreate(new FutureOnSubscribe<>(future, scheduler)); } /** * Subscribes to one observable at a time. Once the current observable completes, waits for a request amount of time * before next subscription. */ public static <T> Observable<T> fromWithDelay(List<Observable<T>> chunks, long delay, TimeUnit timeUnit, Scheduler scheduler) { if (chunks.isEmpty()) { return Observable.empty(); } final Iterator<Observable<T>> chunkIterator = chunks.iterator(); Observable<T> result = chunkIterator.next(); while (chunkIterator.hasNext()) { result = result.concatWith(chunkIterator.next().delay(delay, timeUnit, scheduler)); } return result; } /** * Emit collection content on subscribe. */ public static <T> Observable<T> fromCollection(Supplier<Collection<T>> listProvider) { return Observable.fromCallable(listProvider::get).flatMap(Observable::from); } /** * An operator that combines snapshots state with hot updates. To prevent loss of * any update for a given snapshot, the hot subscriber is subscribed first, and its * values are buffered until the snapshot state is streamed to the subscriber. */ public static <T> Observable.Transformer<T, T> head(Supplier<Collection<T>> headSupplier) { return new HeadTransformer<>(headSupplier); } /** * An operator that on subscription creates a user supplied state object, that is combined with each emitted item. */ public static <T, S> Observable.Transformer<T, Pair<T, S>> combine(Supplier<S> stateFactory) { return new CombineTransformer<>(stateFactory); } /** * Equivalent to {@link Observable#map} function, but with additional state passing. Each function invocation * returns a pair, where the first value is a map result, and the second value is state object, passed as an input * when next item is emitted. */ public static <T, R, S> Observable.Transformer<T, R> mapWithState(S zero, BiFunction<T, S, Pair<R, S>> transformer) { return new MapWithStateTransformer<>(() -> zero, transformer, Observable.empty()); } /** * See {@link #mapWithState(Object, BiFunction)}. The difference is that the initial value is computed on each subscription. */ public static <T, R, S> Observable.Transformer<T, R> mapWithState(Supplier<S> zeroSupplier, BiFunction<T, S, Pair<R, S>> transformer) { return new MapWithStateTransformer<>(zeroSupplier, transformer, Observable.empty()); } /** * A variant of {@link #mapWithState(Object, BiFunction)} operator, with a source of cleanup actions. */ public static <T, R, S> Observable.Transformer<T, R> mapWithState(S zero, BiFunction<T, S, Pair<R, S>> transformer, Observable<Function<S, Pair<R, S>>> cleanupActions) { return new MapWithStateTransformer<>(() -> zero, transformer, cleanupActions); } /** * Returns an Observable that mirrors the source Observable but applies a timeout policy for its completion. If * onCompleted or onError are not emitted within the specified timeout duration after it has been subscribed to, * the resulting {@link Observable} terminates and notifies observers of a {@link java.util.concurrent.TimeoutException}. */ public static <T> Observable.Transformer<T, T> subscriptionTimeout(Supplier<Long> timeout, TimeUnit unit, Scheduler scheduler) { return (observable) -> observable.lift(new SubscriptionTimeout<T>(timeout, unit, scheduler)); } /** * Ignore all elements, and emit empty {@link Optional} if stream completes normally or {@link Optional} with * the exception. */ public static Single<Optional<Throwable>> emitError(Observable<?> source) { return source.ignoreElements().materialize().take(1).map(result -> result.getKind() == Notification.Kind.OnError ? Optional.of(result.getThrowable()) : Optional.<Throwable>empty() ).toSingle(); } /** * Wrap and instrument a <tt>batcher</tt> so it can be {@link Observable#compose(Observable.Transformer) composed} * into a RxJava chain. */ public static <T extends Batchable<?>, I> Observable.Transformer<T, Batch<T, I>> batchWithRateLimit(RateLimitedBatcher<T, I> batcher, String metricsRootName, Registry registry) { return source -> source .lift(batcher) .compose(SpectatorExt.subscriptionMetrics(metricsRootName, registry)); } /** * Wrap and instrument a <tt>batcher</tt> so it can be {@link Observable#compose(Observable.Transformer) composed} * into a RxJava chain. */ public static <T extends Batchable<?>, I> Observable.Transformer<T, Batch<T, I>> batchWithRateLimit(RateLimitedBatcher<T, I> batcher, String metricsRootName, List<Tag> tags, Registry registry) { return source -> source .lift(batcher) .compose(SpectatorExt.subscriptionMetrics(metricsRootName, tags, registry)); } /** * Ignore all elements, and emit empty {@link Optional} if stream completes normally or {@link Optional} with * the exception. */ public static Single<Optional<Throwable>> emitError(Completable source) { return emitError(source.toObservable()); } /** * Back-pressure enabled infinite stream of data generator. */ public static <T> Observable<T> generatorFrom(Supplier<T> source) { return ValueGenerator.from(source, Schedulers.computation()); } /** * Back-pressure enabled infinite stream of data generator. */ public static <T> Observable<T> generatorFrom(Function<Long, T> source, Scheduler scheduler) { return ValueGenerator.from(source, scheduler); } /** * Periodically subscribes to the source observable, and emits all its values (as list) or an exception if * the subscription terminates with an error. * * @param sourceObservable an observable which is periodically subscribed to * @param initialDelay initial delay before the first subscription * @param interval delay time between the last subscription termination, and start of a new one * @param timeUnit time unit for initialDelay and interval parameters * @param scheduler scheduler on which subscription is executed. */ public static <T> Observable<List<T>> periodicGenerator(Observable<T> sourceObservable, long initialDelay, long interval, TimeUnit timeUnit, Scheduler scheduler) { return PeriodicGenerator.from(sourceObservable, initialDelay, interval, timeUnit, scheduler); } /** * Simple scheduler. */ public static Observable<Optional<Throwable>> schedule(String metricNameRoot, Registry registry, String completableName, Completable completable, long initialDelay, long interval, TimeUnit timeUnit, Scheduler scheduler) { InstrumentedCompletableScheduler completableScheduler = new InstrumentedCompletableScheduler(metricNameRoot, registry, scheduler); return completableScheduler.schedule(completableName, completable, initialDelay, interval, timeUnit); } /** * In case subscriber does not provide exception handler, the error is propagated back to source, and the stream is broken. * In some scenarios it is undesirable behavior. This method wraps the unprotected observable, and logs all unhandled * exceptions using the provided logger. */ public static <T> Observable<T> protectFromMissingExceptionHandlers(Observable<T> unprotectedStream, Logger logger) { return Observable.unsafeCreate(subscriber -> { Subscription subscription = unprotectedStream.subscribe( event -> { try { subscriber.onNext(event); } catch (Exception e) { try { subscriber.onError(e); } catch (Exception e2) { logger.warn("Subscriber threw an exception from onNext handler", e); logger.warn("Subscriber threw an exception from onError handler", e2); } } }, e -> { try { subscriber.onError(e); } catch (Exception e2) { logger.warn("Subscriber threw an exception from onError handler", e2); } }, () -> { try { subscriber.onCompleted(); } catch (Exception e) { logger.warn("Subscriber threw an exception from onCompleted handler", e); } } ); subscriber.add(subscription); }); } /** * Adds a backpressure handler to an observable stream, which buffers data, and in case of buffer overflow * calls periodically the user provided callback handler. */ public static <T> Observable<T> onBackpressureDropAndNotify(Observable<T> unprotectedStream, long maxBufferSize, Consumer<Long> onDropAction, long notificationInterval, TimeUnit timeUnit) { long notificationIntervalMs = timeUnit.toMillis(notificationInterval); return Observable.fromCallable(() -> 1).flatMap(tick -> { AtomicLong lastOverflowLogTime = new AtomicLong(); AtomicLong dropCount = new AtomicLong(); return unprotectedStream.onBackpressureBuffer( maxBufferSize, () -> { dropCount.getAndIncrement(); long now = System.currentTimeMillis(); if (now - lastOverflowLogTime.get() > notificationIntervalMs) { onDropAction.accept(dropCount.get()); lastOverflowLogTime.set(now); } }, BackpressureOverflow.ON_OVERFLOW_DROP_OLDEST ); }); } /** * Unsubscribe, ignoring null subscription values. */ public static void safeUnsubscribe(Subscription... subscriptions) { for (Subscription subscription : subscriptions) { if (subscription != null) { subscription.unsubscribe(); } } } /** * Subscriber that swallows all {@link Observable} notifications. {@link Observable#subscribe()} throws an * exception back to the caller if the subscriber does not provide {@link Subscriber#onError(Throwable)} method * implementation. */ public static <T> Subscriber<T> silentSubscriber() { return new Subscriber<T>() { @Override public void onNext(T t) { // Do nothing } @Override public void onCompleted() { // Do nothing } @Override public void onError(Throwable e) { // Do nothing } }; } /** * Creates an instrumented event loop * * @param metricNameRoot the root metric name to use * @param registry the metric registry to use * @param scheduler the scheduler used to create workers */ public static InstrumentedEventLoop createEventLoop(String metricNameRoot, Registry registry, Scheduler scheduler) { return new InstrumentedEventLoop(metricNameRoot, registry, scheduler); } /** * If the source observable does not emit any item in the configured amount of time, the last emitted value is * re-emitted again, optionally updated by the transformer. */ public static <T> Observable.Transformer<T, T> reemiter(Function<T, T> transformer, long interval, TimeUnit timeUnit, Scheduler scheduler) { return new ReEmitterTransformer<>(transformer, interval, timeUnit, scheduler); } /** * Creates multiple {@link Observable} instances (outputs) backed by the same source observable, with the following properties: * <ul> * <li>the source observable is subscribed to only when the all outputs are subscribed to</li> * <li>the source observable is subscribed to only once, and the same result is propagated to the all outputs</li> * <li>if one of the output observables is cancelled, all the remaining observables are cancelled as well</li> * <li>if an output is subscribed to multiple times, all the subscriptions except the first one are terminated with an error</li> * </ul> */ public static <T> List<Observable<T>> propagate(Observable<T> source, int outputs) { return Propagator.create(source, outputs); } }
834
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/TimerWithWorker.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoSink; import reactor.core.scheduler.Scheduler; class TimerWithWorker { static Mono<Void> timer(Runnable action, Scheduler.Worker worker, Duration delay) { return timer(() -> { action.run(); return null; }, worker, delay); } static <T> Mono<T> timer(Supplier<T> action, Scheduler.Worker worker, Duration delay) { if (worker.isDisposed()) { return Mono.empty(); } return Mono.create(sink -> { if (worker.isDisposed()) { sink.success(); } else { timer(action, worker, delay, sink); } }); } private static <T> void timer(Supplier<T> action, Scheduler.Worker worker, Duration delay, MonoSink<T> sink) { worker.schedule(() -> { try { T result = action.get(); if (result != null) { sink.success(result); } else { sink.success(); } } catch (Exception e) { sink.error(e); } }, delay.toMillis(), TimeUnit.MILLISECONDS); } }
835
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/FutureOnSubscribe.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.subscriptions.Subscriptions; class FutureOnSubscribe<T> implements Observable.OnSubscribe<T> { static final long INITIAL_DELAY_MS = 1; static final long MAX_DELAY_MS = 1000; private final Future<T> future; private final Scheduler scheduler; private final AtomicBoolean isSubscribed = new AtomicBoolean(); FutureOnSubscribe(Future<T> future, Scheduler scheduler) { this.future = future; this.scheduler = scheduler; } @Override public void call(Subscriber<? super T> subscriber) { if (isSubscribed.getAndSet(true)) { subscriber.onError(new IllegalStateException("Only one subscription allowed in future wrapper")); return; } new FutureObserver(subscriber); } private class FutureObserver { private final Subscriber<? super T> subscriber; private final Scheduler.Worker worker; FutureObserver(Subscriber<? super T> subscriber) { this.subscriber = subscriber; this.worker = scheduler.createWorker(); subscriber.add(Subscriptions.create(() -> { future.cancel(true); worker.unsubscribe(); })); doSchedule(INITIAL_DELAY_MS); } private void doSchedule(long delayMs) { if (completeIfDone()) { worker.unsubscribe(); } worker.schedule(() -> doSchedule(Math.min(2 * delayMs, MAX_DELAY_MS)), delayMs, TimeUnit.MILLISECONDS); } private boolean completeIfDone() { if (subscriber.isUnsubscribed()) { return true; } if (!future.isDone()) { return false; } if (future.isCancelled()) { subscriber.onError(new IllegalStateException("future is cancelled")); return true; } try { T value = future.get(); subscriber.onNext(value); subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } return true; } } }
836
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/ReactorMapWithStateTransformer.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import com.netflix.titus.common.util.tuple.Either; import com.netflix.titus.common.util.tuple.Pair; import org.reactivestreams.Publisher; import reactor.core.Disposable; import reactor.core.publisher.Flux; /** * See {@link ReactorExt#mapWithState(Object, BiFunction)}. */ class ReactorMapWithStateTransformer<T, R, S> implements Function<Flux<T>, Publisher<R>> { private final Supplier<S> zeroSupplier; private final BiFunction<T, S, Pair<R, S>> transformer; private final Flux<Function<S, Pair<R, S>>> cleanupActions; ReactorMapWithStateTransformer(Supplier<S> zeroSupplier, BiFunction<T, S, Pair<R, S>> transformer, Flux<Function<S, Pair<R, S>>> cleanupActions) { this.zeroSupplier = zeroSupplier; this.transformer = transformer; this.cleanupActions = cleanupActions; } @Override public Publisher<R> apply(Flux<T> source) { return Flux.create(sink -> { AtomicReference<S> lastState = new AtomicReference<>(zeroSupplier.get()); Flux<Either<T, Function<S, Pair<R, S>>>> sourceEither = source.map(Either::ofValue); Flux<Either<T, Function<S, Pair<R, S>>>> cleanupEither = cleanupActions.map(Either::ofError); Disposable subscription = Flux.merge(sourceEither, cleanupEither).subscribe( next -> { Pair<R, S> result; if (next.hasValue()) { try { result = transformer.apply(next.getValue(), lastState.get()); } catch (Throwable e) { sink.error(e); return; } } else { try { Function<S, Pair<R, S>> action = next.getError(); result = action.apply(lastState.get()); } catch (Throwable e) { sink.error(e); return; } } lastState.set(result.getRight()); sink.next(result.getLeft()); }, sink::error, sink::complete ); sink.onCancel(subscription); }); } }
837
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/InstrumentedCompletableScheduler.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.util.spectator.ContinuousSubscriptionMetrics; import com.netflix.titus.common.util.spectator.SpectatorExt; import rx.Completable; import rx.Emitter; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.functions.Action0; public class InstrumentedCompletableScheduler { private final String metricNameRoot; private final Registry registry; private final Scheduler.Worker worker; private final Map<String, ContinuousSubscriptionMetrics> completableMetricsByName; InstrumentedCompletableScheduler(String metricNameRoot, Registry registry, Scheduler scheduler) { this.metricNameRoot = metricNameRoot; this.registry = registry; this.worker = scheduler.createWorker(); completableMetricsByName = new ConcurrentHashMap<>(); } public Observable<Optional<Throwable>> schedule(String completableName, Completable completable, long initialDelay, long interval, TimeUnit timeUnit) { return Observable.create(emitter -> { ContinuousSubscriptionMetrics subscriptionMetrics = this.completableMetricsByName.computeIfAbsent(completableName, k -> { String rootName = metricNameRoot + ".completableScheduler." + completableName; return SpectatorExt.continuousSubscriptionMetrics(rootName, Collections.emptyList(), registry); }); Action0 action = () -> ObservableExt.emitError(completable.compose(subscriptionMetrics.asCompletable())) .subscribe(emitter::onNext, emitter::onError); Subscription subscription = worker.schedulePeriodically(action, initialDelay, interval, timeUnit); emitter.setCancellation(() -> { subscription.unsubscribe(); subscriptionMetrics.remove(); completableMetricsByName.remove(completableName); }); }, Emitter.BackpressureMode.NONE); } public void shutdown() { worker.unsubscribe(); completableMetricsByName.values().forEach(ContinuousSubscriptionMetrics::remove); completableMetricsByName.clear(); } }
838
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/ReEmitterTransformer.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import rx.Observable; import rx.Scheduler; public class ReEmitterTransformer<T> implements Observable.Transformer<T, T> { private final Function<T, T> transformer; private final long intervalMs; private final Scheduler scheduler; ReEmitterTransformer(Function<T, T> transformer, long interval, TimeUnit timeUnit, Scheduler scheduler) { this.transformer = transformer; this.intervalMs = timeUnit.toMillis(interval); this.scheduler = scheduler; } @Override public Observable<T> call(Observable<T> source) { return Observable.unsafeCreate(subscriber -> { AtomicReference<T> lastItemRef = new AtomicReference<>(); AtomicReference<Long> reemmitDeadlineRef = new AtomicReference<>(); Observable<T> reemiter = Observable.interval(intervalMs, intervalMs, TimeUnit.MILLISECONDS, scheduler).flatMap(tick -> { if (lastItemRef.get() != null && reemmitDeadlineRef.get() <= scheduler.now()) { return Observable.just(transformer.apply(lastItemRef.get())); } return Observable.empty(); }); Observable.merge( source.doOnNext(next -> { lastItemRef.set(next); reemmitDeadlineRef.set(scheduler.now() + intervalMs); }), reemiter ).subscribe(subscriber); }); } }
839
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/ReactorExt.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.time.Duration; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.util.tuple.Either; import com.netflix.titus.common.util.tuple.Pair; import hu.akarnokd.rxjava.interop.RxJavaInterop; import org.reactivestreams.Publisher; import org.reactivestreams.Subscription; import org.slf4j.Logger; import reactor.core.CoreSubscriber; import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.SignalType; import reactor.core.scheduler.Scheduler; import rx.Completable; import rx.Observable; import rx.Single; /** * Supplementary Spring Reactor operators. */ public final class ReactorExt { private ReactorExt() { } /** * Wrap value or error into {@link Either}. The resulting stream never emits an error. */ public static <T> Function<Mono<T>, Mono<Either<T, Throwable>>> either() { return source -> source.<Either<T, Throwable>>map(Either::ofValue).onErrorResume(e -> Mono.just(Either.ofError(e))); } /** * Ignore all elements, and emit empty {@link Optional#empty()} if stream completes normally or * {@link Optional#of(Object)} with the exception. */ public static Mono<Optional<Throwable>> emitError(Mono<?> source) { return source.ignoreElement().materialize().map(result -> result.getType() == SignalType.ON_ERROR ? Optional.of(result.getThrowable()) : Optional.empty() ); } public static <L, T> Flux<T> fromListener(Class<L> listener, Consumer<L> register, Consumer<L> unregister) { return FluxListenerInvocationHandler.adapt(listener, register, unregister); } /** * In case subscriber does not provide exception handler, the error is propagated back to source, and the stream is broken. * In some scenarios it is undesirable behavior. This method wraps the unprotected observable, and logs all unhandled * exceptions using the provided logger. */ public static <T> Function<Flux<T>, Publisher<T>> badSubscriberHandler(Logger logger) { return source -> Flux.create(emitter -> { Disposable subscription = source.subscribe( event -> { try { emitter.next(event); } catch (Exception e) { try { emitter.error(e); } catch (Exception e2) { logger.warn("Subscriber threw an exception from onNext handler", e); logger.warn("Subscriber threw an exception from onError handler", e2); } } }, e -> { try { emitter.error(e); } catch (Exception e2) { logger.warn("Subscriber threw an exception from onError handler", e2); } }, () -> { try { emitter.complete(); } catch (Exception e) { logger.warn("Subscriber threw an exception from onCompleted handler", e); } } ); emitter.onDispose(() -> safeDispose(subscription)); }); } /** * An operator that converts collection of value into an event stream. Subsequent collection versions * are compared against each other and add/remove events are emitted accordingly. */ public static <K, T, E> Function<Flux<List<T>>, Publisher<E>> eventEmitter( Function<T, K> keyFun, BiPredicate<T, T> valueComparator, Function<T, E> valueAddedEventMapper, Function<T, E> valueRemovedEventMapper, E snapshotEndEvent) { return new EventEmitterTransformer<>(keyFun, valueComparator, valueAddedEventMapper, valueRemovedEventMapper, snapshotEndEvent); } /** * An operator that combines snapshots state with hot updates. To prevent loss of * any update for a given snapshot, the hot subscriber is subscribed first, and its * values are buffered until the snapshot state is streamed to the subscriber. */ public static <T> Function<Flux<T>, Publisher<T>> head(Supplier<Collection<T>> headSupplier) { return new ReactorHeadTransformer<>(headSupplier); } /** * Creates multiple parallel subscriptions to the source observable. The first subscription happens immediately, while * the remaining are delayed by the configured thresholds. The first one to complete successfully returns. * Errors are ignored. If all subscriptions fail, emits a composite error. * * @param thresholds list of thresholds * @param retryableErrorPredicate should return true if an error is retryable, and the parallel calls should not be interrupted * @param context context values used for logging and metrics * @param scheduler scheduler for all hedged subscriptions */ public static <T> Function<Mono<T>, Mono<T>> hedged(List<Duration> thresholds, Predicate<Throwable> retryableErrorPredicate, Map<String, String> context, Registry registry, Scheduler scheduler) { if (thresholds.isEmpty()) { return Function.identity(); } return ReactorHedgedTransformer.newFromThresholds(thresholds, retryableErrorPredicate, context, registry, scheduler); } /** * Equivalent to {@link Observable#map} function, but with additional state passing. Each function invocation * returns a pair, where the first value is a map result, and the second value is state object, passed as an input * when next item is emitted. */ public static <T, R, S> Function<Flux<T>, Publisher<R>> mapWithState(S zero, BiFunction<T, S, Pair<R, S>> transformer) { return new ReactorMapWithStateTransformer<>(() -> zero, transformer, Flux.empty()); } /** * See {@link #mapWithState(Object, BiFunction)}. The difference is that the initial value is computed on each subscription. */ public static <T, R, S> Function<Flux<T>, Publisher<R>> mapWithState(Supplier<S> zeroSupplier, BiFunction<T, S, Pair<R, S>> transformer) { return new ReactorMapWithStateTransformer<>(zeroSupplier, transformer, Flux.empty()); } /** * A variant of {@link #mapWithState(Object, BiFunction)} operator, with a source of cleanup actions. */ public static <T, R, S> Function<Flux<T>, Publisher<R>> mapWithState(S zero, BiFunction<T, S, Pair<R, S>> transformer, Flux<Function<S, Pair<R, S>>> cleanupActions) { return new ReactorMapWithStateTransformer<>(() -> zero, transformer, cleanupActions); } /** * Merge a map of {@link Mono}s, and return the combined result as a map. If a mono with a given key succeeded, the * returned map will contain value {@link Optional#empty()} for that key. Otherwise it will contain an error entry. */ public static <K> Mono<Map<K, Optional<Throwable>>> merge(Map<K, Mono<Void>> monos, int concurrencyLimit, Scheduler scheduler) { return ReactorMergeOperations.merge(monos, concurrencyLimit, scheduler); } /** * If the source observable does not emit any item in the configured amount of time, the last emitted value is * re-emitted again, optionally updated by the transformer. */ public static <T> Function<Flux<T>, Publisher<T>> reEmitter(Function<T, T> transformer, Duration interval, Scheduler scheduler) { return new ReactorReEmitterOperator<>(transformer, interval, scheduler); } public static void safeDispose(Disposable... disposables) { for (Disposable disposable : disposables) { try { disposable.dispose(); } catch (Exception ignore) { } } } /** * Runs an action on the provided worker. */ public static <T> Mono<T> onWorker(Supplier<T> action, Scheduler.Worker worker) { return TimerWithWorker.timer(action, worker, Duration.ZERO); } /** * Runs an action on the provided worker with the provided delay. */ public static <T> Mono<T> onWorker(Supplier<T> action, Scheduler.Worker worker, Duration delay) { return TimerWithWorker.timer(action, worker, delay); } /** * Runs an action on the provided worker. */ public static Mono<Void> onWorker(Runnable action, Scheduler.Worker worker) { return TimerWithWorker.timer(action, worker, Duration.ZERO); } /** * Runs an action on the provided worker with the provided delay. */ public static Mono<Void> onWorker(Runnable action, Scheduler.Worker worker, Duration delay) { return TimerWithWorker.timer(action, worker, delay); } /** * In case subscriber does not provide exception handler, the error is propagated back to source, and the stream is broken. * In some scenarios it is undesirable behavior. This method wraps the unprotected flux, and logs all unhandled * exceptions using the provided logger. * * @deprecated use {@link #badSubscriberHandler(Logger)} */ @Deprecated public static <T> Flux<T> protectFromMissingExceptionHandlers(Flux<T> unprotectedStream, Logger logger) { return Flux.create(sink -> { Disposable disposable = unprotectedStream.subscribe( event -> { try { sink.next(event); } catch (Exception e) { try { sink.error(e); logger.warn("Subscriber threw an exception from onNext handler", e); } catch (Exception e2) { logger.warn("Subscriber threw an exception from onError handler", e2); } } }, e -> { try { sink.error(e); } catch (Exception e2) { logger.warn("Subscriber threw an exception from onError handler", e2); } }, () -> { try { sink.complete(); } catch (Exception e) { logger.warn("Subscriber threw an exception from onCompleted handler", e); } } ); sink.onDispose(disposable); }); } /** * RxJava {@link Observable} to {@link Flux} bridge. */ public static <T> Flux<T> toFlux(Observable<T> observable) { return Flux.create(new FluxObservableEmitter<>(observable)); } /** * RxJava {@link Single} to {@link Mono} bridge. */ public static <T> Mono<T> toMono(Single<T> single) { return toFlux(single.toObservable()).next(); } /** * RxJava {@link Single} to {@link Mono} bridge. */ public static Mono<Void> toMono(Observable<Void> observable) { return toFlux(observable).next(); } /** * RxJava {@link rx.Completable} to {@link Mono} bridge. */ public static Mono<Void> toMono(Completable completable) { return toFlux(completable.<Void>toObservable()).next(); } /** * {@link Flux} bridge to RxJava {@link Observable}. */ public static <T> Observable<T> toObservable(Flux<T> flux) { return RxJavaInterop.toV1Observable(flux); } /** * {@link Mono} bridge to RxJava {@link Observable}. */ public static <T> Observable<T> toObservable(Mono<T> mono) { return RxJavaInterop.toV1Observable(mono); } /** * {@link Mono} bridge to RxJava {@link Single}. */ public static <T> Single<T> toSingle(Mono<T> mono) { return toObservable(mono).toSingle(); } /** * {@link Mono} bridge to RxJava {@link Completable}. */ public static Completable toCompletable(Mono<Void> mono) { return toObservable(mono).toCompletable(); } /** * Subscriber that does not do anything with the callback requests. */ public static <T> CoreSubscriber<T> silentSubscriber() { return new CoreSubscriber<T>() { @Override public void onSubscribe(Subscription s) { } @Override public void onNext(T t) { } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }; } }
840
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/EventEmitterTransformer.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiPredicate; import java.util.function.Function; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; class EventEmitterTransformer<K, T, E> implements Function<Flux<List<T>>, Publisher<E>> { private final Function<T, K> keyFun; private final BiPredicate<T, T> valueComparator; private final Function<T, E> valueAddedEventMapper; private final Function<T, E> valueRemovedEventMapper; private final E snapshotEndEvent; EventEmitterTransformer( Function<T, K> keyFun, BiPredicate<T, T> valueComparator, Function<T, E> valueAddedEventMapper, Function<T, E> valueRemovedEventMapper, E snapshotEndEvent) { this.keyFun = keyFun; this.valueComparator = valueComparator; this.valueAddedEventMapper = valueAddedEventMapper; this.valueRemovedEventMapper = valueRemovedEventMapper; this.snapshotEndEvent = snapshotEndEvent; } @Override public Publisher<E> apply(Flux<List<T>> source) { return Flux.defer(() -> { AtomicBoolean snapshotSent = new AtomicBoolean(); AtomicReference<Map<K, T>> valueMapRef = new AtomicReference<>(Collections.emptyMap()); return source.flatMapIterable(newSnapshot -> { Map<K, T> previousValueMap = valueMapRef.get(); Map<K, T> newValueMap = toValueMap(newSnapshot); List<E> events = new ArrayList<>(); // Updates newValueMap.forEach((key, value) -> { T previousValue = previousValueMap.get(key); if (previousValue == null || !valueComparator.test(value, previousValue)) { events.add(valueAddedEventMapper.apply(value)); } }); // Removes previousValueMap.forEach((key, value) -> { if (!newValueMap.containsKey(key)) { events.add(valueRemovedEventMapper.apply(value)); } }); valueMapRef.set(newValueMap); if (!snapshotSent.getAndSet(true)) { events.add(snapshotEndEvent); } return events; }); }); } private Map<K, T> toValueMap(List<T> values) { if (values.isEmpty()) { return Collections.emptyMap(); } Map<K, T> valueMap = new HashMap<>(); values.forEach(value -> valueMap.put(keyFun.apply(value), value)); return valueMap; } }
841
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/eventbus/RxEventBus.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.eventbus; import rx.Observable; /** * Back pressure enabled, Rx event bus. */ public interface RxEventBus { void close(); <E> void publish(E event); <E> void publishAsync(E Event); <E> Observable<E> listen(String subscriberId, Class<E> eventType); }
842
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/eventbus/EventBusSubscribers.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.eventbus; import rx.Observable; public class EventBusSubscribers { public static Observable<Object> listen(RxEventBus eventBus, String subscriberId, Class<?>... types) { return eventBus.listen(subscriberId, Object.class).filter(event -> { for (Class<?> type : types) { if (type.isAssignableFrom(event.getClass())) { return true; } } return false; }); } }
843
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/eventbus
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/eventbus/internal/RxEventBusMetrics.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.eventbus.internal; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; class RxEventBusMetrics { private final Id eventCounterId; private final Id subscriberMetricsId; private final Registry registry; private final ConcurrentMap<String, SubscriberMetrics> subscriberMetrics = new ConcurrentHashMap<>(); private final ConcurrentMap<Class<?>, Counter> eventCounters = new ConcurrentHashMap<>(); RxEventBusMetrics(Id rootId, Registry registry) { this.eventCounterId = registry.createId(rootId.name() + "input", rootId.tags()); this.subscriberMetricsId = registry.createId(rootId.name() + "subscribers", rootId.tags()); this.registry = registry; } void subscriberAdded(String subscriberId) { subscriberMetrics.put(subscriberId, new SubscriberMetrics(subscriberId)); } void subscriberRemoved(String subscriberId) { subscriberMetrics.remove(subscriberId).close(); } void published(Object event) { Counter counter = eventCounters.computeIfAbsent( event.getClass(), c -> registry.counter(eventCounterId.withTag("class", c.getName())) ); counter.increment(); } void delivered(String subscriberId, long queueSize, Object event, long latency) { SubscriberMetrics metrics = this.subscriberMetrics.get(subscriberId); if (metrics != null) { // Should always be non-null metrics.delivered(queueSize, event, latency); } } void overflowed(String subscriberId) { SubscriberMetrics metrics = this.subscriberMetrics.get(subscriberId); if (metrics != null) { // Should always be non-null metrics.overflowed(); } } private class SubscriberMetrics { private final Id eventCounterId; private final AtomicLong queueSizeGauge; private final AtomicLong latencyGauge; private final AtomicLong overflowGauge; private final ConcurrentMap<Class<?>, Counter> eventCounters = new ConcurrentHashMap<>(); SubscriberMetrics(String subscriberId) { Id myId = subscriberMetricsId.withTags("subscriber", subscriberId); this.eventCounterId = idFor(myId, "output"); this.queueSizeGauge = registry.gauge(idFor(myId, "queueSize"), new AtomicLong()); this.latencyGauge = registry.gauge(idFor(myId, "latency"), new AtomicLong()); this.overflowGauge = registry.gauge(idFor(myId, "overflow"), new AtomicLong()); } private Id idFor(Id myId, String suffix) { return registry.createId(myId + "." + suffix, myId.tags()); } // We do not reset overflow gauge, as it would disappear too quickly void close() { queueSizeGauge.set(0); latencyGauge.set(0); } void delivered(long queueSize, Object event, long latency) { queueSizeGauge.set(queueSize); latencyGauge.set(latency); Counter counter = eventCounters.computeIfAbsent( event.getClass(), c -> registry.counter(eventCounterId.withTag("class", c.getName())) ); counter.increment(); } void overflowed() { overflowGauge.set(1); } } }
844
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/eventbus
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/eventbus/internal/DefaultRxEventBus.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.eventbus.internal; import java.util.Collections; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.util.rx.eventbus.RxEventBus; import com.netflix.titus.common.util.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Producer; import rx.Scheduler; import rx.Subscriber; import rx.Subscription; import rx.internal.operators.BackpressureUtils; import rx.schedulers.Schedulers; public class DefaultRxEventBus implements RxEventBus { private static final Logger logger = LoggerFactory.getLogger(DefaultRxEventBus.class); private static final long MAX_QUEUE_SiZE = 10000; private final long maxQueueSize; private final Scheduler.Worker worker; private final RxEventBusMetrics metrics; private final Set<SubscriptionHandler> subscriptionHandlers = Collections.newSetFromMap(new ConcurrentHashMap<>()); public DefaultRxEventBus(Id rootId, Registry registry) { this(rootId, registry, MAX_QUEUE_SiZE, Schedulers.computation()); } public DefaultRxEventBus(Id rootId, Registry registry, long maxQueueSize, Scheduler scheduler) { this.maxQueueSize = maxQueueSize; this.worker = scheduler.createWorker(); this.metrics = new RxEventBusMetrics(rootId, registry); } @Override public void close() { if (worker.isUnsubscribed() && subscriptionHandlers.isEmpty()) { return; } logger.debug("Closing EventBus"); subscriptionHandlers.forEach(SubscriptionHandler::close); subscriptionHandlers.clear(); worker.unsubscribe(); } @Override public <E> void publish(E event) { checkIfOpen(); logger.debug("Publishing event {}", event); publish(new Pair<>(worker.now(), event)); metrics.published(event); } @Override public <E> void publishAsync(E event) { checkIfOpen(); logger.debug("Publishing event {}", event); worker.schedule(() -> publish(new Pair<>(worker.now(), event))); metrics.published(event); } private void publish(Pair<Long, Object> eventWithTimestamp) { for (SubscriptionHandler handler : subscriptionHandlers) { if (!handler.isUnsubscribed()) { handler.publish(eventWithTimestamp); } } } private void checkIfOpen() { if (worker.isUnsubscribed()) { throw new IllegalStateException("EventBus closed"); } } @Override public <E> Observable<E> listen(String subscriberId, Class<E> eventType) { return Observable.create(subscriber -> { logger.debug("Subscribed {} for event {}", subscriberId, eventType.getName()); // We register cleanup hook in SubscriptionHandler constructor, so we need to check for early unsubscribe SubscriptionHandler handler = new SubscriptionHandler(subscriberId, eventType, (Subscriber<Object>) subscriber); if (!handler.isUnsubscribed()) { subscriptionHandlers.add(handler); if (handler.isUnsubscribed()) { subscriptionHandlers.remove(handler); } } }); } /** * Drain method implementation based on RxJava guidelines * (see https://github.com/ReactiveX/RxJava/wiki/Implementing-custom-operators-(draft)). */ private class SubscriptionHandler implements Subscription, Producer { private final String subscriberId; private final Class<?> eventType; private final Subscriber<Object> subscriber; private final AtomicInteger queueSize = new AtomicInteger(); private final Queue<Pair<Long, Object>> eventQueue = new ConcurrentLinkedQueue<>(); // mutual exclusion private final AtomicInteger counter = new AtomicInteger(); // tracks the downstream request amount private final AtomicLong requested = new AtomicLong(); // no more values expected from upstream private volatile boolean done; // the upstream error private volatile Throwable error; SubscriptionHandler(String subscriberId, Class<?> eventType, Subscriber<Object> subscriber) { this.subscriberId = subscriberId; this.eventType = eventType; this.subscriber = subscriber; subscriber.add(this); subscriber.setProducer(this); metrics.subscriberAdded(subscriberId); } void publish(Pair<Long, Object> eventWithTimestamp) { Object event = eventWithTimestamp.getRight(); if (!subscriber.isUnsubscribed() && eventType.isAssignableFrom(event.getClass())) { if (queueSize.incrementAndGet() > maxQueueSize) { error = new IllegalStateException("Event queue overflow"); metrics.overflowed(subscriberId); done = true; } else { eventQueue.add(eventWithTimestamp); } drain(); } } void close() { done = true; drain(); } @Override public void request(long n) { if (n > 0) { BackpressureUtils.getAndAddRequest(requested, n); drain(); } } @Override public void unsubscribe() { subscriptionHandlers.remove(this); logger.debug("Unsubscribed {} for event {}", subscriberId, eventType.getName()); } @Override public boolean isUnsubscribed() { return subscriber.isUnsubscribed(); } private void drain() { if (counter.getAndIncrement() != 0) { return; } int missed = 1; for (; ; ) { // Error happens only when we have overflow, in which case we ignore all elements in the queue. if (error != null) { terminate(); return; } long requests = requested.get(); long emission = 0L; while (emission != requests) { // don't emit more than requested if (subscriber.isUnsubscribed()) { return; } // Error happens only when we have overflow, in which case we ignore all elements in the queue. if (error != null) { terminate(); return; } boolean stop = done; // order matters here! Pair<Long, Object> eventWithTimestamp = eventQueue.poll(); boolean empty = eventWithTimestamp == null; // if no more values, emit completion event if (stop && empty) { terminate(); return; } // the upstream hasn't stopped yet but we don't have a value available if (empty) { break; } Object event = eventWithTimestamp.getRight(); long latency = worker.now() - eventWithTimestamp.getLeft(); int currentQueueSize = queueSize.decrementAndGet(); subscriber.onNext(event); metrics.delivered(subscriberId, currentQueueSize, event, latency); emission++; logger.debug("Emitted event {} to subscriber {}", event, subscriberId); } // if we are at a request boundary, a terminal event can be still emitted without requests if (emission == requests) { if (subscriber.isUnsubscribed()) { return; } boolean stop = done; // order matters here! boolean empty = eventQueue.isEmpty(); // if no more values, emit completion event if (stop && empty) { terminate(); return; } } // decrement the current request amount by the emission count if (emission != 0L && requests != Long.MAX_VALUE) { BackpressureUtils.produced(requested, emission); } // indicate that we have performed the outstanding amount of work missed = counter.addAndGet(-missed); if (missed == 0) { return; } // if a concurrent getAndIncrement() happened, we loop back and continue } } private void terminate() { Throwable ex = error; if (ex != null) { subscriber.onError(ex); logger.debug("Completed {}/{} subscription with error", subscriberId, eventType.getName(), ex); } else { subscriber.onCompleted(); logger.debug("Completed {}/{} subscription", subscriberId, eventType.getName()); } metrics.subscriberRemoved(subscriberId); } } }
845
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/invoker/ReactorSerializedInvokerMetrics.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.invoker; import java.util.concurrent.TimeUnit; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; class ReactorSerializedInvokerMetrics { private static final String ROOT_NAME = "titus.common.serializedInvoker."; private final Counter submitCounter; private final Counter queueFullCounter; private final Gauge queueSize; private final Timer queueingTimer; private final Timer executionTimer; private final Timer executionErrorTimer; private final Timer executionDisposedTimer; private final String name; private final Registry registry; ReactorSerializedInvokerMetrics(String name, Registry registry) { this.name = name; this.registry = registry; this.submitCounter = registry.counter(ROOT_NAME + "submit", "name", name); this.queueFullCounter = registry.counter(ROOT_NAME + "queueFull", "name", name); this.queueSize = registry.gauge(ROOT_NAME + "queueSize", "name", name); this.queueingTimer = registry.timer(ROOT_NAME + "queueingTime", "name", name); this.executionTimer = registry.timer(ROOT_NAME + "executionTime", "name", name, "status", "success"); this.executionErrorTimer = registry.timer(ROOT_NAME + "executionTime", "name", name, "status", "error"); this.executionDisposedTimer = registry.timer(ROOT_NAME + "executionTime", "name", name, "status", "disposed"); } void onSubmit() { submitCounter.increment(); } void setQueueSize(int size) { queueSize.set(size); } void onQueueFull() { queueFullCounter.increment(); } void onActionExecutionStarted(long queueingTimeMs) { queueingTimer.record(queueingTimeMs, TimeUnit.MILLISECONDS); } void onActionCompleted(long executionTimeMs) { executionTimer.record(executionTimeMs, TimeUnit.MILLISECONDS); } void onActionFailed(long executionTimeMs, Throwable error) { executionErrorTimer.record(executionTimeMs, TimeUnit.MILLISECONDS); registry.counter(ROOT_NAME + "executionError", "name", name, "error", error.getClass().getSimpleName() ).increment(); } void onActionExecutionDisposed(long executionTimeMs) { executionDisposedTimer.record(executionTimeMs, TimeUnit.MILLISECONDS); } }
846
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/invoker/ReactorSerializedInvoker.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.invoker; import java.time.Duration; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeoutException; import com.google.common.base.Preconditions; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.util.time.Clock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.core.Disposables; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoProcessor; import reactor.core.publisher.MonoSink; import reactor.core.publisher.SignalType; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Scheduler.Worker; /** * A simple queue for Spring Reactor {@link Mono} actions, which execution order must be serialized. */ public class ReactorSerializedInvoker<T> { private static final Logger logger = LoggerFactory.getLogger(ReactorSerializedInvoker.class); private final Duration excessiveRunningTime; private final Worker worker; private final Scheduler scheduler; private final Clock clock; private final ReactorSerializedInvokerMetrics metrics; private final BlockingQueue<ActionHandler> actionHandlers; private ActionHandler pendingAction; private volatile boolean shutdownFlag; private ReactorSerializedInvoker(String name, int size, Duration excessiveRunningTime, Scheduler scheduler, Registry registry, Clock clock) { this.excessiveRunningTime = excessiveRunningTime; this.worker = scheduler.createWorker(); this.scheduler = scheduler; this.metrics = new ReactorSerializedInvokerMetrics(name, registry); this.actionHandlers = new LinkedBlockingQueue<>(size); this.clock = clock; } public void shutdown(Duration timeout) { if (shutdownFlag) { return; } this.shutdownFlag = true; MonoProcessor<Void> marker = MonoProcessor.create(); worker.schedule(this::drainOnShutdown); worker.schedule(marker::onComplete); try { marker.block(timeout); } catch (Exception ignoreTimeout) { } finally { worker.dispose(); } } public Mono<T> submit(Mono<T> action) { Preconditions.checkState(!shutdownFlag, "ReactorQueue has been shutdown"); Preconditions.checkNotNull(action); StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); return Mono.create(sink -> { metrics.onSubmit(); ActionHandler actionHandler = new ActionHandler(action, sink, stackTrace); if (!actionHandlers.offer(actionHandler)) { metrics.onQueueFull(); sink.error(actionHandler.newException(new IllegalStateException("Queue is full"))); return; } metrics.setQueueSize(actionHandlers.size()); if (shutdownFlag) { actionHandler.terminate(); } else { worker.schedule(this::drain); } }); } /** * Draining is performed by the internal event loop worker. */ private void drain() { if (shutdownFlag) { return; } if (pendingAction != null && !pendingAction.isTerminated()) { return; } ActionHandler nextAction; while ((nextAction = actionHandlers.poll()) != null) { if (nextAction.startExecution()) { this.pendingAction = nextAction; metrics.setQueueSize(actionHandlers.size()); return; } } metrics.setQueueSize(actionHandlers.size()); pendingAction = null; } private void drainOnShutdown() { if (pendingAction != null) { pendingAction.terminate(); } ActionHandler nextAction; while ((nextAction = actionHandlers.poll()) != null) { nextAction.terminate(); } metrics.setQueueSize(0); } public static <T> Builder<T> newBuilder() { return new Builder<>(); } public static class Builder<T> { private String name; private int size; private Duration excessiveRunningTime = Duration.ofHours(1); private Scheduler scheduler; private Registry registry; private Clock clock; public Builder<T> withName(String name) { this.name = name; return this; } public Builder<T> withMaxQueueSize(int size) { this.size = size; return this; } public Builder<T> withExcessiveRunningTime(Duration excessiveRunningTime) { this.excessiveRunningTime = excessiveRunningTime; return this; } public Builder<T> withScheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } public Builder<T> withRegistry(Registry registry) { this.registry = registry; return this; } public Builder<T> withClock(Clock clock) { this.clock = clock; return this; } public ReactorSerializedInvoker<T> build() { return new ReactorSerializedInvoker<>(name, size, excessiveRunningTime, scheduler, registry, clock); } } private class ActionHandler { private final Mono<T> action; private final MonoSink<T> sink; private final StackTraceElement[] stackTrace; private volatile boolean terminated; private volatile Disposable.Composite disposable; private final long queueTimestamp; private long startTimestamp; private ActionHandler(Mono<T> action, MonoSink<T> sink, StackTraceElement[] stackTrace) { this.action = action; this.sink = sink; this.stackTrace = stackTrace; this.queueTimestamp = clock.wallTime(); } boolean isTerminated() { return terminated; } boolean startExecution() { startTimestamp = clock.wallTime(); metrics.onActionExecutionStarted(startTimestamp - queueTimestamp); this.disposable = Disposables.composite(); sink.onCancel(disposable); // Check early in case the sink is already disposed/cancelled. if (disposable.isDisposed()) { metrics.onActionExecutionDisposed(0); return false; } Disposable actionDisposable = action .timeout(excessiveRunningTime, Mono.error(newException(new TimeoutException("Excessive running time")))) .subscribeOn(scheduler) .doFinally(signalType -> { if (signalType != SignalType.ON_COMPLETE && signalType != SignalType.ON_ERROR) { metrics.onActionExecutionDisposed(clock.wallTime() - startTimestamp); } terminated = true; worker.schedule(ReactorSerializedInvoker.this::drain); }) .subscribe( next -> { metrics.onActionCompleted(clock.wallTime() - startTimestamp); try { sink.success(next); } catch (Exception e) { logger.warn("Bad subscriber", e); } }, e -> { metrics.onActionFailed(clock.wallTime() - startTimestamp, e); try { sink.error(e); } catch (Exception e2) { logger.warn("Bad subscriber", e2); } }, () -> { metrics.onActionCompleted(clock.wallTime() - startTimestamp); try { sink.success(); } catch (Exception e) { logger.warn("Bad subscriber", e); } } ); disposable.add(actionDisposable); return true; } void terminate() { if (!terminated) { terminated = true; if (disposable != null) { disposable.dispose(); } try { sink.error(newException(new IllegalStateException("Queue shutdown"))); } catch (Exception e) { logger.warn("Bad subscriber", e); } } } <E extends Throwable> E newException(E exception) { exception.setStackTrace(stackTrace); return exception; } } }
847
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/batch/RateLimitedBatcher.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.batch; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; import com.google.common.base.Preconditions; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.common.util.collections.ConcurrentHashMultimap; import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket; import com.netflix.titus.common.util.rx.InstrumentedEventLoop; 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 rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.exceptions.Exceptions; import rx.plugins.RxJavaHooks; /** * rxJava operator that buffers items from an upstream Observable stream, and emits batches indexed by pluggable logic * to downstream subscribers, in a rate provided by a {@link TokenBucket}. * <p> * Items for a particular index are batched for a minimum period (<tt>initialDelay</tt>). When the {@link TokenBucket} * gets exhausted, emission of batches to downstream subscribers is paused with an exponential backoff strategy up to * <tt>maxDelay</tt>. * <p> * Items are removed from the (in-memory) pending buffer right after they are emitted, but concurrent operations are * allowed while batches are being emitted (flushed). It is possible that a particular item is replaced in the in-memory * buffer while it is being emitted. To avoid losing the most recent item, they are compared with * {@link Object#equals(Object)} and removed atomically from the buffer only when considered equal * (with <tt>compareAndRemove</tt> semantics). Implementations of {@link Batchable} are encouraged to implement * <tt>equals</tt> in a way that two {@link Batchable} causing the system to be in the same final state are considered * equal. * <p> * A single instance of this operator can be used in multiple different rxJava streams, in which case the same * {@link TokenBucket} will be shared across all of them, and all work will be scheduled on the same {@link Scheduler.Worker}. * <p> * Example usage: * <pre> * {@code * RateLimitedBatcher<SomeOperation, IndexType> batcher = RateLimitedBatcher.create(...); * Observable<SomeOperation> source = ...; * source.lift(RateLimitedBatcher.create(...)) * .subscribe(Batch<SomeOperation, IndexType> batch -> { * // batch.getIndex() is of type IndexType, and will be provided by an IndexExtractor * processBatch(batch.getItems()); * }); * } * </pre> * * @param <T> type of items to be queued and batched * @param <I> type of the value (an index, usually a field of T, provided by <tt>IndexExtractor</tt>) to batch by */ public class RateLimitedBatcher<T extends Batchable<?>, I> implements Observable.Operator<Batch<T, I>, T> { private final Logger logger = LoggerFactory.getLogger(RateLimitedBatcher.class); private static final String ACTION_FLUSH = "flush"; private static final String ACTION_COMPLETED = "sendCompleted"; private static final String ACTION_ERROR = "sendError"; /** * event loop that serializes all on{Next, Error, Completed} calls */ private final InstrumentedEventLoop worker; private final TokenBucket tokenBucket; private final long initialDelayMs; private final long maxDelayMs; private final IndexExtractor<T, I> indexExtractor; private final EmissionStrategy emissionStrategy; private final String metricsRoot; private final Registry registry; private final Counter rateLimitCounter; private final Clock clock; /** * @see com.netflix.titus.common.util.rx.ObservableExt#batchWithRateLimit(RateLimitedBatcher, String, Registry) * @see com.netflix.titus.common.util.rx.ObservableExt#batchWithRateLimit(RateLimitedBatcher, String, List, Registry) */ public static <T extends Batchable<?>, I> RateLimitedBatcher<T, I> create(TokenBucket tokenBucket, long initialDelay, long maxDelay, IndexExtractor<T, I> indexExtractor, EmissionStrategy emissionStrategy, String metricsRoot, Registry registry, Scheduler scheduler) { return new RateLimitedBatcher<T, I>(tokenBucket, initialDelay, maxDelay, indexExtractor, emissionStrategy, metricsRoot, registry, scheduler); } private RateLimitedBatcher(TokenBucket tokenBucket, long initialDelay, long maxDelay, IndexExtractor<T, I> indexExtractor, EmissionStrategy emissionStrategy, String metricsRoot, Registry registry, Scheduler scheduler) { Preconditions.checkArgument(initialDelay > 0, "initialDelayMs must be > 0"); Preconditions.checkArgument(maxDelay >= initialDelay, "maxDelayMs must be >= initialDelayMs"); Preconditions.checkArgument(!metricsRoot.endsWith("."), "metricsRoot must not end with a '.' (dot)"); this.tokenBucket = tokenBucket; this.initialDelayMs = initialDelay; this.maxDelayMs = maxDelay; this.indexExtractor = indexExtractor; this.emissionStrategy = emissionStrategy; this.metricsRoot = metricsRoot; this.registry = registry; this.rateLimitCounter = registry.counter(metricsRoot + ".rateLimit"); this.clock = Clocks.scheduler(scheduler); this.worker = new InstrumentedEventLoop(metricsRoot, registry, scheduler); } @Override public Subscriber<? super T> call(final Subscriber<? super Batch<T, I>> downstream) { Flusher flusher = new Flusher(downstream); flusher.run(); return new BatchUpstreamSubscriber(flusher); } private interface EventQueue<T> { void offer(T item); void offerError(Throwable e); void stopWhenEmpty(); } private final class BatchUpstreamSubscriber extends Subscriber<T> { private final EventQueue<T> events; private BatchUpstreamSubscriber(EventQueue<T> events) { this.events = events; } @Override public void onCompleted() { events.stopWhenEmpty(); } @Override public void onError(Throwable e) { events.offerError(e); } @Override public void onNext(T item) { Preconditions.checkNotNull(item); events.offer(item); } } /** * Continually flushes pending batches to downstream subscribers */ private final class Flusher implements EventQueue<T> { /** * each batch is an immutable Map (indexed by <tt>Batchable#getIdentifier()</tt>), and modifications are applied * with copy-on-write */ private final ConcurrentHashMultimap<I, T> pending = new ConcurrentHashMultimap<>(Batchable::getIdentifier, this::isHigherPriorityOrNewer); /** * all calls to on{Next,Error,Completed} are serialized in an event loop controlled by a {@link Scheduler.Worker}, * so we respect the <tt>Observable</tt> contract (onError or onCompleted are called only once, and no items are * delivered with onNext after they are called). */ private final Subscriber<? super Batch<T, I>> downstream; /** * current delay between scans for pending items to be flushed. It is exponentially incremented when we get rate * limited by the {@link TokenBucket}. */ private final AtomicLong currentDelayMs = new AtomicLong(initialDelayMs); /** * tracks when upstream has completed emitting, so we can terminate after flushing what is currently pending */ private volatile boolean done = false; /** * tracks when an error has been scheduled to be sent, so we interrupt pending work */ private volatile boolean isOnErrorScheduled = false; /** * tracks when an error event has been sent to downstream subscribers, so we don't try and send more. */ private volatile boolean sentError = false; /** * tracks when a completed event has been sent to downstream subscribers, so we don't try and send more. */ private volatile boolean sentCompleted = false; private Flusher(Subscriber<? super Batch<T, I>> downstream) { this.downstream = downstream; } /** * On a conflict, replace the existing value if the new one has higher priority, or the same priority but is * different (as per {@link Batchable#isEquivalent(Batchable)}) and a more recent timestamp. That way, older * items are only replaced by newer items doing something different. * <p> * Same priority and same timestamp is also replaced (last with the same timestamp wins) as long as they are * different (by {@link Batchable#isEquivalent(Batchable)}). * * @param existing old value * @param replacement new value * @return true when the existing value should be replaced by the new value */ private boolean isHigherPriorityOrNewer(T existing, T replacement) { final int priorityComparison = Batchable.byPriority().compare(replacement, existing); if (priorityComparison != 0) { return priorityComparison > 0; // always keep the one with higher priority } // same priority, check if newer boolean isMoreRecent = !replacement.getTimestamp().isBefore(existing.getTimestamp()); return isMoreRecent && !replacement.isEquivalent(existing); } /** * start the continuous loop */ public void run() { PolledMeter.using(registry) .withName(metricsRoot + ".pending") // TODO: size() does a O(N) scan, optimize it .monitorValue(pending, ConcurrentHashMultimap::size); worker.schedule(ACTION_FLUSH, this::flushPending, currentDelayMs.get(), TimeUnit.MILLISECONDS); } /** * continually schedules itself to keep flushing items being accumulated */ private void flushPending() { if (isOnErrorScheduled) { logger.info("Ending the flush loop, onError will be called and onNext can not be called anymore"); return; } Queue<Batch<T, I>> ordered = emissionStrategy.compute(readyBatchesStream()); if (ordered.isEmpty()) { scheduleNextIfNotDone(); return; } for (; ; ) { if (isOnErrorScheduled) { logger.info("Ending the flush loop, onError will be called and onNext can not be called anymore"); return; } final Batch<T, I> next = ordered.poll(); if (next == null) { break; } if (!tokenBucket.tryTake()) { scheduleNextWhenRateLimited(); return; } resetCurrentDelay(); onNextSafe(next); /* * Only remove sent items if they have not been modified in the pending data structure to avoid losing * items that were replaced while being emitted. * * Partial failures in the batch consider the whole batch as done. */ next.getItems().forEach(item -> pending.removeIf(next.getIndex(), item, current -> current.isEquivalent(item) )); } logger.debug("All pending items flushed, scheduling another round"); worker.schedule(ACTION_FLUSH, this::flushPending); } /** * swallow downstream exceptions and keep the event loop running */ private void onNextSafe(Batch<T, I> next) { // TODO: capture rate limit exceptions from downstream and apply exponential backoff here too try { downstream.onNext(next); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); logger.error("onNext failed, ignoring batch {}", next.getIndex(), ex); } } private void scheduleNextWhenRateLimited() { final long nextRefill = tokenBucket.getRefillStrategy().getTimeUntilNextRefill(TimeUnit.MILLISECONDS); final long delayForNext = Math.max(increaseAndGetCurrentDelayMs(), nextRefill); logger.warn("Rate limit applied, retry in {} ms", delayForNext); rateLimitCounter.increment(); worker.schedule(ACTION_FLUSH, this::flushPending, delayForNext, TimeUnit.MILLISECONDS); } private void scheduleNextIfNotDone() { if (done && pending.isEmpty()) { logger.info("Ending the flush loop, all pending items were flushed after onComplete from upstream"); worker.schedule(ACTION_COMPLETED, this::sendCompleted); return; } logger.debug("No batches are ready yet. Next iteration in {} ms", currentDelayMs); worker.schedule(ACTION_FLUSH, this::flushPending, currentDelayMs.get(), TimeUnit.MILLISECONDS); } private long increaseAndGetCurrentDelayMs() { return currentDelayMs.updateAndGet(current -> Math.min(maxDelayMs, current << 1)); } /** * reset backoff when we have tokens again */ private void resetCurrentDelay() { currentDelayMs.set(initialDelayMs); } /** * Let batches accumulate in pending for at least initialDelayMs */ private Stream<Batch<T, I>> readyBatchesStream() { return pending.asMap().entrySet().stream() // TODO: Batch.of() iterates on all values to find oldestTimestamp. Consider precomputing as they are added .map(entry -> Batch.of(entry.getKey(), new ArrayList<>(entry.getValue()))) .filter(batch -> isWaitingForAtLeast(batch, initialDelayMs)); } private boolean isWaitingForAtLeast(Batch<T, I> batch, long ms) { Instant now = Instant.ofEpochMilli(clock.wallTime()); final Instant cutLine = now.minus(ms, ChronoUnit.MILLIS); return !batch.getOldestItemTimestamp().isAfter(cutLine); } /** * ensure onCompleted is only called if onError was not (the {@link Observable} contract). Since it is a * terminal event, {@link Scheduler.Worker#unsubscribe()} is called. */ private void sendCompleted() { if (sentError || sentCompleted) { logger.warn("onCompleted event being swallowed because another terminal event already sent"); return; } sentCompleted = true; downstream.onCompleted(); worker.shutdown(); } /** * ensure onError is only called if onCompleted was not (the {@link Observable} contract). Since it is a * terminal event, {@link Scheduler.Worker#unsubscribe()} is called. */ private void sendError(Throwable e) { if (sentError || sentCompleted) { logger.error("Another terminal event was already sent, emitting as undeliverable", e); RxJavaHooks.onError(e); return; } sentError = true; /* * setting done is not strictly necessary since the error tracking above should be enough to stop periodic * scheduling, but it is here for completeness */ done = true; downstream.onError(e); worker.shutdown(); } /** * schedule an error to be sent and interrupt pending work */ public void offerError(Throwable e) { if (isOnErrorScheduled || sentError || sentCompleted) { logger.error("Another terminal event was already sent, emitting as undeliverable", e); RxJavaHooks.onError(e); return; } isOnErrorScheduled = true; worker.schedule(ACTION_ERROR, () -> sendError(e)); } /** * enqueue an item from upstream */ public void offer(T item) { if (done || isOnErrorScheduled || sentError || sentCompleted) { logger.warn("done={} onErrorScheduled={} onError={} onCompleted={} ignoring item {}", done, isOnErrorScheduled, sentError, sentCompleted, item); return; // don't accumulate more after being told to stop } pending.put(indexExtractor.apply(item), item); } /** * causes current pending items to be drained to downstream subscribers before stopping completely */ public void stopWhenEmpty() { done = true; } } }
848
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/batch/IndexExtractor.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.batch; import java.util.function.Function; /** * Logic to determine what index (value) to batch items by, mostly an alias to Function<T, F>. * * @param <T> container type * @param <F> type of a field of <tt>T</tt> to be extracted */ public interface IndexExtractor<T, F> extends Function<T, F> { }
849
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/batch/Batch.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.batch; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; /** * @param <I> type of the batch identifier (index) * @param <T> type of items in the batch */ public class Batch<T extends Batchable<?>, I> { private static final Comparator<Batch<?, ?>> COMPARING_BY_SIZE = Comparator.comparingInt(b -> b.getItems().size()); public static Comparator<Batch<?, ?>> bySize() { return COMPARING_BY_SIZE; } private final I index; private final List<T> items; private final Instant oldestItemTimestamp; @SafeVarargs public static <T extends Batchable<?>, I> Batch<T, I> of(I index, T... items) { return of(index, Arrays.asList(items)); } public static <T extends Batchable<?>, I> Batch<T, I> of(I index, List<T> items) { return new Batch<>(index, items); } private Batch(I index, List<T> items) { this.index = index; this.items = Collections.unmodifiableList(items); // TODO: consider precomputing this as items are accumulated for a batch this.oldestItemTimestamp = items.stream().min(Comparator.comparing(Batchable::getTimestamp)) .map(Batchable::getTimestamp) .orElse(Instant.now()); } public I getIndex() { return index; } /** * @return an immutable {@link List} */ public List<T> getItems() { return items; } public Instant getOldestItemTimestamp() { return oldestItemTimestamp; } public int size() { return items.size(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Batch)) { return false; } Batch<?, ?> batch = (Batch<?, ?>) o; return Objects.equals(getIndex(), batch.getIndex()) && Objects.equals(getItems(), batch.getItems()); } @Override public String toString() { return "Batch{" + "index=" + index + ", items=" + items + ", oldestItemTimestamp=" + oldestItemTimestamp + '}'; } }
850
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/batch/EmissionStrategy.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.batch; import java.util.Queue; import java.util.stream.Stream; /** * Defines the order in which batches should be emitted to downstream subscribers */ public interface EmissionStrategy { /** * Compute the order in which batches should be emitted. * * @param candidates all batches to be emitted * @param <T> type of items in the batch * @param <I> type of the index of each batch * @return a <tt>Queue</tt> representing the order in which batches should be emitted */ <T extends Batchable<?>, I> Queue<Batch<T, I>> compute(Stream<Batch<T, I>> candidates); }
851
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/batch/LargestPerTimeBucket.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.batch; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.PriorityQueue; import java.util.Queue; import java.util.stream.Stream; import rx.Scheduler; /** * Emit batches with older items first. Bigger batches with "similar" timestamps are allowed to be emitted first, by * grouping all batches into time buckets, based on a configurable time window. * <p> * This allows items sitting on the queue for longer to be processed first, while optimistically grouping some newer * items that can be batched together with it. Configurable time window buckets allow for tunable favoring of bigger * batches, for cases where it is better to process bigger batches in front of smaller but slightly older batches. * <p> * This {@link EmissionStrategy} also allows for batches that have not been waiting in the queue for a minimum period * to be filtered out and not emitted, allowing batches to accumulate items for a minimum configurable period of time. */ public class LargestPerTimeBucket implements EmissionStrategy { private final long minimumTimeInQueueMs; private final long timeWindowBucketSizeMs; private final Scheduler scheduler; public LargestPerTimeBucket(long minimumTimeInQueueMs, long timeWindowBucketSizeMs, Scheduler scheduler) { this.minimumTimeInQueueMs = minimumTimeInQueueMs; this.timeWindowBucketSizeMs = timeWindowBucketSizeMs; this.scheduler = scheduler; } /** * Compute the order in which candidates should be emitted. * * @param candidates all candidates to be emitted * @param <T> type of items in the batch * @param <I> type of the index of each batch * @return a <tt>Queue</tt> representing the order in which candidates should be emitted */ @Override public <T extends Batchable<?>, I> Queue<Batch<T, I>> compute(Stream<Batch<T, I>> candidates) { // TODO: break too large candidates by a configurable maxBatchSize final Instant now = Instant.ofEpochMilli(scheduler.now()); final Instant cutLine = now.minus(minimumTimeInQueueMs, ChronoUnit.MILLIS); final Stream<Batch<T, I>> inQueueMinimumRequired = candidates.filter( batch -> !batch.getOldestItemTimestamp().isAfter(cutLine) ); PriorityQueue<Batch<T, I>> queue = new PriorityQueue<>(this::compare); inQueueMinimumRequired.forEach(queue::offer); return queue; } private <T extends Batchable<?>, I> int compare(Batch<T, I> one, Batch<T, I> other) { final Instant oneTimestamp = one.getOldestItemTimestamp(); final Instant otherTimestamp = other.getOldestItemTimestamp(); final long oneTimeBucket = bucketFor(oneTimestamp); final long otherTimeBucket = bucketFor(otherTimestamp); // older first final int timeBucketComparison = Long.compare(oneTimeBucket, otherTimeBucket); if (timeBucketComparison != 0) { return timeBucketComparison; } // in the same bucket, bigger batches first final int sizeComparison = Batch.bySize().reversed().compare(one, other); if (sizeComparison != 0) { return sizeComparison; } // unless they have the same size in the same bucket, in which case order by timestamp return oneTimestamp.compareTo(otherTimestamp); } private long bucketFor(Instant timestamp) { return timestamp.toEpochMilli() / timeWindowBucketSizeMs; } }
852
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/batch/Batchable.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.batch; import java.time.Instant; import java.util.Comparator; /** * Represents an item that can be batched, usually objects representing operations. Implementations of this class are * highly encouraged to be immutable, since their identifiers are held as keys in Maps. * * @param <I> type of the identifier. There will be at most one item for each identifier in a batch */ public interface Batchable<I> { final static Comparator<Batchable<?>> COMPARING_BY_PRIORITY = Comparator.comparing(Batchable::getPriority); static Comparator<Batchable<?>> byPriority() { return COMPARING_BY_PRIORITY; } /** * Two or more <tt>Batchables</tt> with equal identifiers (as defined by <tt>equals()</tt> and <tt>hashCode()</tt>) * are deduplicated in each batch. Multiple calls of this should return equivalent identifiers (as per <tt>equals()</tt> * and <tt>hashCode()</tt>). * * @return an identifier object that properly implements <tt>equals</tt> and <tt>hashCode()</tt>, so multiple * equivalent items are deduplicated in each batch */ I getIdentifier(); /** * <tt>Batchables</tt> with lower priorities (as defined by java.util.Comparable<Priority>) are dropped (ignored) * when another item with the same identifier and higher priority has been already queued. */ Priority getPriority(); /** * Older items are dropped (ignored) when there is already a more recent one (same identifier) with the same or * higher priority. */ Instant getTimestamp(); /** * Indicates when two operations would leave the system in the same state. * <p> * Implementations are encouraged to ignore the timestamp, since this is used to avoid replacing existing items * with a newer ones that would do the same. This is also used to avoid losing items when they get replaced * concurrently as they are being emitted (flushed). See {@link RateLimitedBatcher} for more details. * * @param other <tt>Batchable</tt> to compare to * @return true when both represent the same changes that would leave the system in the same state when applied */ boolean isEquivalent(Batchable<?> other); }
853
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/rx/batch/Priority.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx.batch; public enum Priority { LOW, HIGH }
854
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/histogram/HistogramDescriptor.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.histogram; import java.util.Arrays; import java.util.List; import com.google.common.base.Preconditions; import com.google.common.primitives.Longs; public class HistogramDescriptor { private final long[] valueBounds; private final List<Long> valueBoundList; private HistogramDescriptor(long[] valueBounds) { Preconditions.checkArgument(valueBounds.length > 0, "Expecting at least one element in the value bounds array"); Preconditions.checkArgument(isAscending(valueBounds), "Expected increasing sequence of numbers: %s", valueBounds); this.valueBounds = valueBounds; this.valueBoundList = Longs.asList(valueBounds); } public List<Long> getValueBounds() { return valueBoundList; } long[] newCounters() { return new long[valueBounds.length + 1]; } int positionOf(long value) { int insertionPoint = Arrays.binarySearch(valueBounds, value); if (insertionPoint >= 0) { return insertionPoint; } int position = -(insertionPoint + 1); return position; } private boolean isAscending(long[] valueBounds) { long previous = valueBounds[0]; for (int i = 1; i < valueBounds.length; i++) { if (previous >= valueBounds[i]) { return false; } previous = valueBounds[i]; } return true; } public static HistogramDescriptor histogramOf(long... valueBounds) { return new HistogramDescriptor(valueBounds); } }
855
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/histogram/Histogram.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.histogram; import java.util.List; import com.google.common.primitives.Longs; public class Histogram { private final List<Long> counters; private final HistogramDescriptor histogramDescriptor; private Histogram(List<Long> counters, HistogramDescriptor histogramDescriptor) { this.counters = counters; this.histogramDescriptor = histogramDescriptor; } public List<Long> getCounters() { return counters; } public HistogramDescriptor getHistogramDescriptor() { return histogramDescriptor; } public static Builder newBuilder(HistogramDescriptor histogramDescriptor) { return new Builder(histogramDescriptor); } public static class Builder { private final HistogramDescriptor histogramDescriptor; private final long[] counters; private Builder(HistogramDescriptor histogramDescriptor) { this.histogramDescriptor = histogramDescriptor; this.counters = histogramDescriptor.newCounters(); } public Builder increment(long value) { return add(value, 1); } public Builder add(long value, long count) { int position = histogramDescriptor.positionOf(value); counters[position] = counters[position] + count; return this; } public Histogram build() { return new Histogram(Longs.asList(counters), histogramDescriptor); } } }
856
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/histogram/RollingCount.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.histogram; import java.util.Arrays; import com.google.common.base.Preconditions; /** * Counts number of items in a rolling time window. */ public class RollingCount { private final int steps; private final long stepTimeMs; private final long[] buckets; private int bucketStart; private long startTime; private long endTime; private long now; private RollingCount(long stepTimeMs, int steps, long startTime) { this.steps = steps; this.stepTimeMs = stepTimeMs; this.buckets = new long[steps]; this.startTime = startTime; this.endTime = startTime + steps * stepTimeMs; this.now = startTime; } public long getCounts(long now) { Preconditions.checkState(now >= this.now, "Tried to check rolling count state in the past"); add(0, now); return buckets[posAt(now)]; } public long addOne(long now) { return add(1, now); } public long add(long counter, long now) { Preconditions.checkState(now >= this.now, "Tried to add rolling count item in the past"); if (now >= endTime) { adjust(now); } int insertionPoint = (int) ((now - startTime) / stepTimeMs); for (int i = insertionPoint; i < steps; i++) { buckets[(bucketStart + i) % steps] += counter; } this.now = now; return buckets[posAt(now)]; } private void adjust(long now) { int shift = (int) ((now - endTime) / stepTimeMs + 1); if (shift >= steps) { Arrays.fill(buckets, 0); this.bucketStart = 0; } else { long correction = buckets[(bucketStart + shift - 1) % steps]; for (int i = shift; i < steps; i++) { buckets[(bucketStart + i) % steps] -= correction; } long total = buckets[(bucketStart + steps - 1) % steps]; for (int i = 0; i < shift; i++) { buckets[(bucketStart + i) % steps] = total; } this.bucketStart = (bucketStart + shift) % steps; } this.startTime = startTime + shift * stepTimeMs; this.endTime = startTime + steps * stepTimeMs; this.now = now; } private int posAt(long now) { int stepIdx = (int) ((now - startTime) / stepTimeMs); return (bucketStart + stepIdx) % steps; } public static RollingCount rollingCount(long stepTimeMs, int steps, long startTime) { return new RollingCount(stepTimeMs, steps, startTime); } public static RollingCount rollingWindow(long windowSizeMs, int resolution, long startTime) { Preconditions.checkArgument(windowSizeMs > 0, "Window size must be > 0"); Preconditions.checkArgument(resolution > 0, "Resolution must be > 0"); int stepTimeMs = (int) (windowSizeMs / resolution); return new RollingCount(stepTimeMs, resolution, startTime); } }
857
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson/CommonObjectMappers.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.util.jackson; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonStreamContext; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.deser.Deserializers; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.module.SimpleDeserializers; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; import com.fasterxml.jackson.databind.ser.PropertyWriter; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import com.google.common.base.Preconditions; import com.google.protobuf.Message; import com.netflix.titus.common.util.PropertiesExt; import com.netflix.titus.common.util.ReflectionExt; import com.netflix.titus.common.util.jackson.internal.AssignableFromDeserializers; import com.netflix.titus.common.util.jackson.internal.CompositeDeserializers; import com.netflix.titus.common.util.jackson.internal.CustomDeserializerSimpleModule; import com.netflix.titus.common.util.jackson.internal.ProtobufMessageDeserializer; import com.netflix.titus.common.util.jackson.internal.ProtobufMessageSerializer; import com.netflix.titus.common.util.jackson.internal.TrimmingStringDeserializer; import rx.exceptions.Exceptions; /** * Jackon's {@link ObjectMapper} is thread safe, and uses cache for optimal performance. It makes sense * to reuse the same instance within single JVM. This class provides shared, pre-configured instances of * {@link ObjectMapper} with different configuration options. */ public class CommonObjectMappers { /** * A helper marker class for use with {@link JsonView} annotation. */ public static final class PublicView { } public static final class DebugView { } private static final ObjectMapper JACKSON_DEFAULT = new ObjectMapper(); private static final ObjectMapper DEFAULT = createDefaultMapper(); private static final ObjectMapper COMPACT = createCompactMapper(); private static final ObjectMapper PROTOBUF = createProtobufMapper(); public static ObjectMapper jacksonDefaultMapper() { return JACKSON_DEFAULT; } public static ObjectMapper defaultMapper() { return DEFAULT; } public static ObjectMapper compactMapper() { return COMPACT; } public static ObjectMapper protobufMapper() { return PROTOBUF; } public static String writeValueAsString(ObjectMapper objectMapper, Object object) { try { return objectMapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw Exceptions.propagate(e); } } public static <T> T readValue(ObjectMapper objectMapper, String json, Class<T> clazz) { try { return objectMapper.readValue(json, clazz); } catch (IOException e) { throw Exceptions.propagate(e); } } /** * Serializes only the specified fields in Titus POJOs. */ public static ObjectMapper applyFieldsFilter(ObjectMapper original, Collection<String> fields) { Preconditions.checkArgument(!fields.isEmpty(), "Fields filter, with no field names provided"); PropertiesExt.PropertyNode<Boolean> rootNode = PropertiesExt.fullSplit(fields); SimpleModule module = new SimpleModule() { @Override public void setupModule(SetupContext context) { super.setupModule(context); context.appendAnnotationIntrospector(new TitusAnnotationIntrospector()); } }; ObjectMapper newMapper = original.copy().registerModule(module); SimpleBeanPropertyFilter filter = new SimpleBeanPropertyFilter() { private PropertiesExt.PropertyNode<Boolean> findNode(JsonStreamContext outputContext) { if (outputContext.inArray()) { return findNode(outputContext.getParent()); } if (outputContext.getParent() == null) { return rootNode; } PropertiesExt.PropertyNode<Boolean> node = findNode(outputContext.getParent()); if (node == null) { return null; } if (isEnabled(node)) { return node; } return node.getChildren().get(outputContext.getCurrentName()); } @Override public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) throws Exception { PropertiesExt.PropertyNode<Boolean> selectorNode = findNode(jgen.getOutputContext().getParent()); if (selectorNode != null) { boolean enabled = isEnabled(selectorNode); if (!enabled) { PropertiesExt.PropertyNode<Boolean> childNode = selectorNode.getChildren().get(writer.getName()); if (childNode != null) { boolean isNested = !childNode.getChildren().isEmpty() && !isPrimitive(writer); enabled = isNested || isEnabled(childNode); } } if (enabled) { writer.serializeAsField(pojo, jgen, provider); return; } } if (!jgen.canOmitFields()) { writer.serializeAsOmittedField(pojo, jgen, provider); } } private boolean isPrimitive(PropertyWriter writer) { if (writer instanceof BeanPropertyWriter) { BeanPropertyWriter bw = (BeanPropertyWriter) writer; return ReflectionExt.isPrimitiveOrWrapper(bw.getType().getRawClass()); } return false; } private Boolean isEnabled(PropertiesExt.PropertyNode<Boolean> childNode) { return childNode.getValue().orElse(Boolean.FALSE); } }; newMapper.setFilterProvider(new SimpleFilterProvider().addFilter("titusFilter", filter)); return newMapper; } private static class TitusAnnotationIntrospector extends AnnotationIntrospector { @Override public Version version() { return Version.unknownVersion(); } @Override public Object findFilterId(Annotated ann) { Object id = super.findFilterId(ann); if (id == null) { String name = ann.getRawType().getName(); // TODO We hardcode here two packages. It should be configurable. if (name.startsWith("com.netflix.titus") || name.startsWith("com.netflix.managedbatch")) { id = "titusFilter"; } } return id; } } private static ObjectMapper createDefaultMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false); objectMapper.configure(MapperFeature.AUTO_DETECT_FIELDS, false); return objectMapper; } private static ObjectMapper createCompactMapper() { return new ObjectMapper(); } private static ObjectMapper createProtobufMapper() { ObjectMapper mapper = new ObjectMapper(); // Serialization mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // Deserialization mapper.disable(SerializationFeature.INDENT_OUTPUT); SimpleDeserializers simpleDeserializers = new SimpleDeserializers(); simpleDeserializers.addDeserializer(String.class, new TrimmingStringDeserializer()); List<Deserializers> deserializersList = Arrays.asList( new AssignableFromDeserializers(Message.class, new ProtobufMessageDeserializer()), simpleDeserializers ); CompositeDeserializers compositeDeserializers = new CompositeDeserializers(deserializersList); CustomDeserializerSimpleModule module = new CustomDeserializerSimpleModule(compositeDeserializers); module.addSerializer(Message.class, new ProtobufMessageSerializer()); mapper.registerModule(module); return mapper; } }
858
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson/internal/ProtobufMessageSerializer.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.util.jackson.internal; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.google.protobuf.Message; import com.google.protobuf.util.JsonFormat; public class ProtobufMessageSerializer extends JsonSerializer<Message> { @Override public void serialize(Message value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException { String jsonString = JsonFormat.printer() .includingDefaultValueFields() .print(value); jsonGenerator.writeRawValue(jsonString); } }
859
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson/internal/ProtobufMessageDeserializer.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.util.jackson.internal; import java.io.IOException; import java.lang.reflect.Method; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.deser.ContextualDeserializer; import com.google.protobuf.Message; import com.google.protobuf.util.JsonFormat; public class ProtobufMessageDeserializer extends JsonDeserializer<Message> implements ContextualDeserializer { private Class<?> type; public ProtobufMessageDeserializer() { } public ProtobufMessageDeserializer(Class<?> type) { this.type = type; } @Override public Message deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { try { Method newBuilderMethod = type.getMethod("newBuilder"); Message.Builder proto = (Message.Builder) newBuilderMethod.invoke(null); String jsonString = jsonParser.readValueAsTree().toString(); JsonFormat.parser().merge(jsonString, proto); return proto.build(); } catch (Exception e) { throw new IOException(e); } } @Override public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) throws JsonMappingException { type = context.getContextualType().getRawClass(); return new ProtobufMessageDeserializer(type); } }
860
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson/internal/TrimmingStringDeserializer.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.util.jackson.internal; import java.io.IOException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer; import com.fasterxml.jackson.databind.deser.std.StringDeserializer; import com.netflix.titus.common.util.StringExt; public class TrimmingStringDeserializer extends StdScalarDeserializer<String> { private final StringDeserializer stdDeserializer; public TrimmingStringDeserializer() { super(String.class); this.stdDeserializer = new StringDeserializer(); } @Override public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { String value = stdDeserializer.deserialize(jp, ctxt); return StringExt.isNotEmpty(value) ? value.trim() : value; } }
861
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson/internal/AssignableFromDeserializers.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.util.jackson.internal; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.DeserializationConfig; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.KeyDeserializer; import com.fasterxml.jackson.databind.deser.Deserializers; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import com.fasterxml.jackson.databind.type.ArrayType; import com.fasterxml.jackson.databind.type.CollectionLikeType; import com.fasterxml.jackson.databind.type.CollectionType; import com.fasterxml.jackson.databind.type.MapLikeType; import com.fasterxml.jackson.databind.type.MapType; import com.fasterxml.jackson.databind.type.ReferenceType; public class AssignableFromDeserializers extends Deserializers.Base { private final Class<?> assignableFromClass; private final JsonDeserializer<?> deserializer; public AssignableFromDeserializers(Class<?> assignableFromClass, JsonDeserializer<?> deserializer) { this.assignableFromClass = assignableFromClass; this.deserializer = deserializer; } @Override public JsonDeserializer<?> findEnumDeserializer(Class<?> type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException { return getDeserializer(type); } @Override public JsonDeserializer<?> findTreeNodeDeserializer(Class<? extends JsonNode> nodeType, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException { return getDeserializer(nodeType); } @Override public JsonDeserializer<?> findReferenceDeserializer(ReferenceType refType, DeserializationConfig config, BeanDescription beanDesc, TypeDeserializer contentTypeDeserializer, JsonDeserializer<?> contentDeserializer) throws JsonMappingException { return getDeserializer(refType.getRawClass()); } @Override public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException { return getDeserializer(type.getRawClass()); } @Override public JsonDeserializer<?> findArrayDeserializer(ArrayType type, DeserializationConfig config, BeanDescription beanDesc, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { return getDeserializer(type.getRawClass()); } @Override public JsonDeserializer<?> findCollectionDeserializer(CollectionType type, DeserializationConfig config, BeanDescription beanDesc, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { return getDeserializer(type.getRawClass()); } @Override public JsonDeserializer<?> findCollectionLikeDeserializer(CollectionLikeType type, DeserializationConfig config, BeanDescription beanDesc, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { return getDeserializer(type.getRawClass()); } @Override public JsonDeserializer<?> findMapDeserializer(MapType type, DeserializationConfig config, BeanDescription beanDesc, KeyDeserializer keyDeserializer, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { return getDeserializer(type.getRawClass()); } @Override public JsonDeserializer<?> findMapLikeDeserializer(MapLikeType type, DeserializationConfig config, BeanDescription beanDesc, KeyDeserializer keyDeserializer, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { return getDeserializer(type.getRawClass()); } private JsonDeserializer<?> getDeserializer(Class<?> type) { if (assignableFromClass.isAssignableFrom(type)) { return deserializer; } return null; } }
862
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson/internal/CustomDeserializerSimpleModule.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.util.jackson.internal; import com.fasterxml.jackson.databind.deser.Deserializers; import com.fasterxml.jackson.databind.module.SimpleModule; public class CustomDeserializerSimpleModule extends SimpleModule { private final Deserializers deserializers; public CustomDeserializerSimpleModule(Deserializers deserializers) { this.deserializers = deserializers; } @Override public void setupModule(SetupContext context) { super.setupModule(context); context.addDeserializers(deserializers); } }
863
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/jackson/internal/CompositeDeserializers.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.util.jackson.internal; import java.util.List; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.DeserializationConfig; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.KeyDeserializer; import com.fasterxml.jackson.databind.deser.Deserializers; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import com.fasterxml.jackson.databind.type.ArrayType; import com.fasterxml.jackson.databind.type.CollectionLikeType; import com.fasterxml.jackson.databind.type.CollectionType; import com.fasterxml.jackson.databind.type.MapLikeType; import com.fasterxml.jackson.databind.type.MapType; import com.fasterxml.jackson.databind.type.ReferenceType; /** * Aggregates multiple {@link Deserializers} and iterates through them until a non-null value is returned. * Returns null if none of the values are non-null */ public class CompositeDeserializers extends Deserializers.Base { private final List<Deserializers> deserializersList; public CompositeDeserializers(List<Deserializers> deserializers) { this.deserializersList = deserializers; } @Override public JsonDeserializer<?> findEnumDeserializer(Class<?> type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException { for (Deserializers deserializers : deserializersList) { JsonDeserializer<?> deserializer = deserializers.findEnumDeserializer(type, config, beanDesc); if (deserializer != null) { return deserializer; } } return null; } @Override public JsonDeserializer<?> findTreeNodeDeserializer(Class<? extends JsonNode> nodeType, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException { for (Deserializers deserializers : deserializersList) { JsonDeserializer<?> deserializer = deserializers.findTreeNodeDeserializer(nodeType, config, beanDesc); if (deserializer != null) { return deserializer; } } return null; } @Override public JsonDeserializer<?> findReferenceDeserializer(ReferenceType refType, DeserializationConfig config, BeanDescription beanDesc, TypeDeserializer contentTypeDeserializer, JsonDeserializer<?> contentDeserializer) throws JsonMappingException { for (Deserializers deserializers : deserializersList) { JsonDeserializer<?> deserializer = deserializers.findReferenceDeserializer(refType, config, beanDesc, contentTypeDeserializer, contentDeserializer); if (deserializer != null) { return deserializer; } } return null; } @Override public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException { for (Deserializers deserializers : deserializersList) { JsonDeserializer<?> deserializer = deserializers.findBeanDeserializer(type, config, beanDesc); if (deserializer != null) { return deserializer; } } return null; } @Override public JsonDeserializer<?> findArrayDeserializer(ArrayType type, DeserializationConfig config, BeanDescription beanDesc, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { for (Deserializers deserializers : deserializersList) { JsonDeserializer<?> deserializer = deserializers.findArrayDeserializer(type, config, beanDesc, elementTypeDeserializer, elementDeserializer); if (deserializer != null) { return deserializer; } } return null; } @Override public JsonDeserializer<?> findCollectionDeserializer(CollectionType type, DeserializationConfig config, BeanDescription beanDesc, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { for (Deserializers deserializers : deserializersList) { JsonDeserializer<?> deserializer = deserializers.findCollectionDeserializer(type, config, beanDesc, elementTypeDeserializer, elementDeserializer); if (deserializer != null) { return deserializer; } } return null; } @Override public JsonDeserializer<?> findCollectionLikeDeserializer(CollectionLikeType type, DeserializationConfig config, BeanDescription beanDesc, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { for (Deserializers deserializers : deserializersList) { JsonDeserializer<?> deserializer = deserializers.findCollectionLikeDeserializer(type, config, beanDesc, elementTypeDeserializer, elementDeserializer); if (deserializer != null) { return deserializer; } } return null; } @Override public JsonDeserializer<?> findMapDeserializer(MapType type, DeserializationConfig config, BeanDescription beanDesc, KeyDeserializer keyDeserializer, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { for (Deserializers deserializers : deserializersList) { JsonDeserializer<?> deserializer = deserializers.findMapDeserializer(type, config, beanDesc, keyDeserializer, elementTypeDeserializer, elementDeserializer); if (deserializer != null) { return deserializer; } } return null; } @Override public JsonDeserializer<?> findMapLikeDeserializer(MapLikeType type, DeserializationConfig config, BeanDescription beanDesc, KeyDeserializer keyDeserializer, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { for (Deserializers deserializers : deserializersList) { JsonDeserializer<?> deserializer = deserializers.findMapLikeDeserializer(type, config, beanDesc, keyDeserializer, elementTypeDeserializer, elementDeserializer); if (deserializer != null) { return deserializer; } } return null; } }
864
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/fit/FitActionDescriptor.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.fit; import java.util.Map; /** * Action metadata. */ public class FitActionDescriptor { private final String kind; private final String description; private final Map<String, String> configurableProperties; public FitActionDescriptor(String kind, String description, Map<String, String> configurableProperties) { this.kind = kind; this.description = description; this.configurableProperties = configurableProperties; } /** * Action type unique identifier. */ public String getKind() { return kind; } /** * Human readable action description. */ public String getDescription() { return description; } /** * Configuration properties accepted by the action. */ public Map<String, String> getConfigurableProperties() { return configurableProperties; } }
865
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/fit/FitComponent.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.fit; import java.util.List; import java.util.Optional; import java.util.function.Consumer; /** * {@link FitComponent} represents a part of an application, and it is a container for the FIT injection points. * It may contain sub-components to an arbitrary depth. */ public interface FitComponent { /** * Globally unique component identifier. */ String getId(); /** * Adds new sub-component instance. */ FitComponent createChild(String childId); /** * Gets all direct children of this component. */ List<FitComponent> getChildren(); /** * Returns a child component with the given id. * * @throws IllegalArgumentException if a child with the given id does not exist */ FitComponent getChild(String id); /** * Returns a child component with the given id if found or {@link Optional#empty()} otherwise. */ Optional<FitComponent> findChild(String id); /** * Adds new FIT injection. */ FitComponent addInjection(FitInjection fitInjection); /** * Returns all FIT injections associated with this component. */ List<FitInjection> getInjections(); /** * Returns the owned {@link FitInjection} instance with the given id. * * @throws IllegalArgumentException if an instance with the given id does not exist */ FitInjection getInjection(String id); /** * Returns the owned {@link FitInjection} instance with the given id if found or {@link Optional#empty()} otherwise. */ Optional<FitInjection> findInjection(String name); /** * Visitor pattern's acceptor that traverses the component/injector hierarchy in breadth-first order. */ void acceptInjections(Consumer<FitInjection> evaluator); }
866
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/fit/FitAction.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.fit; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import com.google.common.util.concurrent.ListenableFuture; import rx.Observable; /** * Syntactic failure generator, like exception or latency. Each action is configured to trigger either before or * after client code section. For example an action with before=true property, may trigger an error when {@link #beforeImmediate(String)} * method is called, but at the same time calls to {@link #afterImmediate(String)} are always void. */ public interface FitAction { /** * Unique action identifier with an injection point. */ String getId(); /** * Action kind descriptor. */ FitActionDescriptor getDescriptor(); /** * Action configuration data. */ Map<String, String> getProperties(); /** * Method to be called in the beginning of the client's code section. */ void beforeImmediate(String injectionPoint); /** * Method to be called at the end of the client's code section. */ void afterImmediate(String injectionPoint); /** * Method to be called at the end of the client's code section. * * @param result value returned by the client, which can be intercepted and modified by the FIT action */ default <T> T afterImmediate(String injectionPoint, T result) { afterImmediate(injectionPoint); return result; } /** * Wraps an observable to inject on subscribe or after completion errors. */ <T> Supplier<Observable<T>> aroundObservable(String injectionPoint, Supplier<Observable<T>> source); /** * Wraps a Java future to inject an error before the future creation or after it completes. */ <T> Supplier<CompletableFuture<T>> aroundCompletableFuture(String injectionPoint, Supplier<CompletableFuture<T>> source); /** * Wraps a Guava future to inject an error before the future creation or after it completes. */ <T> Supplier<ListenableFuture<T>> aroundListenableFuture(String injectionPoint, Supplier<ListenableFuture<T>> source); }
867
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/fit/FitUtil.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.fit; import java.util.Map; import java.util.function.Supplier; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.netflix.titus.common.util.ErrorGenerator; import com.netflix.titus.common.util.time.Clocks; import com.netflix.titus.common.util.unit.TimeUnitExt; /** * A collection of helper functions useful when building custom FIT actions. */ public class FitUtil { public static final Map<String, String> PERIOD_ERROR_PROPERTIES = ImmutableMap.of( "percentage", "Percentage of requests to fail (defaults to 50)", "errorTime", "Time window during which requests will fail (defaults to '1m')", "upTime", "Time window during which no errors occur (defaults to '1m')" ); public static FitComponent getFitComponentOrFail(FitFramework fitFramework, String componentId) { return fitFramework.getRootComponent() .findChild(componentId) .orElseThrow(() -> new IllegalArgumentException("FIT component not found: " + componentId)); } public static FitInjection getFitInjectionOrFail(String fitInjectionId, FitComponent fitComponent) { return fitComponent.findInjection(fitInjectionId) .orElseThrow(() -> new IllegalArgumentException("FIT injection not found: " + fitInjectionId)); } public static FitAction getFitActionOrFail(String actionId, FitInjection fitInjection) { return fitInjection.findAction(actionId) .orElseThrow(() -> new IllegalArgumentException("FIT action not found: " + actionId)); } public static Supplier<Boolean> periodicErrors(Map<String, String> properties) { double expectedRatio = Double.parseDouble(properties.getOrDefault("percentage", "100")) / 100; long errorTimeMs = TimeUnitExt.parse(properties.getOrDefault("errorTime", "1m")) .map(p -> p.getRight().toMillis(p.getLeft())) .orElseThrow(() -> new IllegalArgumentException("Invalid 'errorTime' parameter: " + properties.get("errorTime"))); long upTimeMs = TimeUnitExt.parse(properties.getOrDefault("upTime", "1m")) .map(p -> p.getRight().toMillis(p.getLeft())) .orElseThrow(() -> new IllegalArgumentException("Invalid 'upTime' parameter: " + properties.get("upTime"))); Preconditions.checkArgument(upTimeMs > 0 || errorTimeMs > 0, "Both upTime and errorTime cannot be equal to 0"); ErrorGenerator errorGenerator = ErrorGenerator.periodicFailures(upTimeMs, errorTimeMs, expectedRatio, Clocks.system()); return errorGenerator::shouldFail; } }
868
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/fit/FitInjection.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.fit; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import com.google.common.util.concurrent.ListenableFuture; import rx.Observable; /** * {@link FitInjection} represents a particular point in code or several codes for which the same FIT action or action set * should be triggered. For example a database driver API may be associated with one {@link FitInjection} instance to * generate random errors, irrespective of which operation is called. If different errors should be generated for * read and write operations, two {@link FitInjection} instances would be needed to handle each case separately. */ public interface FitInjection { /** * A unique id within a scope of {@link FitComponent} which owns this instance. */ String getId(); /** * Human readable text describing the purpose of this injection point. */ String getDescription(); /** * Exception type to throw when creating a syntactic error. */ Class<? extends Throwable> getExceptionType(); /** * Adds new FIT action. */ void addAction(FitAction action); /** * Returns all FIT actions associated with this injection point. */ List<FitAction> getActions(); /** * Gets FIT action by id. * * @throws IllegalArgumentException if action with the provided id is not found */ FitAction getAction(String actionId); /** * Returns an action with the given id if found or {@link Optional#empty()} otherwise. */ Optional<FitAction> findAction(String actionId); /** * Removes an action with the given id. * * @return true if the action was found, and removed */ boolean removeAction(String actionId); /** * Method to be called in the beginning of the client's code section. */ void beforeImmediate(String injectionPoint); /** * Method to be called at the end of the client's code section. */ void afterImmediate(String injectionPoint); /** * Method to be called at the end of the client's code section. * * @param result value returned by the client, which can be intercepted and modified by the FIT action */ <T> T afterImmediate(String injectionPoint, T result); /** * Executes before/after FIT handlers around the provided action. */ default void aroundImmediate(String injectionPoint, Runnable action) { beforeImmediate(injectionPoint); action.run(); afterImmediate(injectionPoint); } /** * Wraps an observable to inject on subscribe or after completion errors. */ <T> Observable<T> aroundObservable(String injectionPoint, Supplier<Observable<T>> source); /** * Wraps a Java future to inject an error before the future creation or after it completes. */ <T> CompletableFuture<T> aroundCompletableFuture(String injectionPoint, Supplier<CompletableFuture<T>> source); /** * Wraps a Guava future to inject an error before the future creation or after it completes. */ <T> ListenableFuture<T> aroundListenableFuture(String injectionPoint, Supplier<ListenableFuture<T>> source); interface Builder { Builder withDescription(String description); Builder withExceptionType(Class<? extends Throwable> exceptionType); FitInjection build(); } }
869
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/fit/FitFramework.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.fit; import java.util.function.Supplier; import com.netflix.titus.common.framework.fit.internal.ActiveFitFramework; import com.netflix.titus.common.framework.fit.internal.DefaultFitRegistry; import com.netflix.titus.common.framework.fit.internal.InactiveFitFramework; import com.netflix.titus.common.framework.fit.internal.action.FitErrorAction; import com.netflix.titus.common.framework.fit.internal.action.FitLatencyAction; import com.netflix.titus.common.util.tuple.Pair; import static java.util.Arrays.asList; /** * Factory methods for the FIT (Failure Injection Testing) framework. */ public abstract class FitFramework { /** * Returns true if FIT framework is activated. */ public abstract boolean isActive(); /** * Returns the default FIT action registry, with the predefined/standard action set. */ public abstract FitRegistry getFitRegistry(); /** * Top level FIT component. */ public abstract FitComponent getRootComponent(); /** * Creates a new, empty FIT component. */ public abstract FitInjection.Builder newFitInjectionBuilder(String id); /** * Creates an interface proxy with methods instrumented using the provided {@link FitInjection} instance: * <ul> * <li> * All methods returning {@link java.util.concurrent.CompletableFuture} are wrapped with * {@link FitInjection#aroundCompletableFuture(String, Supplier)} operator. * </li> * <li> * All methods returning {@link com.google.common.util.concurrent.ListenableFuture} are wrapped with * {@link FitInjection#aroundListenableFuture(String, Supplier)} operator. * </li> * <li> * All methods returning {@link rx.Observable} are wrapped with * {@link FitInjection#aroundObservable(String, Supplier)} operator. * </li> * <li> * All the remaining interface methods are assumed to be blocking, and are wrapped with * {@link FitInjection#beforeImmediate(String)}, and {@link FitInjection#afterImmediate(String)} handlers. * </li> * </ul> */ public abstract <I> I newFitProxy(I interf, FitInjection injection); /** * New active FIT framework. */ public static FitFramework newFitFramework() { return new ActiveFitFramework(newDefaultRegistry()); } /** * New inactive FIT framework. All {@link FitFramework} API methods throw an exception if called, except {@link #isActive()} * method, which can be called to check the activation status. */ public static FitFramework inactiveFitFramework() { return new InactiveFitFramework(); } private static DefaultFitRegistry newDefaultRegistry() { return new DefaultFitRegistry( asList( Pair.of(FitErrorAction.DESCRIPTOR, (id, properties) -> injection -> new FitErrorAction(id, properties, injection)), Pair.of(FitLatencyAction.DESCRIPTOR, (id, properties) -> injection -> new FitLatencyAction(id, properties, injection)) ) ); } }
870
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/fit/FitRegistry.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.fit; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; /** * A container for FIT action kinds. */ public interface FitRegistry { /** * Returns list of all known action descriptors. */ List<FitActionDescriptor> getFitActionDescriptors(); /** * Returns a FIT action factory for the provided configuration data. * <h1>Why FIT action is not created immediately?</h1> * The factory method is returned, as to finish the action construction process the {@link FitInjection} instance * is needed, and it is not always available at this stage. */ Function<FitInjection, FitAction> newFitActionFactory(String actionKind, String id, Map<String, String> properties); /** * Add new FIT action kind to the registry. * * @param descriptor action descriptor * @param factory action creator */ void registerActionKind(FitActionDescriptor descriptor, BiFunction<String, Map<String, String>, Function<FitInjection, FitAction>> factory); }
871
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/fit/AbstractFitAction.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.fit; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import com.google.common.util.concurrent.ListenableFuture; import rx.Observable; public abstract class AbstractFitAction implements FitAction { private final String id; private final FitActionDescriptor descriptor; private final Map<String, String> properties; private final FitInjection injection; protected final boolean runBefore; protected AbstractFitAction(String id, FitActionDescriptor descriptor, Map<String, String> properties, FitInjection injection) { this.id = id; this.descriptor = descriptor; this.properties = properties; this.injection = injection; this.runBefore = Boolean.parseBoolean(properties.getOrDefault("before", "true")); } @Override public String getId() { return id; } @Override public FitActionDescriptor getDescriptor() { return descriptor; } @Override public Map<String, String> getProperties() { return properties; } public FitInjection getInjection() { return injection; } @Override public void beforeImmediate(String injectionPoint) { } @Override public void afterImmediate(String injectionPoint) { } @Override public <T> T afterImmediate(String injectionPoint, T result) { return result; } @Override public <T> Supplier<Observable<T>> aroundObservable(String injectionPoint, Supplier<Observable<T>> source) { return source; } @Override public <T> Supplier<CompletableFuture<T>> aroundCompletableFuture(String injectionPoint, Supplier<CompletableFuture<T>> source) { return source; } @Override public <T> Supplier<ListenableFuture<T>> aroundListenableFuture(String injectionPoint, Supplier<ListenableFuture<T>> source) { return source; } }
872
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit/internal/FitInvocationHandler.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.fit.internal; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ListenableFuture; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.util.ReflectionExt; import rx.Observable; public class FitInvocationHandler implements InvocationHandler { private final Object delegate; private final Map<Method, Function<Object[], Object>> methodHandlers; public FitInvocationHandler(Object delegate, Map<Method, Function<Object[], Object>> methodHandlers) { this.delegate = delegate; this.methodHandlers = methodHandlers; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Function<Object[], Object> handler = methodHandlers.get(method); if (handler == null) { return method.invoke(delegate, args); } return handler.apply(args); } private static Object handleSynchronous(FitInjection injection, Method method, Object target, Object[] arguments) { injection.beforeImmediate(method.getName()); Object result; try { result = method.invoke(target, arguments); } catch (IllegalAccessException e) { throw new IllegalStateException("Reflective invocation of method not allowed: " + method.getName(), e); } catch (InvocationTargetException e) { throw new IllegalStateException("Unexpected method invocation error: " + method.getName(), e); } injection.afterImmediate(method.getName()); return result; } private static CompletableFuture<?> handleCompletableFuture(FitInjection injection, Method method, Object target, Object[] arguments) { return injection.aroundCompletableFuture(method.getName(), () -> { try { return (CompletableFuture<?>) method.invoke(target, arguments); } catch (IllegalAccessException e) { throw new IllegalStateException("Reflective invocation of method not allowed: " + method.getName(), e); } catch (InvocationTargetException e) { throw new IllegalStateException("Unexpected method invocation error: " + method.getName(), e); } }); } private static ListenableFuture<?> handleListenableFuture(FitInjection injection, Method method, Object target, Object[] arguments) { return injection.aroundListenableFuture(method.getName(), () -> { try { return (ListenableFuture<?>) method.invoke(target, arguments); } catch (IllegalAccessException e) { throw new IllegalStateException("Reflective invocation of method not allowed: " + method.getName(), e); } catch (InvocationTargetException e) { throw new IllegalStateException("Unexpected method invocation error: " + method.getName(), e); } }); } private static Observable<?> handleObservable(FitInjection injection, Method method, Object target, Object[] arguments) { return injection.aroundObservable(method.getName(), () -> { try { return (Observable<?>) method.invoke(target, arguments); } catch (IllegalAccessException e) { throw new IllegalStateException("Reflective invocation of method not allowed: " + method.getName(), e); } catch (InvocationTargetException e) { throw new IllegalStateException("Unexpected method invocation error: " + method.getName(), e); } }); } public static <I> I newProxy(Object delegate, FitInjection injection) { List<Class<?>> interfaces = ReflectionExt.findAllInterfaces(delegate.getClass()); Preconditions.checkArgument( interfaces.size() == 1, "%s expected to implement exactly one interface", delegate.getClass().getName() ); Class<?> interf = interfaces.get(0); Map<Method, Function<Object[], Object>> handlers = new HashMap<>(); for (Method method : interf.getMethods()) { Class<?> returnType = method.getReturnType(); if (returnType.isAssignableFrom(CompletableFuture.class)) { handlers.put(method, args -> handleCompletableFuture(injection, method, delegate, args)); } else if (returnType.isAssignableFrom(ListenableFuture.class)) { handlers.put(method, args -> handleListenableFuture(injection, method, delegate, args)); } else if (returnType.isAssignableFrom(Observable.class)) { handlers.put(method, args -> handleObservable(injection, method, delegate, args)); } else { handlers.put(method, args -> handleSynchronous(injection, method, delegate, args)); } } return (I) Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), new Class<?>[]{interf}, new FitInvocationHandler(delegate, handlers) ); } }
873
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit/internal/InactiveFitFramework.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.fit.internal; import com.netflix.titus.common.framework.fit.FitComponent; import com.netflix.titus.common.framework.fit.FitFramework; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.framework.fit.FitRegistry; public class InactiveFitFramework extends FitFramework { @Override public boolean isActive() { return false; } @Override public FitRegistry getFitRegistry() { throw new IllegalStateException("FIT framework not activated"); } @Override public FitComponent getRootComponent() { throw new IllegalStateException("FIT framework not activated"); } @Override public FitInjection.Builder newFitInjectionBuilder(String id) { throw new IllegalStateException("FIT framework not activated"); } @Override public <I> I newFitProxy(I interf, FitInjection injection) { throw new IllegalStateException("FIT framework not activated"); } }
874
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit/internal/DefaultFitInjection.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.fit.internal; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Supplier; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ListenableFuture; import com.netflix.titus.common.framework.fit.FitAction; import com.netflix.titus.common.framework.fit.FitInjection; import rx.Observable; public class DefaultFitInjection implements FitInjection { private final String id; private final String description; private final Class<? extends Throwable> exceptionType; private final ConcurrentMap<String, FitAction> actions = new ConcurrentHashMap<>(); private DefaultFitInjection(InternalBuilder builder) { this.id = builder.id; this.description = builder.description; this.exceptionType = builder.exceptionType; } @Override public String getId() { return id; } @Override public String getDescription() { return description; } @Override public void addAction(FitAction action) { actions.put(action.getId(), action); } @Override public Class<? extends Throwable> getExceptionType() { return exceptionType; } @Override public List<FitAction> getActions() { return new ArrayList<>(actions.values()); } @Override public FitAction getAction(String actionId) { FitAction action = actions.get(actionId); Preconditions.checkArgument(action != null, "Action %s not found", actionId); return action; } @Override public Optional<FitAction> findAction(String actionId) { return Optional.ofNullable(actions.get(actionId)); } @Override public boolean removeAction(String actionId) { return actions.remove(actionId) != null; } @Override public void beforeImmediate(String injectionPoint) { actions.values().forEach(a -> a.beforeImmediate(injectionPoint)); } @Override public void afterImmediate(String injectionPoint) { actions.values().forEach(a -> a.afterImmediate(injectionPoint)); } @Override public <T> T afterImmediate(String injectionPoint, T result) { for (FitAction fitAction : actions.values()) { result = fitAction.afterImmediate(injectionPoint, result); } return result; } @Override public <T> Observable<T> aroundObservable(String injectionPoint, Supplier<Observable<T>> source) { Supplier<Observable<T>> result = source; for (FitAction action : actions.values()) { result = action.aroundObservable(injectionPoint, source); } return result.get(); } @Override public <T> CompletableFuture<T> aroundCompletableFuture(String injectionPoint, Supplier<CompletableFuture<T>> source) { Supplier<CompletableFuture<T>> result = source; for (FitAction action : actions.values()) { result = action.aroundCompletableFuture(injectionPoint, result); } return result.get(); } @Override public <T> ListenableFuture<T> aroundListenableFuture(String injectionPoint, Supplier<ListenableFuture<T>> source) { Supplier<ListenableFuture<T>> result = source; for (FitAction action : actions.values()) { result = action.aroundListenableFuture(injectionPoint, result); } return result.get(); } public static Builder newBuilder(String id) { return new InternalBuilder(id); } private static class InternalBuilder implements Builder { private final String id; private Class<? extends Throwable> exceptionType = RuntimeException.class; private String description = "Not provided"; private InternalBuilder(String id) { this.id = id; } @Override public Builder withDescription(String description) { this.description = description; return this; } @Override public Builder withExceptionType(Class<? extends Throwable> exceptionType) { this.exceptionType = exceptionType; return this; } @Override public FitInjection build() { return new DefaultFitInjection(this); } } }
875
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit/internal/DefaultFitRegistry.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.fit.internal; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import com.google.common.base.Preconditions; import com.netflix.titus.common.framework.fit.FitAction; import com.netflix.titus.common.framework.fit.FitActionDescriptor; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.framework.fit.FitRegistry; import com.netflix.titus.common.util.tuple.Pair; public class DefaultFitRegistry implements FitRegistry { private final List<FitActionDescriptor> actionDescriptors; private final Map<String, BiFunction<String, Map<String, String>, Function<FitInjection, FitAction>>> actionFactories; public DefaultFitRegistry(List<Pair<FitActionDescriptor, BiFunction<String, Map<String, String>, Function<FitInjection, FitAction>>>> actions) { this.actionDescriptors = new CopyOnWriteArrayList<>(actions.stream().map(Pair::getLeft).collect(Collectors.toList())); this.actionFactories = new ConcurrentHashMap<>(actions.stream().collect(Collectors.toMap(p -> p.getLeft().getKind(), Pair::getRight))); } @Override public List<FitActionDescriptor> getFitActionDescriptors() { return actionDescriptors; } @Override public Function<FitInjection, FitAction> newFitActionFactory(String actionKind, String id, Map<String, String> properties) { return Preconditions.checkNotNull( actionFactories.get(actionKind), "Action kind %s not found", actionKind ).apply(id, properties); } @Override public void registerActionKind(FitActionDescriptor descriptor, BiFunction<String, Map<String, String>, Function<FitInjection, FitAction>> factory) { actionFactories.put(descriptor.getKind(), factory); actionDescriptors.add(descriptor); } }
876
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit/internal/ActiveFitFramework.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.fit.internal; import com.netflix.titus.common.framework.fit.FitComponent; import com.netflix.titus.common.framework.fit.FitFramework; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.framework.fit.FitRegistry; public class ActiveFitFramework extends FitFramework { private static final String ROOT_COMPONENT = "root"; private final FitRegistry fitRegistry; private final DefaultFitComponent rootComponent; public ActiveFitFramework(FitRegistry fitRegistry) { this.fitRegistry = fitRegistry; this.rootComponent = new DefaultFitComponent(ROOT_COMPONENT); } @Override public boolean isActive() { return true; } @Override public FitRegistry getFitRegistry() { return fitRegistry; } @Override public FitComponent getRootComponent() { return rootComponent; } @Override public FitInjection.Builder newFitInjectionBuilder(String id) { return DefaultFitInjection.newBuilder(id); } @Override public <I> I newFitProxy(I interf, FitInjection injection) { return FitInvocationHandler.newProxy(interf, injection); } }
877
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit/internal/DefaultFitComponent.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.fit.internal; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Consumer; import com.google.common.base.Preconditions; import com.netflix.titus.common.framework.fit.FitComponent; import com.netflix.titus.common.framework.fit.FitInjection; public class DefaultFitComponent implements FitComponent { private final String id; private final ConcurrentMap<String, FitComponent> children = new ConcurrentHashMap<>(); private final ConcurrentMap<String, FitInjection> injections = new ConcurrentHashMap<>(); public DefaultFitComponent(String id) { this.id = id; } @Override public String getId() { return id; } @Override public FitComponent createChild(String childId) { DefaultFitComponent newChild = new DefaultFitComponent(childId); children.put(childId, newChild); return newChild; } @Override public List<FitComponent> getChildren() { return new ArrayList<>(children.values()); } @Override public FitComponent getChild(String id) { FitComponent child = children.get(id); Preconditions.checkArgument(child != null, "FitComponent %s not found", id); return child; } @Override public Optional<FitComponent> findChild(String id) { return Optional.ofNullable(children.get(id)); } @Override public FitComponent addInjection(FitInjection injection) { injections.put(injection.getId(), injection); return this; } @Override public List<FitInjection> getInjections() { return new ArrayList<>(injections.values()); } @Override public FitInjection getInjection(String id) { return Preconditions.checkNotNull(injections.get(id), "Injection %s not found", id); } @Override public Optional<FitInjection> findInjection(String id) { return Optional.ofNullable(injections.get(id)); } @Override public void acceptInjections(Consumer<FitInjection> evaluator) { injections.values().forEach(evaluator); children.values().forEach(c -> c.acceptInjections(evaluator)); } }
878
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit/internal/action/FitErrorAction.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.fit.internal.action; import java.lang.reflect.Constructor; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import com.google.common.base.Function; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.netflix.titus.common.framework.fit.AbstractFitAction; import com.netflix.titus.common.framework.fit.FitActionDescriptor; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.framework.fit.FitUtil; import com.netflix.titus.common.util.CollectionsExt; import rx.Observable; public class FitErrorAction extends AbstractFitAction { public static final FitActionDescriptor DESCRIPTOR = new FitActionDescriptor( "exception", "Throw an exception", CollectionsExt.copyAndAdd( FitUtil.PERIOD_ERROR_PROPERTIES, "before", "Throw exception before running the downstream action (defaults to 'true')" ) ); private final Constructor<? extends Throwable> exceptionConstructor; private final Supplier<Boolean> shouldFailFunction; public FitErrorAction(String id, Map<String, String> properties, FitInjection injection) { super(id, DESCRIPTOR, properties, injection); this.shouldFailFunction = FitUtil.periodicErrors(properties); try { this.exceptionConstructor = getInjection().getExceptionType().getConstructor(String.class); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Invalid exception type: " + getInjection().getExceptionType()); } } @Override public void beforeImmediate(String injectionPoint) { if (runBefore) { doFail(injectionPoint); } } @Override public void afterImmediate(String injectionPoint) { if (!runBefore) { doFail(injectionPoint); } } @Override public <T> Supplier<Observable<T>> aroundObservable(String injectionPoint, Supplier<Observable<T>> source) { if (runBefore) { return () -> Observable.defer(() -> { doFail(injectionPoint); return source.get(); }); } return () -> source.get().concatWith(Observable.defer(() -> { doFail(injectionPoint); return Observable.empty(); })); } @Override public <T> Supplier<CompletableFuture<T>> aroundCompletableFuture(String injectionPoint, Supplier<CompletableFuture<T>> source) { if (runBefore) { return () -> { if (shouldFailFunction.get()) { CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(newException(injectionPoint)); return future; } return source.get(); }; } return () -> source.get().thenApply(result -> doFail(injectionPoint) ? null : result); } @Override public <T> Supplier<ListenableFuture<T>> aroundListenableFuture(String injectionPoint, Supplier<ListenableFuture<T>> source) { if (runBefore) { return () -> { if (shouldFailFunction.get()) { return Futures.immediateFailedFuture(newException(injectionPoint)); } return source.get(); }; } return () -> Futures.transform(source.get(), input -> doFail(injectionPoint) ? null : input, MoreExecutors.directExecutor()); } private boolean doFail(String injectionPoint) { if (shouldFailFunction.get()) { Throwable exception = newException(injectionPoint); if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } throw new RuntimeException("Wrapper", exception); } return false; } private Throwable newException(String injectionPoint) { try { return exceptionConstructor.newInstance("FIT exception at " + injectionPoint); } catch (Exception e) { throw new IllegalStateException("Cannot create FIT exception from type " + getInjection().getExceptionType(), e); } } }
879
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit/internal
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit/internal/action/FitLatencyAction.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.fit.internal.action; import java.util.Map; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.regex.Pattern; import javax.annotation.Nullable; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import com.netflix.titus.common.framework.fit.AbstractFitAction; import com.netflix.titus.common.framework.fit.FitActionDescriptor; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.util.unit.TimeUnitExt; import rx.Observable; /** * Injects latencies into a request path. */ public class FitLatencyAction extends AbstractFitAction { public static final String ACTION_ID = "latency"; public static final FitActionDescriptor DESCRIPTOR = new FitActionDescriptor( ACTION_ID, "Add latency to request execution", ImmutableMap.of( "before", "Insert latency before running the downstream action (defaults to 'true')", "latency", "Latency duration (defaults to 100ms)", "random", "If true, pick random value from range <0, latency>", "pattern", "Injection point regular expression pattern for which the FIT action is enabled" ) ); private final Supplier<Long> latencyFun; private final Pattern pattern; public FitLatencyAction(String id, Map<String, String> properties, FitInjection injection) { super(id, DESCRIPTOR, properties, injection); long latencyMs = TimeUnitExt.parse(properties.getOrDefault("latency", "100ms")) .map(p -> p.getRight().toMillis(p.getLeft())) .orElseThrow(() -> new IllegalArgumentException("Invalid 'latency' parameter: " + properties.get("latency"))); this.pattern = Pattern.compile(properties.getOrDefault("pattern", ".*")); Preconditions.checkArgument(latencyMs > 0, "Latency must be > 0: %s", latencyMs); this.latencyFun = Boolean.parseBoolean(properties.getOrDefault("random", "false")) ? newRandomGen(latencyMs) : () -> latencyMs; } private Supplier<Long> newRandomGen(long latencyMs) { Random random = new Random(); return () -> 1 + (random.nextLong() % latencyMs); } @Override public void beforeImmediate(String injectionPoint) { if (runBefore && pattern.matcher(injectionPoint).matches()) { doWait(); } } @Override public void afterImmediate(String injectionPoint) { if (!runBefore && pattern.matcher(injectionPoint).matches()) { doWait(); } } @Override public <T> Supplier<Observable<T>> aroundObservable(String injectionPoint, Supplier<Observable<T>> source) { if (!pattern.matcher(injectionPoint).matches()) { return source; } if (runBefore) { return () -> Observable.timer(latencyFun.get(), TimeUnit.MILLISECONDS).flatMap(tick -> source.get()); } return () -> source.get().concatWith((Observable<T>) Observable.timer(latencyFun.get(), TimeUnit.MILLISECONDS).ignoreElements()); } @Override public <T> Supplier<CompletableFuture<T>> aroundCompletableFuture(String injectionPoint, Supplier<CompletableFuture<T>> source) { if (!pattern.matcher(injectionPoint).matches()) { return source; } if (runBefore) { return () -> { CompletableFuture<T> future = new CompletableFuture<>(); Observable.timer(latencyFun.get(), TimeUnit.MILLISECONDS).subscribe(tick -> { if (!future.isCancelled()) { source.get().handle((result, error) -> { if (error == null) { future.complete(result); } else { future.completeExceptionally(error); } return result; }); } }); return future; }; } return () -> { CompletableFuture<T> future = new CompletableFuture<>(); source.get().handle((result, error) -> { if (error == null) { Observable.timer(latencyFun.get(), TimeUnit.MILLISECONDS).subscribe(tick -> future.complete(result)); } else { future.completeExceptionally(error); } return result; }); return future; }; } @Override public <T> Supplier<ListenableFuture<T>> aroundListenableFuture(String injectionPoint, Supplier<ListenableFuture<T>> source) { if (!pattern.matcher(injectionPoint).matches()) { return source; } if (runBefore) { return () -> { SettableFuture<T> future = SettableFuture.create(); Observable.timer(latencyFun.get(), TimeUnit.MILLISECONDS).subscribe(tick -> { if (!future.isCancelled()) { Futures.addCallback(source.get(), new FutureCallback<T>() { @Override public void onSuccess(@Nullable T result) { future.set(result); } @Override public void onFailure(Throwable error) { future.setException(error); } }, MoreExecutors.directExecutor()); } }); return future; }; } return () -> { SettableFuture<T> future = SettableFuture.create(); Futures.addCallback(source.get(), new FutureCallback<T>() { @Override public void onSuccess(@Nullable T result) { if (!future.isCancelled()) { Observable.timer(latencyFun.get(), TimeUnit.MILLISECONDS).subscribe(tick -> future.set(result)); } } @Override public void onFailure(Throwable error) { future.setException(error); } }, MoreExecutors.directExecutor()); return future; }; } private void doWait() { try { Thread.sleep(latencyFun.get()); } catch (InterruptedException ignore) { } } }
880
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/fit/adapter/GrpcFitInterceptor.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.fit.adapter; import java.util.List; import java.util.Optional; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import com.netflix.titus.common.framework.fit.FitFramework; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.framework.fit.internal.action.FitLatencyAction; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.ExceptionExt; import io.grpc.Metadata; import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.Status; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; public class GrpcFitInterceptor implements ServerInterceptor { public static final String COMPONENT = "grpcServer"; private final Optional<FitInjection> fitRequestHandler; private final Scheduler scheduler; public GrpcFitInterceptor(TitusRuntime titusRuntime, Scheduler scheduler) { this.scheduler = scheduler; FitFramework fit = titusRuntime.getFitFramework(); if (fit.isActive()) { FitInjection fitRequestHandler = fit.newFitInjectionBuilder("grpcRequestHandler") .withDescription("GRPC request handler (inject request errors or latencies") .build(); fit.getRootComponent().getChild(COMPONENT).addInjection(fitRequestHandler); this.fitRequestHandler = Optional.of(fitRequestHandler); } else { this.fitRequestHandler = Optional.empty(); } } @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { if (!fitRequestHandler.isPresent()) { return next.startCall(call, headers); } FitInjection fitInjection = fitRequestHandler.get(); String injectionPoint = call.getMethodDescriptor().getFullMethodName(); // Request failure try { fitInjection.beforeImmediate(injectionPoint); } catch (Exception e) { call.close(Status.UNAVAILABLE.withDescription("FIT server failure"), new Metadata()); return new ServerCall.Listener<ReqT>() { }; } // Increased latency. return fitInjection.findAction(FitLatencyAction.ACTION_ID) .map(action -> { int latencyMs = ExceptionExt.doTry(() -> Integer.parseInt(action.getProperties().get("latency"))).orElse(100); return new LatencyHandler<>(call, headers, next, latencyMs).getLatencyListener(); }) .orElse(next.startCall(call, headers)); } public static Optional<ServerInterceptor> getIfFitEnabled(TitusRuntime titusRuntime) { return titusRuntime.getFitFramework().isActive() ? Optional.of(new GrpcFitInterceptor(titusRuntime, Schedulers.parallel())) : Optional.empty(); } public static List<ServerInterceptor> appendIfFitEnabled(List<ServerInterceptor> original, TitusRuntime titusRuntime) { return titusRuntime.getFitFramework().isActive() ? CollectionsExt.copyAndAdd(original, new GrpcFitInterceptor(titusRuntime, Schedulers.parallel())) : original; } private class LatencyHandler<ReqT, RespT> { private final ServerCall.Listener<ReqT> latencyListener; private final AtomicReference<ServerCall.Listener<ReqT>> nextListenerRef = new AtomicReference<>(); private final BlockingQueue<Consumer<ServerCall.Listener<ReqT>>> events = new LinkedBlockingQueue<>(); private final AtomicInteger wip = new AtomicInteger(1); private final ServerCall<ReqT, RespT> call; private LatencyHandler(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next, long latencyMs) { this.call = call; // Empty action to give priority for the scheduler callback. events.offer(listener -> { }); scheduler.schedule( () -> { try { nextListenerRef.set(next.startCall(call, headers)); drain(); } catch (Exception e) { call.close(Status.INTERNAL.withDescription("Unexpected error during call processing in FIT interceptor: " + e), new Metadata()); } }, latencyMs, TimeUnit.MILLISECONDS ); this.latencyListener = new ServerCall.Listener<ReqT>() { @Override public void onMessage(ReqT message) { queueAndDrainIfReady(listener -> listener.onMessage(message)); } @Override public void onHalfClose() { queueAndDrainIfReady(ServerCall.Listener::onHalfClose); } @Override public void onCancel() { queueAndDrainIfReady(ServerCall.Listener::onCancel); } @Override public void onComplete() { queueAndDrainIfReady(ServerCall.Listener::onComplete); } @Override public void onReady() { queueAndDrainIfReady(ServerCall.Listener::onReady); } }; } private void queueAndDrainIfReady(Consumer<ServerCall.Listener<ReqT>> action) { events.offer(action); if (wip.getAndIncrement() == 0) { drain(); } } private void drain() { do { try { events.poll().accept(nextListenerRef.get()); } catch (Exception e) { call.close(Status.INTERNAL.withDescription("Unexpected error during call processing in FIT interceptor: " + e), new Metadata()); } } while (wip.decrementAndGet() != 0); } private ServerCall.Listener<ReqT> getLatencyListener() { return latencyListener; } } }
881
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/scheduler/LocalScheduler.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; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; import java.util.function.Function; import com.netflix.titus.common.framework.scheduler.model.Schedule; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.framework.scheduler.model.event.LocalSchedulerEvent; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; /** * Simple scheduler for running tasks periodically within a JVM process. */ public interface LocalScheduler { /** * Returns all schedules that are currently active. */ List<Schedule> getActiveSchedules(); /** * Returns all archived schedules. */ List<Schedule> getArchivedSchedules(); /** * Returns schedule with the given id. * * @throws LocalSchedulerException if a schedule with the given id does not exist. */ default Schedule getSchedule(String scheduleId) { return findSchedule(scheduleId).orElseThrow(() -> LocalSchedulerException.scheduleNotFound(scheduleId)); } /** * Returns schedule with the given id if it exists or {@link Optional#empty()}. */ Optional<Schedule> findSchedule(String scheduleId); /** * Emits event for each schedule state change. */ Flux<LocalSchedulerEvent> events(); /** * Schedule {@link Mono} action. */ ScheduleReference scheduleMono(ScheduleDescriptor scheduleDescriptor, Function<ExecutionContext, Mono<Void>> actionProducer, Scheduler scheduler); /** * This method enhances the periodic action execution with reactive stream based triggers. For each item * emitted by the trigger stream, a new action is scheduled (serialized). */ default <TRIGGER> ScheduleReference scheduleMono(ScheduleDescriptor scheduleDescriptor, TRIGGER timeTrigger, Function<TRIGGER, Mono<Void>> actionProducer, Flux<TRIGGER> trigger, Scheduler scheduler) { throw new IllegalStateException("not implemented yet"); } /** * Schedule an action which is executed synchronously. If the action execution time is long (>1ms), set * isolated flag to true. Isolated actions run on their own thread. */ ScheduleReference schedule(ScheduleDescriptor scheduleDescriptor, Consumer<ExecutionContext> action, boolean isolated); /** * Schedule an action which is executed synchronously using the provided {@link java.util.concurrent.ExecutorService}. */ ScheduleReference schedule(ScheduleDescriptor scheduleDescriptor, Consumer<ExecutionContext> action, ExecutorService executorService); /** * Cancel a schedule with the given id. */ Mono<Void> cancel(String scheduleId); }
882
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/scheduler/ExecutionContext.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; import java.util.Optional; import com.netflix.titus.common.framework.scheduler.model.ExecutionId; import com.netflix.titus.common.framework.scheduler.model.ScheduledAction; public class ExecutionContext { private final String id; private final ExecutionId executionId; private final ScheduledAction currentAction; private final Optional<ScheduledAction> previousAction; private ExecutionContext(String id, ExecutionId executionId, ScheduledAction currentAction, Optional<ScheduledAction> previousAction) { this.id = id; this.executionId = executionId; this.currentAction = currentAction; this.previousAction = previousAction; } public String getId() { return id; } public ExecutionId getExecutionId() { return executionId; } public ScheduledAction getCurrentAction() { return currentAction; } public Optional<ScheduledAction> getPreviousAction() { return previousAction; } public Builder toBuilder() { return newBuilder().withId(id).withIteration(executionId); } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private String id; private ScheduledAction currentAction; private ScheduledAction previousAction; private ExecutionId executionId; private Builder() { } public Builder withId(String id) { this.id = id; return this; } public Builder withIteration(ExecutionId executionId) { this.executionId = executionId; return this; } public Builder withCurrentAction(ScheduledAction currentAction) { this.currentAction = currentAction; return this; } public Builder withPreviousAction(ScheduledAction previousAction) { this.previousAction = previousAction; return this; } public ExecutionContext build() { return new ExecutionContext(id, executionId, currentAction, Optional.ofNullable(previousAction)); } } }
883
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/scheduler/LocalSchedulerException.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; public class LocalSchedulerException extends RuntimeException { public enum ErrorCode { Cancelled, NotFound } private final ErrorCode errorCode; private LocalSchedulerException(ErrorCode errorCode, String message) { super(message); this.errorCode = errorCode; } public ErrorCode getErrorCode() { return errorCode; } public static LocalSchedulerException cancelled() { return new LocalSchedulerException(ErrorCode.Cancelled, "Cancelled"); } public static LocalSchedulerException scheduleNotFound(String scheduleId) { return new LocalSchedulerException(ErrorCode.NotFound, String.format("Schedule not found: id=%s", scheduleId)); } }
884
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/scheduler/ScheduleReference.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; import com.netflix.titus.common.framework.scheduler.model.Schedule; public interface ScheduleReference { Schedule getSchedule(); boolean isClosed(); void cancel(); }
885
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/internal/ScheduleMetrics.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.internal; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.common.framework.scheduler.model.Schedule; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus.SchedulingState; import com.netflix.titus.common.util.spectator.SpectatorExt; import com.netflix.titus.common.util.spectator.SpectatorExt.FsmMetrics; import com.netflix.titus.common.util.time.Clock; /** * Single schedule metrics. */ class ScheduleMetrics { static final String ROOT_NAME = "titus.localScheduler."; private final Clock clock; private final Registry registry; private final Counter successes; private final Counter failures; private final Id waitingId; private final Id runningId; private final Id cancellingId; private FsmMetrics<SchedulingState> currentState; private Schedule lastSchedule; ScheduleMetrics(Schedule schedule, Clock clock, Registry registry) { this.lastSchedule = schedule; this.clock = clock; this.registry = registry; this.currentState = SpectatorExt.fsmMetrics( registry.createId(ROOT_NAME + "scheduleState", "scheduleName", schedule.getDescriptor().getName()), SchedulingState::isFinal, SchedulingState.Waiting, registry ); this.successes = registry.counter(ROOT_NAME + "executions", "scheduleName", schedule.getDescriptor().getName(), "status", "succeeded" ); this.failures = registry.counter(ROOT_NAME + "executions", "scheduleName", schedule.getDescriptor().getName(), "status", "failed" ); this.waitingId = registry.createId(ROOT_NAME + "waitingTimeMs", "scheduleName", schedule.getDescriptor().getName()); PolledMeter.using(registry) .withId(waitingId) .monitorValue(this, self -> howLongInState(SchedulingState.Waiting)); this.runningId = registry.createId(ROOT_NAME + "runningTimeMs", "scheduleName", schedule.getDescriptor().getName()); PolledMeter.using(registry) .withId(runningId) .monitorValue(this, self -> howLongInState(SchedulingState.Running)); this.cancellingId = registry.createId(ROOT_NAME + "cancellingTimeMs", "scheduleName", schedule.getDescriptor().getName()); PolledMeter.using(registry) .withId(cancellingId) .monitorValue(this, self -> howLongInState(SchedulingState.Cancelling)); } void onNewScheduledActionExecutor(Schedule schedule) { this.lastSchedule = schedule; currentState.transition(SchedulingState.Waiting); } void onSchedulingStateUpdate(Schedule schedule) { this.lastSchedule = schedule; SchedulingState state = schedule.getCurrentAction().getStatus().getState(); if (state.isFinal()) { if (state == SchedulingState.Succeeded) { successes.increment(); } else { failures.increment(); } } else { currentState.transition(state); } } void onScheduleRemoved(Schedule schedule) { this.lastSchedule = schedule; currentState.transition(SchedulingState.Failed); PolledMeter.remove(registry, waitingId); PolledMeter.remove(registry, runningId); PolledMeter.remove(registry, cancellingId); } private long howLongInState(SchedulingState expectedState) { SchedulingState state = lastSchedule.getCurrentAction().getStatus().getState(); if (state != expectedState) { return 0; } return clock.wallTime() - lastSchedule.getCurrentAction().getStatus().getTimestamp(); } }
886
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/internal/SchedulerMetrics.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.internal; import java.util.concurrent.TimeUnit; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.common.util.time.Clock; class SchedulerMetrics { private final DefaultLocalScheduler scheduler; private final Clock clock; private final Registry registry; private final Id activeSchedulesId; private final Id archivedSchedulesId; private final Id lastEvaluationId; private final Timer evaluationTimer; private long lastEvaluationTime; SchedulerMetrics(DefaultLocalScheduler scheduler, Clock clock, Registry registry) { this.clock = clock; this.registry = registry; this.scheduler = scheduler; this.lastEvaluationTime = clock.wallTime(); this.activeSchedulesId = registry.createId(ScheduleMetrics.ROOT_NAME + "active"); PolledMeter.using(registry) .withId(activeSchedulesId) .monitorValue(this, self -> self.scheduler.getActiveSchedules().size()); this.archivedSchedulesId = registry.createId(ScheduleMetrics.ROOT_NAME + "archived"); PolledMeter.using(registry) .withId(activeSchedulesId) .monitorValue(this, self -> self.scheduler.getArchivedSchedules().size()); this.evaluationTimer = registry.timer(ScheduleMetrics.ROOT_NAME + "evaluationTime"); this.lastEvaluationId = registry.createId(ScheduleMetrics.ROOT_NAME + "lastEvaluationMs"); PolledMeter.using(registry) .withId(lastEvaluationId) .monitorValue(this, self -> self.clock.wallTime() - self.lastEvaluationTime); } void shutdown() { PolledMeter.remove(registry, activeSchedulesId); PolledMeter.remove(registry, archivedSchedulesId); PolledMeter.remove(registry, lastEvaluationId); } void recordEvaluationTime(long evaluationTimeMs) { this.lastEvaluationTime = clock.wallTime(); evaluationTimer.record(evaluationTimeMs, TimeUnit.MILLISECONDS); } }
887
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/internal/LocalSchedulerTransactionLogger.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.internal; import java.time.Duration; import java.util.List; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.common.framework.scheduler.LocalScheduler; import com.netflix.titus.common.framework.scheduler.model.Schedule; import com.netflix.titus.common.framework.scheduler.model.ScheduledAction; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus.SchedulingState; import com.netflix.titus.common.framework.scheduler.model.event.LocalSchedulerEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleAddedEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleRemovedEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleUpdateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.util.retry.Retry; import static com.netflix.titus.common.util.CollectionsExt.last; class LocalSchedulerTransactionLogger { private static final Logger logger = LoggerFactory.getLogger("LocalSchedulerTransactionLogger"); private static final Duration RETRY_DELAY = Duration.ofSeconds(1); static Disposable logEvents(LocalScheduler localScheduler) { return localScheduler.events() .retryWhen(Retry.fixedDelay(1, RETRY_DELAY)) .subscribe( event -> { boolean failure = event.getSchedule().getCurrentAction().getStatus().getError().isPresent(); if (failure) { logger.info(doFormat(event)); } else { logger.debug(doFormat(event)); } }, e -> logger.error("Event stream terminated with an error", e), () -> logger.info("Event stream completed") ); } @VisibleForTesting static String doFormat(LocalSchedulerEvent event) { if (event instanceof ScheduleAddedEvent) { return logScheduleAddedEvent((ScheduleAddedEvent) event); } else if (event instanceof ScheduleRemovedEvent) { return logScheduleRemovedEvent((ScheduleRemovedEvent) event); } if (event instanceof ScheduleUpdateEvent) { return logScheduleUpdateEvent((ScheduleUpdateEvent) event); } return "Unknown event type: " + event.getClass(); } private static String logScheduleAddedEvent(ScheduleAddedEvent event) { return doFormat(event.getSchedule(), "ScheduleAdded", "New schedule added"); } private static String logScheduleRemovedEvent(ScheduleRemovedEvent event) { return doFormat(event.getSchedule(), "ScheduleRemoved", "Schedule removed"); } private static String logScheduleUpdateEvent(ScheduleUpdateEvent event) { SchedulingStatus status = event.getSchedule().getCurrentAction().getStatus(); SchedulingState schedulingState = status.getState(); String summary; switch (schedulingState) { case Waiting: summary = "Waiting..."; break; case Running: summary = "Running..."; break; case Cancelling: summary = "Schedule cancelled by a user"; break; case Succeeded: summary = "Scheduled action completed"; break; case Failed: summary = "Scheduled action failed: error=" + status.getError().map(Throwable::getMessage).orElse("<error_not_available>"); break; default: summary = "Unknown scheduling state: schedulingState=" + schedulingState; } return doFormat(event.getSchedule(), "ExecutionUpdate", summary); } private static String doFormat(Schedule schedule, String eventKind, String summary) { ScheduledAction action = schedule.getCurrentAction(); return String.format( "name=%-20s eventKind=%-15s iteration=%-6s state=%-10s %-15s summary=%s", schedule.getDescriptor().getName(), eventKind, action.getExecutionId().getId() + "." + action.getExecutionId().getAttempt(), action.getStatus().getState(), "elapsed=" + toElapsedMs(schedule) + "ms", summary ); } private static long toElapsedMs(Schedule schedule) { SchedulingStatus currentStatus = schedule.getCurrentAction().getStatus(); if (currentStatus.getState() != SchedulingState.Waiting) { List<SchedulingStatus> statusHistory = schedule.getCurrentAction().getStatusHistory(); return currentStatus.getTimestamp() - last(statusHistory).getTimestamp(); } // Report time between the new action, and the previous one if (schedule.getCompletedActions().isEmpty()) { return 0; } ScheduledAction previousAction = last(schedule.getCompletedActions()); return currentStatus.getTimestamp() - previousAction.getStatus().getTimestamp(); } }
888
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/internal/ScheduledActionExecutor.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.internal; import java.util.List; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import java.util.function.Function; import com.google.common.base.Preconditions; import com.netflix.titus.common.framework.scheduler.ExecutionContext; import com.netflix.titus.common.framework.scheduler.LocalSchedulerException; import com.netflix.titus.common.framework.scheduler.model.ExecutionId; import com.netflix.titus.common.framework.scheduler.model.Schedule; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.framework.scheduler.model.ScheduledAction; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus.SchedulingState; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.ExceptionExt; import com.netflix.titus.common.util.retry.Retryer; import com.netflix.titus.common.util.time.Clock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; /** * {@link ScheduledActionExecutor} handles lifecycle of a single action, which transitions trough * waiting -> running -> cancelling (optionally) -> succeeded | failed states. */ class ScheduledActionExecutor { private static final Logger logger = LoggerFactory.getLogger(ScheduledActionExecutor.class); private static final int SCHEDULE_HISTORY_LIMIT = 5; private final ScheduleDescriptor descriptor; private final Function<ExecutionContext, Mono<Void>> actionProducer; private final Scheduler scheduler; private final Clock clock; private volatile Schedule schedule; private final ScheduleMetrics scheduleMetrics; private volatile ScheduledAction action; private volatile Retryer retryer; private volatile Disposable actionDisposable; // We need this extra coordination, as disposable may become disposed before onError/onCompleted callbacks complete. private volatile boolean actionCompleted; private volatile Throwable error; ScheduledActionExecutor(Schedule schedule, ScheduleMetrics scheduleMetrics, Function<ExecutionContext, Mono<Void>> actionProducer, Scheduler scheduler, Clock clock) { this.schedule = schedule; this.descriptor = schedule.getDescriptor(); this.scheduleMetrics = scheduleMetrics; this.actionProducer = actionProducer; this.scheduler = scheduler; this.clock = clock; this.action = schedule.getCurrentAction(); scheduleMetrics.onNewScheduledActionExecutor(this.getSchedule()); } Schedule getSchedule() { return schedule; } ScheduledAction getAction() { return action; } /** * Invocations serialized with cancel. */ boolean handleExecution() { SchedulingState state = action.getStatus().getState(); switch (state) { case Waiting: boolean changed = handleWaitingState(); if (changed) { scheduleMetrics.onSchedulingStateUpdate(this.getSchedule()); } return changed; case Running: boolean runningChanged = handleRunningState(); if (runningChanged) { scheduleMetrics.onSchedulingStateUpdate(this.getSchedule()); } return runningChanged; case Cancelling: boolean cancellingChanged = handleCancellingState(); if (cancellingChanged) { scheduleMetrics.onScheduleRemoved(this.getSchedule()); } return cancellingChanged; case Succeeded: case Failed: Preconditions.checkState(false, "Invocation of the terminated action executor: state={}", state); } Preconditions.checkState(false, "Unrecognized state: {}", state); return false; } ScheduledActionExecutor nextScheduledActionExecutor(boolean retried) { Schedule newSchedule = schedule.toBuilder() .withCurrentAction(newScheduledAction(retried)) .withCompletedActions(appendToCompletedActions()) .build(); return new ScheduledActionExecutor( newSchedule, scheduleMetrics, actionProducer, scheduler, clock ); } /** * Invocations serialized with handleExecution. */ boolean cancel() { if (action.getStatus().getState().isFinal()) { return false; } this.action = changeState(builder -> builder.withState(SchedulingState.Cancelling)); this.schedule = schedule.toBuilder().withCurrentAction(action).build(); if (actionDisposable != null) { actionDisposable.dispose(); } return true; } private ScheduledAction newScheduledAction(boolean retried) { long now = clock.wallTime(); boolean effectivelyRetried = retried && retryer != null && retryer.getDelayMs().isPresent(); long delayMs = effectivelyRetried ? retryer.getDelayMs().orElse(descriptor.getInterval().toMillis()) : descriptor.getInterval().toMillis(); return ScheduledAction.newBuilder() .withId(schedule.getId()) .withStatus(SchedulingStatus.newBuilder() .withState(SchedulingState.Waiting) .withExpectedStartTime(now + delayMs) .withTimestamp(now) .build() ) .withIteration(effectivelyRetried ? ExecutionId.nextAttempt(action.getExecutionId()) : ExecutionId.nextIteration(action.getExecutionId()) ) .build(); } private List<ScheduledAction> appendToCompletedActions() { List<ScheduledAction> completedActions = CollectionsExt.copyAndAdd(schedule.getCompletedActions(), action); if (completedActions.size() > SCHEDULE_HISTORY_LIMIT) { completedActions = completedActions.subList(completedActions.size() - SCHEDULE_HISTORY_LIMIT, completedActions.size()); } return completedActions; } private boolean handleWaitingState() { long now = clock.wallTime(); if (action.getStatus().getExpectedStartTime() > now) { return false; } SchedulingStatus oldStatus = action.getStatus(); this.action = action.toBuilder() .withStatus(SchedulingStatus.newBuilder() .withState(SchedulingState.Running) .withTimestamp(now) .build() ) .withStatusHistory(CollectionsExt.copyAndAdd(action.getStatusHistory(), oldStatus)) .build(); this.schedule = schedule.toBuilder().withCurrentAction(action).build(); try { this.retryer = descriptor.getRetryerSupplier().get(); this.actionCompleted = false; this.error = null; this.actionDisposable = actionProducer .apply( ExecutionContext.newBuilder() .withId(schedule.getId()) .withIteration(action.getExecutionId()) .build() ) .timeout(descriptor.getTimeout()) .subscribeOn(scheduler) .publishOn(scheduler) .doOnCancel(() -> actionCompleted = true) .subscribe( next -> { // Never }, e -> { if (logger.isDebugEnabled()) { logger.warn("Action execution error: name={}", descriptor.getName(), e); } Throwable effectiveError = e; if (e instanceof TimeoutException) { effectiveError = new TimeoutException(String.format("Action did not complete in time: timeout=%sms", descriptor.getTimeout().toMillis())); } Throwable finalEffectiveError = effectiveError; ExceptionExt.silent(() -> descriptor.getOnErrorHandler().accept(action, finalEffectiveError)); this.error = effectiveError; this.actionCompleted = true; }, () -> { ExceptionExt.silent(() -> descriptor.getOnSuccessHandler().accept(action)); this.actionCompleted = true; } ); } catch (Exception e) { logger.warn("Could not produce action: name={}", descriptor.getName(), e); this.action = newFailedStatus(); } return true; } private boolean handleRunningState() { if (!actionDisposable.isDisposed() || !actionCompleted) { return false; } this.action = error == null ? changeState(builder -> builder.withState(SchedulingState.Succeeded)) : newFailedStatus(); this.schedule = schedule.toBuilder().withCurrentAction(action).build(); return true; } private boolean handleCancellingState() { if (actionDisposable != null && !actionDisposable.isDisposed()) { return false; } this.error = LocalSchedulerException.cancelled(); this.action = newFailedStatus(); this.schedule = schedule.toBuilder().withCurrentAction(action).build(); return true; } private ScheduledAction changeState(Consumer<SchedulingStatus.Builder> updater) { SchedulingStatus.Builder statusBuilder = SchedulingStatus.newBuilder() .withTimestamp(clock.wallTime()); updater.accept(statusBuilder); SchedulingStatus oldStatus = action.getStatus(); List<SchedulingStatus> statusHistory = CollectionsExt.copyAndAdd(action.getStatusHistory(), oldStatus); return action.toBuilder() .withStatus(statusBuilder.build()) .withStatusHistory(statusHistory) .build(); } private ScheduledAction newFailedStatus() { return changeState(builder -> builder.withState(SchedulingState.Failed).withError(error)); } }
889
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/internal/DefaultLocalScheduler.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.internal; 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.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import com.google.common.base.Stopwatch; import com.netflix.spectator.api.Registry; import com.netflix.titus.common.framework.scheduler.ExecutionContext; import com.netflix.titus.common.framework.scheduler.LocalScheduler; import com.netflix.titus.common.framework.scheduler.LocalSchedulerException; import com.netflix.titus.common.framework.scheduler.ScheduleReference; import com.netflix.titus.common.framework.scheduler.model.ExecutionId; import com.netflix.titus.common.framework.scheduler.model.Schedule; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.framework.scheduler.model.ScheduledAction; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus.SchedulingState; import com.netflix.titus.common.framework.scheduler.model.event.LocalSchedulerEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleAddedEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleRemovedEvent; import com.netflix.titus.common.framework.scheduler.model.event.ScheduleUpdateEvent; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.common.util.time.Clock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.core.publisher.DirectProcessor; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; public class DefaultLocalScheduler implements LocalScheduler { private static final Logger logger = LoggerFactory.getLogger(DefaultLocalScheduler.class); private static final ThreadGroup SCHEDULER_THREAD_GROUP = new ThreadGroup("LocalScheduler"); private static final Runnable DO_NOTHING = () -> { }; private final long internalLoopIntervalMs; private final Clock clock; private final Registry registry; private final Scheduler scheduler; private final Scheduler.Worker worker; private final BlockingQueue<ScheduleHolder> newHolders = new LinkedBlockingQueue<>(); private final ConcurrentMap<String, ScheduleHolder> activeHoldersById = new ConcurrentHashMap<>(); private final ConcurrentMap<String, Schedule> archivedSchedulesById = new ConcurrentHashMap<>(); private final DirectProcessor<LocalSchedulerEvent> eventProcessor = DirectProcessor.create(); private final SchedulerMetrics metrics; private final Disposable transactionLoggerDisposable; public DefaultLocalScheduler(Duration internalLoopInterval, Scheduler scheduler, Clock clock, Registry registry) { this.internalLoopIntervalMs = internalLoopInterval.toMillis(); this.scheduler = scheduler; this.clock = clock; this.registry = registry; this.worker = scheduler.createWorker(); this.metrics = new SchedulerMetrics(this, clock, registry); this.transactionLoggerDisposable = LocalSchedulerTransactionLogger.logEvents(this); scheduleNextIteration(); } public void shutdown() { worker.dispose(); metrics.shutdown(); ReactorExt.safeDispose(transactionLoggerDisposable); } @Override public List<Schedule> getActiveSchedules() { Map<String, Schedule> all = new HashMap<>(); activeHoldersById.forEach((id, h) -> all.put(id, h.getSchedule())); newHolders.forEach(h -> all.put(h.getSchedule().getId(), h.getSchedule())); return new ArrayList<>(all.values()); } @Override public List<Schedule> getArchivedSchedules() { return new ArrayList<>(archivedSchedulesById.values()); } @Override public Optional<Schedule> findSchedule(String scheduleId) { ScheduleHolder holder = activeHoldersById.get(scheduleId); if (holder == null) { holder = newHolders.stream().filter(h -> h.getSchedule().getId().equals(scheduleId)).findFirst().orElse(null); } return Optional.ofNullable(holder).map(ScheduleHolder::getSchedule); } @Override public Flux<LocalSchedulerEvent> events() { return eventProcessor; } @Override public ScheduleReference scheduleMono(ScheduleDescriptor scheduleDescriptor, Function<ExecutionContext, Mono<Void>> actionProducer, Scheduler scheduler) { return scheduleInternal(scheduleDescriptor, actionProducer, scheduler, DO_NOTHING); } @Override public ScheduleReference schedule(ScheduleDescriptor scheduleDescriptor, Consumer<ExecutionContext> action, boolean isolated) { ExecutorService executorService = isolated ? Executors.newSingleThreadScheduledExecutor(r -> { Thread thread = new Thread(SCHEDULER_THREAD_GROUP, r, scheduleDescriptor.getName()); thread.setDaemon(true); return thread; }) : null; return schedule(scheduleDescriptor, action, executorService); } @Override public ScheduleReference schedule(ScheduleDescriptor scheduleDescriptor, Consumer<ExecutionContext> action, ExecutorService executorService) { Scheduler actionScheduler; Runnable cleanup; if (executorService != null) { actionScheduler = Schedulers.fromExecutorService(executorService); cleanup = executorService::shutdown; } else { actionScheduler = this.scheduler; cleanup = DO_NOTHING; } return scheduleInternal(scheduleDescriptor, executionContext -> Mono.defer(() -> { try { action.accept(executionContext); return Mono.empty(); } catch (Exception e) { return Mono.error(e); } }), actionScheduler, cleanup); } private ScheduleReference scheduleInternal(ScheduleDescriptor descriptor, Function<ExecutionContext, Mono<Void>> actionProducer, Scheduler scheduler, Runnable cleanup) { String scheduleId = UUID.randomUUID().toString(); ScheduleHolder scheduleHolder = new ScheduleHolder(scheduleId, descriptor, actionProducer, scheduler, cleanup); newHolders.add(scheduleHolder); return scheduleHolder.getReference(); } @Override public Mono<Void> cancel(String scheduleId) { return ReactorExt.onWorker(() -> { ScheduleHolder holder = activeHoldersById.get(scheduleId); if (holder == null) { throw LocalSchedulerException.scheduleNotFound(scheduleId); } holder.cancelInternal(); }, worker); } private void scheduleNextIteration() { worker.schedule(this::doRun, internalLoopIntervalMs, TimeUnit.MILLISECONDS); } private void doRun() { Stopwatch timer = Stopwatch.createStarted(); List<ScheduleHolder> holders = new ArrayList<>(); newHolders.drainTo(holders); holders.forEach(h -> { activeHoldersById.put(h.getSchedule().getId(), h); eventProcessor.onNext(new ScheduleAddedEvent(h.getSchedule())); }); try { activeHoldersById.values().forEach(ScheduleHolder::handleExecution); } catch (Exception e) { logger.warn("Unexpected error in the internal scheduler loop", e); } finally { scheduleNextIteration(); metrics.recordEvaluationTime(timer.elapsed(TimeUnit.MILLISECONDS)); } } private class ScheduleHolder { private final Runnable cleanup; private final ScheduleReference reference; private volatile ScheduledActionExecutor executor; private volatile boolean closed; private ScheduleHolder(String scheduleId, ScheduleDescriptor descriptor, Function<ExecutionContext, Mono<Void>> actionProducer, Scheduler scheduler, Runnable cleanup) { ScheduledAction firstAction = ScheduledAction.newBuilder() .withId(scheduleId) .withStatus(SchedulingStatus.newBuilder() .withState(SchedulingState.Waiting) .withExpectedStartTime(clock.wallTime() + descriptor.getInitialDelay().toMillis()) .withTimestamp(clock.wallTime()) .build() ) .withIteration(ExecutionId.initial()) .build(); Schedule schedule = Schedule.newBuilder() .withId(scheduleId) .withDescriptor(descriptor) .withCurrentAction(firstAction) .withCompletedActions(Collections.emptyList()) .build(); this.executor = new ScheduledActionExecutor(schedule, new ScheduleMetrics(schedule, clock, registry), actionProducer, scheduler, clock); this.cleanup = cleanup; this.reference = new ScheduleReference() { @Override public Schedule getSchedule() { return executor.getSchedule(); } @Override public boolean isClosed() { return closed && executor.getAction().getStatus().getState().isFinal(); } @Override public void cancel() { // Run the cancel request via event loop so it is properly serialized with other concurrent updates. DefaultLocalScheduler.this.cancel(scheduleId).subscribe( next -> logger.debug("Action cancelled by a user: {}", executor.getAction().getExecutionId()), e -> logger.debug("User triggered action cancellation failed with an error: executionId={}", executor.getAction().getExecutionId(), e) ); } }; } private Schedule getSchedule() { return executor.getSchedule(); } private ScheduleReference getReference() { return reference; } /** * Must be called from the within an event loop. */ private void cancelInternal() { if (closed) { return; } boolean cancelled; synchronized (this) { closed = true; cancelled = executor.cancel(); } if (cancelled) { eventProcessor.onNext(new ScheduleUpdateEvent(executor.getSchedule())); } } /** * Must be called from the within an event loop. */ private void handleExecution() { if (!executor.handleExecution()) { return; } Schedule currentSchedule = executor.getSchedule(); eventProcessor.onNext(new ScheduleUpdateEvent(currentSchedule)); SchedulingState currentState = executor.getAction().getStatus().getState(); if (currentState.isFinal()) { boolean nextIteration; synchronized (this) { nextIteration = !closed; if (nextIteration) { this.executor = executor.nextScheduledActionExecutor(currentState == SchedulingState.Failed); } } if (nextIteration) { eventProcessor.onNext(new ScheduleUpdateEvent(executor.getSchedule())); } else { doCleanup(); } } } private void doCleanup() { Schedule schedule = executor.getSchedule(); try { cleanup.run(); } catch (Exception e) { logger.warn("Cleanup action failed for schedule: name={}", schedule.getDescriptor().getName(), e); } finally { activeHoldersById.remove(schedule.getId()); archivedSchedulesById.put(schedule.getId(), schedule); eventProcessor.onNext(new ScheduleRemovedEvent(schedule)); } } } }
890
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/endpoint/LocalSchedulerResource.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.endpoint; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.netflix.titus.common.framework.scheduler.LocalScheduler; import com.netflix.titus.common.framework.scheduler.endpoint.representation.EvictionRepresentations; import com.netflix.titus.common.framework.scheduler.endpoint.representation.ScheduleRepresentation; import com.netflix.titus.common.runtime.TitusRuntime; @Path("/api/diagnostic/localScheduler") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Singleton public class LocalSchedulerResource { private final LocalScheduler localScheduler; @Inject public LocalSchedulerResource(TitusRuntime titusRuntime) { this.localScheduler = titusRuntime.getLocalScheduler(); } @GET @Path("/schedules") public List<ScheduleRepresentation> getActiveSchedules() { return localScheduler.getActiveSchedules().stream().map(EvictionRepresentations::toRepresentation).collect(Collectors.toList()); } @GET @Path("/schedules/{name}") public ScheduleRepresentation getActiveSchedule(@PathParam("name") String name) { return localScheduler.getActiveSchedules().stream() .filter(s -> s.getDescriptor().getName().equals(name)) .findFirst() .map(EvictionRepresentations::toRepresentation) .orElseThrow(() -> new WebApplicationException(Response.status(404).build())); } @GET @Path("/archived") public List<ScheduleRepresentation> getArchivedSchedules() { return localScheduler.getArchivedSchedules().stream() .map(EvictionRepresentations::toRepresentation) .collect(Collectors.toList()); } @GET @Path("/archived/{name}") public ScheduleRepresentation getArchivedSchedule(@PathParam("name") String name) { return localScheduler.getArchivedSchedules().stream() .filter(s -> s.getDescriptor().getName().equals(name)) .findFirst() .map(EvictionRepresentations::toRepresentation) .orElseThrow(() -> new WebApplicationException(Response.status(404).build())); } }
891
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/endpoint
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/endpoint/representation/EvictionRepresentations.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.endpoint.representation; import java.util.stream.Collectors; import com.netflix.titus.common.framework.scheduler.model.ExecutionId; import com.netflix.titus.common.framework.scheduler.model.Schedule; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.framework.scheduler.model.ScheduledAction; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus; import com.netflix.titus.common.util.DateTimeExt; public final class EvictionRepresentations { private EvictionRepresentations() { } public static ScheduleRepresentation toRepresentation(Schedule core) { return new ScheduleRepresentation( core.getId(), toRepresentation(core.getDescriptor()), toRepresentation(core.getCurrentAction()), core.getCompletedActions().stream().map(EvictionRepresentations::toRepresentation).collect(Collectors.toList()) ); } private static ScheduleDescriptorRepresentation toRepresentation(ScheduleDescriptor descriptor) { return new ScheduleDescriptorRepresentation( descriptor.getName(), descriptor.getDescription(), DateTimeExt.toTimeUnitString(descriptor.getInitialDelay().toMillis()), DateTimeExt.toTimeUnitString(descriptor.getInterval().toMillis()), DateTimeExt.toTimeUnitString(descriptor.getTimeout().toMillis()) ); } private static ScheduledActionRepresentation toRepresentation(ScheduledAction currentAction) { return new ScheduledActionRepresentation( currentAction.getId(), doFormat(currentAction.getExecutionId()), toRepresentation(currentAction.getStatus()), currentAction.getStatusHistory().stream().map(EvictionRepresentations::toRepresentation).collect(Collectors.toList()) ); } private static String doFormat(ExecutionId executionId) { return String.format("%s.%s(%s)", executionId.getId(), executionId.getAttempt(), executionId.getTotal()); } private static SchedulingStatusRepresentation toRepresentation(SchedulingStatus status) { return new SchedulingStatusRepresentation( status.getState(), DateTimeExt.toUtcDateTimeString(status.getTimestamp()), DateTimeExt.toUtcDateTimeString(status.getExpectedStartTime()), status.getError().map(Throwable::getMessage).orElse(null) ); } }
892
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/endpoint
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/endpoint/representation/SchedulingStatusRepresentation.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.endpoint.representation; import com.netflix.titus.common.framework.scheduler.model.SchedulingStatus.SchedulingState; public class SchedulingStatusRepresentation { private final SchedulingState state; private final String timestamp; private final String expectedStartTime; private final String error; public SchedulingStatusRepresentation(SchedulingState state, String timestamp, String expectedStartTime, String error) { this.state = state; this.timestamp = timestamp; this.expectedStartTime = expectedStartTime; this.error = error; } public SchedulingState getState() { return state; } public String getTimestamp() { return timestamp; } public String getExpectedStartTime() { return expectedStartTime; } public String getError() { return error; } }
893
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/endpoint
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/endpoint/representation/ScheduleDescriptorRepresentation.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.endpoint.representation; public class ScheduleDescriptorRepresentation { private final String name; private final String description; private final String initialDelay; private final String interval; private final String timeout; public ScheduleDescriptorRepresentation(String name, String description, String initialDelay, String interval, String timeout) { this.name = name; this.description = description; this.initialDelay = initialDelay; this.interval = interval; this.timeout = timeout; } public String getName() { return name; } public String getDescription() { return description; } public String getInitialDelay() { return initialDelay; } public String getInterval() { return interval; } public String getTimeout() { return timeout; } }
894
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/endpoint
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/endpoint/representation/ScheduledActionRepresentation.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.endpoint.representation; import java.util.List; public class ScheduledActionRepresentation { private final String id; private final String executionId; private final SchedulingStatusRepresentation status; private final List<SchedulingStatusRepresentation> statusHistory; public ScheduledActionRepresentation(String id, String executionId, SchedulingStatusRepresentation status, List<SchedulingStatusRepresentation> statusHistory) { this.id = id; this.executionId = executionId; this.status = status; this.statusHistory = statusHistory; } public String getId() { return id; } public String getExecutionId() { return executionId; } public SchedulingStatusRepresentation getStatus() { return status; } public List<SchedulingStatusRepresentation> getStatusHistory() { return statusHistory; } }
895
0
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/endpoint
Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/framework/scheduler/endpoint/representation/ScheduleRepresentation.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.endpoint.representation; import java.util.List; public class ScheduleRepresentation { private final String id; private final ScheduleDescriptorRepresentation scheduleDescriptor; private final ScheduledActionRepresentation currentAction; private final List<ScheduledActionRepresentation> completedActions; public ScheduleRepresentation(String id, ScheduleDescriptorRepresentation scheduleDescriptor, ScheduledActionRepresentation currentAction, List<ScheduledActionRepresentation> completedActions) { this.id = id; this.scheduleDescriptor = scheduleDescriptor; this.currentAction = currentAction; this.completedActions = completedActions; } public String getId() { return id; } public ScheduleDescriptorRepresentation getScheduleDescriptor() { return scheduleDescriptor; } public ScheduledActionRepresentation getCurrentAction() { return currentAction; } public List<ScheduledActionRepresentation> getCompletedActions() { return completedActions; } }
896
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/ScheduleDescriptor.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.time.Duration; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Supplier; import com.google.common.base.Preconditions; import com.netflix.titus.common.util.retry.Retryer; import com.netflix.titus.common.util.retry.Retryers; public class ScheduleDescriptor { private final String name; private final String description; private final Duration initialDelay; private final Duration interval; private final Supplier<Retryer> retryerSupplier; private final Duration timeout; private final Consumer<ScheduledAction> onSuccessHandler; private final BiConsumer<ScheduledAction, Throwable> onErrorHandler; private ScheduleDescriptor(String name, String description, Duration initialDelay, Duration interval, Duration timeout, Supplier<Retryer> retryerSupplier, Consumer<ScheduledAction> onSuccessHandler, BiConsumer<ScheduledAction, Throwable> onErrorHandler) { this.name = name; this.description = description; this.initialDelay = initialDelay; this.interval = interval; this.retryerSupplier = retryerSupplier; this.timeout = timeout; this.onSuccessHandler = onSuccessHandler; this.onErrorHandler = onErrorHandler; } public String getName() { return name; } public String getDescription() { return description; } public Supplier<Retryer> getRetryerSupplier() { return retryerSupplier; } public Duration getInitialDelay() { return initialDelay; } public Duration getInterval() { return interval; } public Duration getTimeout() { return timeout; } public Consumer<ScheduledAction> getOnSuccessHandler() { return onSuccessHandler; } public BiConsumer<ScheduledAction, Throwable> getOnErrorHandler() { return onErrorHandler; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ScheduleDescriptor that = (ScheduleDescriptor) o; return Objects.equals(name, that.name) && Objects.equals(description, that.description) && Objects.equals(initialDelay, that.initialDelay) && Objects.equals(interval, that.interval) && Objects.equals(retryerSupplier, that.retryerSupplier) && Objects.equals(timeout, that.timeout) && Objects.equals(onSuccessHandler, that.onSuccessHandler) && Objects.equals(onErrorHandler, that.onErrorHandler); } @Override public int hashCode() { return Objects.hash(name, description, initialDelay, interval, retryerSupplier, timeout, onSuccessHandler, onErrorHandler); } @Override public String toString() { return "ScheduleDescriptor{" + "name='" + name + '\'' + ", description='" + description + '\'' + ", initialDelay=" + initialDelay + ", interval=" + interval + ", retryerSupplier=" + retryerSupplier + ", timeout=" + timeout + ", onSuccessHandler=" + onSuccessHandler + ", onErrorHandler=" + onErrorHandler + '}'; } public Builder toBuilder() { return newBuilder() .withName(name) .withDescription(description) .withInitialDelay(initialDelay) .withInterval(interval) .withRetryerSupplier(retryerSupplier) .withTimeout(timeout) .withOnSuccessHandler(onSuccessHandler) .withOnErrorHandler(onErrorHandler); } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private String name; private String description; private Duration initialDelay; private Duration interval; private Duration timeout; private Supplier<Retryer> retryerSupplier = () -> Retryers.exponentialBackoff(1, 5, TimeUnit.SECONDS); private Consumer<ScheduledAction> onSuccessHandler = schedule -> { }; private BiConsumer<ScheduledAction, Throwable> onErrorHandler = (schedule, error) -> { }; private Builder() { } public Builder withName(String name) { this.name = name; return this; } public Builder withDescription(String description) { this.description = description; return this; } public Builder withInitialDelay(Duration initialDelay) { this.initialDelay = initialDelay; return this; } public Builder withInterval(Duration interval) { if (initialDelay == null) { this.initialDelay = interval; } this.interval = interval; return this; } public Builder withTimeout(Duration timeout) { this.timeout = timeout; return this; } public Builder withRetryerSupplier(Supplier<Retryer> retryerSupplier) { this.retryerSupplier = retryerSupplier; return this; } public Builder withOnErrorHandler(BiConsumer<ScheduledAction, Throwable> onErrorHandler) { this.onErrorHandler = onErrorHandler; return this; } public Builder withOnSuccessHandler(Consumer<ScheduledAction> onSuccessHandler) { this.onSuccessHandler = onSuccessHandler; return this; } public ScheduleDescriptor build() { Preconditions.checkNotNull(name, "name cannot be null"); Preconditions.checkNotNull(description, "description cannot be null"); Preconditions.checkNotNull(initialDelay, "initial delay cannot be null"); Preconditions.checkNotNull(interval, "interval cannot be null"); Preconditions.checkNotNull(timeout, "timeout cannot be null"); Preconditions.checkNotNull(retryerSupplier, "retryerSupplier cannot be null"); Preconditions.checkNotNull(onSuccessHandler, "onSuccessHandler cannot be null"); Preconditions.checkNotNull(onErrorHandler, "onErrorHandler cannot be null"); return new ScheduleDescriptor(name, description, initialDelay, interval, timeout, retryerSupplier, onSuccessHandler, onErrorHandler); } } }
897
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/Schedule.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 Schedule { private final String id; private final ScheduleDescriptor descriptor; private final ScheduledAction currentAction; private final List<ScheduledAction> completedActions; public Schedule(String id, ScheduleDescriptor descriptor, ScheduledAction currentAction, List<ScheduledAction> completedActions) { this.id = id; this.descriptor = descriptor; this.currentAction = currentAction; this.completedActions = completedActions; } public String getId() { return id; } public ScheduleDescriptor getDescriptor() { return descriptor; } public ScheduledAction getCurrentAction() { return currentAction; } public List<ScheduledAction> getCompletedActions() { return completedActions; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Schedule schedule = (Schedule) o; return Objects.equals(id, schedule.id) && Objects.equals(descriptor, schedule.descriptor) && Objects.equals(currentAction, schedule.currentAction) && Objects.equals(completedActions, schedule.completedActions); } @Override public int hashCode() { return Objects.hash(id, descriptor, currentAction, completedActions); } public Builder toBuilder() { return newBuilder().withId(id).withDescriptor(descriptor).withCurrentAction(currentAction).withCompletedActions(completedActions); } @Override public String toString() { return "Schedule{" + "id='" + id + '\'' + ", descriptor=" + descriptor + ", currentAction=" + currentAction + ", completedActions=" + completedActions + '}'; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private String id; private ScheduleDescriptor descriptor; private ScheduledAction currentAction; private List<ScheduledAction> completedActions = Collections.emptyList(); private Builder() { } public Builder withId(String id) { this.id = id; return this; } public Builder withDescriptor(ScheduleDescriptor descriptor) { this.descriptor = descriptor; return this; } public Builder withCurrentAction(ScheduledAction currentAction) { this.currentAction = currentAction; return this; } public Builder withCompletedActions(List<ScheduledAction> completedActions) { this.completedActions = completedActions; return this; } public Schedule build() { Preconditions.checkNotNull(id, "id cannot be null"); Preconditions.checkNotNull(descriptor, "descriptor cannot be null"); Preconditions.checkNotNull(currentAction, "currentAction cannot be null"); Preconditions.checkNotNull(completedActions, "completedActions cannot be null"); return new Schedule(id, descriptor, currentAction, completedActions); } } }
898
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/SchedulingStatus.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; import java.util.Optional; import com.google.common.base.Preconditions; public class SchedulingStatus { public enum SchedulingState { Waiting, Running, Cancelling, Succeeded, Failed; public boolean isFinal() { return this == Succeeded || this == Failed; } } private final SchedulingState state; private final long timestamp; private final long expectedStartTime; private final Optional<Throwable> error; private SchedulingStatus(SchedulingState state, long timestamp, long expectedStartTime, Optional<Throwable> error) { this.state = state; this.timestamp = timestamp; this.expectedStartTime = expectedStartTime; this.error = error; } public SchedulingState getState() { return state; } public long getTimestamp() { return timestamp; } public long getExpectedStartTime() { return expectedStartTime; } public Optional<Throwable> getError() { return error; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SchedulingStatus that = (SchedulingStatus) o; return timestamp == that.timestamp && expectedStartTime == that.expectedStartTime && state == that.state && Objects.equals(error, that.error); } @Override public int hashCode() { return Objects.hash(state, timestamp, expectedStartTime, error); } public Builder toBuilder() { return newBuilder().withState(state).withTimestamp(timestamp).withExpectedStartTime(expectedStartTime).withError(error.orElse(null)); } @Override public String toString() { return "SchedulingStatus{" + "state=" + state + ", timestamp=" + timestamp + ", expectedStartTime=" + expectedStartTime + ", error=" + error + '}'; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private SchedulingState state; private long timestamp; private long expectedStartTime; private Throwable error; private Builder() { } public Builder withState(SchedulingState state) { this.state = state; return this; } public Builder withTimestamp(long timestamp) { this.timestamp = timestamp; return this; } public Builder withExpectedStartTime(long expectedStartTime) { this.expectedStartTime = expectedStartTime; return this; } public Builder withError(Throwable error) { this.error = error; return this; } public SchedulingStatus build() { Preconditions.checkNotNull(state, "state cannot be null"); return new SchedulingStatus(state, timestamp, expectedStartTime, Optional.ofNullable(error)); } } }
899