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/limiter | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket/ImmutableTokenBucket.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.limiter.tokenbucket;
import java.util.Optional;
import com.netflix.titus.common.util.tuple.Pair;
/**
*/
public interface ImmutableTokenBucket {
interface ImmutableRefillStrategy {
Pair<ImmutableRefillStrategy, Long> consume();
}
/**
* Attempt to take a token from the bucket.
*
* @return {@link Optional#empty()} if not enough tokens available, or {@link ImmutableTokenBucket} containing one token less
*/
default Optional<ImmutableTokenBucket> tryTake() {
return tryTake(1);
}
/**
* Attempt to take a token from the bucket.
*
* @param numberOfTokens the number of tokens to take
* @return {@link Optional#empty()} if not enough tokens available, or {@link ImmutableTokenBucket} with 'numberOfTokens' less
*/
default Optional<ImmutableTokenBucket> tryTake(long numberOfTokens) {
return tryTake(numberOfTokens, numberOfTokens).map(Pair::getRight);
}
/**
* Attempt to take at least min number of tokens, up to max if more available.
*
* @return {@link Optional#empty()} if less then min tokens available, or a pir of values with the first one
* being number of tokens consumed, and the second one {@link ImmutableTokenBucket} with the tokens consumed
*/
Optional<Pair<Long, ImmutableTokenBucket>> tryTake(long min, long max);
}
| 700 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket/FixedIntervalTokenBucketConfiguration.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.limiter.tokenbucket;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
@Configuration(prefix = "titus.common.tokenBucket")
public interface FixedIntervalTokenBucketConfiguration {
@DefaultValue("1")
long getCapacity();
@DefaultValue("0")
long getInitialNumberOfTokens();
@DefaultValue("1000")
long getIntervalMs();
@DefaultValue("1")
long getNumberOfTokensPerInterval();
}
| 701 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/DefaultImmutableTokenBucket.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.limiter.tokenbucket.internal;
import java.util.Optional;
import com.netflix.titus.common.util.limiter.tokenbucket.ImmutableTokenBucket;
import com.netflix.titus.common.util.tuple.Pair;
/**
*/
public class DefaultImmutableTokenBucket implements ImmutableTokenBucket {
private final ImmutableRefillStrategy refillStrategy;
private final long bucketSize;
private final long bucketLevel;
public DefaultImmutableTokenBucket(long bucketSize, long bucketLevel, ImmutableRefillStrategy refillStrategy) {
this.bucketSize = bucketSize;
this.bucketLevel = bucketLevel;
this.refillStrategy = refillStrategy;
}
@Override
public Optional<Pair<Long, ImmutableTokenBucket>> tryTake(long min, long max) {
if (bucketLevel >= max) {
return Optional.of(Pair.of(max, new DefaultImmutableTokenBucket(bucketSize, bucketLevel - max, refillStrategy)));
}
Pair<ImmutableRefillStrategy, Long> consumed = refillStrategy.consume();
long refill = consumed.getRight();
ImmutableRefillStrategy newRefillStrategyInstance = consumed.getLeft();
if (refill == 0) {
if (bucketLevel >= min) {
return Optional.of(Pair.of(bucketLevel, new DefaultImmutableTokenBucket(bucketSize, 0, refillStrategy)));
}
} else {
long newBucketLevel = Math.min(bucketSize, bucketLevel + refill);
if (newBucketLevel >= min) {
long tokensToTake = Math.min(newBucketLevel, max);
return Optional.of(Pair.of(tokensToTake, new DefaultImmutableTokenBucket(bucketSize, newBucketLevel - tokensToTake, newRefillStrategyInstance)));
}
}
return Optional.empty();
}
}
| 702 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/SpectatorRefillStrategyDecorator.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.limiter.tokenbucket.internal;
import java.util.concurrent.TimeUnit;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.limiter.tokenbucket.RefillStrategy;
/**
* Adds Spectator metrics to a {@link RefillStrategy} instance.
*/
public class SpectatorRefillStrategyDecorator implements RefillStrategy {
private static final String NAME_PREFIX = "titus.common.tokenBucket.refillStrategy.";
private final RefillStrategy delegate;
private final Counter refillCounter;
private final Id timeUntilNextRefillId;
private final Registry registry;
public SpectatorRefillStrategyDecorator(String bucketName,
RefillStrategy delegate,
TitusRuntime titusRuntime) {
this.delegate = delegate;
this.registry = titusRuntime.getRegistry();
this.refillCounter = registry.counter(
NAME_PREFIX + "refillCount",
"bucketName", bucketName
);
this.timeUntilNextRefillId = registry.createId(
NAME_PREFIX + "timeUntilNextRefill",
"bucketName", bucketName
);
PolledMeter.using(registry)
.withId(timeUntilNextRefillId)
.monitorValue(this, self -> self.getTimeUntilNextRefill(TimeUnit.MILLISECONDS));
}
public void shutdown() {
PolledMeter.remove(registry, timeUntilNextRefillId);
}
@Override
public long refill() {
long refill = delegate.refill();
refillCounter.increment(refill);
return refill;
}
@Override
public long getTimeUntilNextRefill(TimeUnit unit) {
return delegate.getTimeUntilNextRefill(unit);
}
@Override
public String toString() {
return delegate.toString();
}
}
| 703 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/TokenBucketDelegate.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.limiter.tokenbucket.internal;
import com.netflix.titus.common.util.limiter.tokenbucket.RefillStrategy;
import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket;
public class TokenBucketDelegate implements TokenBucket {
private final TokenBucket delegate;
public TokenBucketDelegate(TokenBucket delegate) {
this.delegate = delegate;
}
@Override
public String getName() {
return delegate.getName();
}
@Override
public long getCapacity() {
return delegate.getCapacity();
}
@Override
public long getNumberOfTokens() {
return delegate.getNumberOfTokens();
}
@Override
public boolean tryTake() {
return delegate.tryTake();
}
@Override
public boolean tryTake(long numberOfTokens) {
return delegate.tryTake(numberOfTokens);
}
@Override
public void take() {
delegate.take();
}
@Override
public void take(long numberOfTokens) {
delegate.take(numberOfTokens);
}
@Override
public void refill(long numberOfToken) {
delegate.refill(numberOfToken);
}
@Override
public RefillStrategy getRefillStrategy() {
return delegate.getRefillStrategy();
}
@Override
public String toString() {
return delegate.toString();
}
}
| 704 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/ImmutableFixedIntervalRefillStrategy.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.limiter.tokenbucket.internal;
import com.netflix.titus.common.util.limiter.tokenbucket.ImmutableTokenBucket.ImmutableRefillStrategy;
import com.netflix.titus.common.util.time.Clock;
import com.netflix.titus.common.util.tuple.Pair;
/**
*/
public class ImmutableFixedIntervalRefillStrategy implements ImmutableRefillStrategy {
private final long numberOfTokensPerInterval;
private final long intervalNs;
private final Clock clock;
private final long startTimeNs;
private final Pair<ImmutableRefillStrategy, Long> noProgressReply;
public ImmutableFixedIntervalRefillStrategy(long numberOfTokensPerInterval, long intervalNs, Clock clock) {
this.numberOfTokensPerInterval = numberOfTokensPerInterval;
this.intervalNs = intervalNs;
this.clock = clock;
this.startTimeNs = clock.nanoTime();
this.noProgressReply = Pair.of(this, 0L);
}
@Override
public Pair<ImmutableRefillStrategy, Long> consume() {
long refills = getRefills();
if (refills == 0) {
return noProgressReply;
}
return Pair.of(new ImmutableFixedIntervalRefillStrategy(numberOfTokensPerInterval, intervalNs, clock), refills);
}
private long getRefills() {
long elapsed = clock.nanoTime() - startTimeNs;
return numberOfTokensPerInterval * (elapsed / intervalNs);
}
}
| 705 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/SpectatorTokenBucketDecorator.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.limiter.tokenbucket.internal;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket;
public class SpectatorTokenBucketDecorator extends TokenBucketDelegate {
private static final String NAME_PREFIX = "titus.common.tokenBucket.";
private final Counter takeSuccessCounter;
private final Counter takeFailureCounter;
public SpectatorTokenBucketDecorator(TokenBucket delegate, TitusRuntime titusRuntime) {
super(delegate);
Registry registry = titusRuntime.getRegistry();
this.takeSuccessCounter = registry.counter(
NAME_PREFIX + "tokenRequest",
"bucketName", delegate.getName(),
"success", "true"
);
this.takeFailureCounter = registry.counter(
NAME_PREFIX + "tokenRequest",
"bucketName", delegate.getName(),
"success", "false"
);
PolledMeter.using(registry).withId(registry.createId(
NAME_PREFIX + "capacity",
"bucketName", delegate.getName(),
"available", "false"
)).monitorValue(this, self -> self.getCapacity() - self.getNumberOfTokens());
PolledMeter.using(registry).withId(registry.createId(
NAME_PREFIX + "capacity",
"bucketName", delegate.getName(),
"available", "true"
)).monitorValue(this, TokenBucketDelegate::getNumberOfTokens);
}
@Override
public boolean tryTake() {
boolean success = super.tryTake();
recordTokenRequest(success, 1);
return success;
}
@Override
public boolean tryTake(long numberOfTokens) {
boolean success = super.tryTake(numberOfTokens);
recordTokenRequest(success, numberOfTokens);
return success;
}
@Override
public void take() {
super.take();
recordTokenRequest(true, 1);
}
@Override
public void take(long numberOfTokens) {
super.take(numberOfTokens);
recordTokenRequest(true, numberOfTokens);
}
private void recordTokenRequest(boolean success, long count) {
if (success) {
takeSuccessCounter.increment(count);
} else {
takeFailureCounter.increment(count);
}
}
}
| 706 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/DynamicTokenBucketDelegate.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.limiter.tokenbucket.internal;
import java.util.function.Supplier;
import com.netflix.titus.common.util.limiter.tokenbucket.RefillStrategy;
import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket;
public class DynamicTokenBucketDelegate implements TokenBucket {
private final Supplier<TokenBucket> tokenBucketSupplier;
public DynamicTokenBucketDelegate(Supplier<TokenBucket> tokenBucketSupplier) {
this.tokenBucketSupplier = tokenBucketSupplier;
}
@Override
public String getName() {
return tokenBucketSupplier.get().getName();
}
@Override
public long getCapacity() {
return tokenBucketSupplier.get().getCapacity();
}
@Override
public long getNumberOfTokens() {
return tokenBucketSupplier.get().getNumberOfTokens();
}
@Override
public boolean tryTake() {
return tokenBucketSupplier.get().tryTake();
}
@Override
public boolean tryTake(long numberOfTokens) {
return tokenBucketSupplier.get().tryTake(numberOfTokens);
}
@Override
public void take() {
tokenBucketSupplier.get().take();
}
@Override
public void take(long numberOfTokens) {
tokenBucketSupplier.get().take(numberOfTokens);
}
@Override
public void refill(long numberOfToken) {
tokenBucketSupplier.get().refill(numberOfToken);
}
@Override
public RefillStrategy getRefillStrategy() {
return tokenBucketSupplier.get().getRefillStrategy();
}
@Override
public String toString() {
return tokenBucketSupplier.get().toString();
}
}
| 707 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/DefaultTokenBucket.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.limiter.tokenbucket.internal;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.util.concurrent.Uninterruptibles;
import com.netflix.titus.common.util.limiter.tokenbucket.RefillStrategy;
import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket;
public class DefaultTokenBucket implements TokenBucket {
private final Object mutex = new Object();
private final String name;
private final long capacity;
private final RefillStrategy refillStrategy;
private volatile long numberOfTokens;
public DefaultTokenBucket(String name, long capacity, RefillStrategy refillStrategy, long initialNumberOfTokens) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(name), "Name must not be null or empty.");
Preconditions.checkArgument(capacity > 0, "Capacity must be greater than 0.");
Preconditions.checkNotNull(refillStrategy);
Preconditions.checkArgument(initialNumberOfTokens >= 0, "Capacity must not be negative.");
this.name = name;
this.capacity = capacity;
this.refillStrategy = refillStrategy;
this.numberOfTokens = initialNumberOfTokens;
}
@Override
public String getName() {
return name;
}
@Override
public long getCapacity() {
return capacity;
}
@Override
public long getNumberOfTokens() {
refill(refillStrategy.refill());
return numberOfTokens;
}
@Override
public boolean tryTake() {
return tryTake(1);
}
@Override
public boolean tryTake(long numberOfTokens) {
Preconditions.checkArgument(numberOfTokens > 0, "Number of tokens must be greater than 0.");
Preconditions.checkArgument(numberOfTokens <= capacity, "Number of tokens must not be greater than the capacity.");
// Quick path if no refill.
if (refillStrategy.getTimeUntilNextRefill(TimeUnit.MILLISECONDS) > 0) {
if (numberOfTokens > this.numberOfTokens) {
return false;
}
synchronized (mutex) {
if (numberOfTokens <= this.numberOfTokens) {
this.numberOfTokens -= numberOfTokens;
return true;
}
}
return false;
}
synchronized (mutex) {
long refill = refillStrategy.refill();
if (refill > 0) {
refillInternal(refill);
}
if (numberOfTokens <= this.numberOfTokens) {
this.numberOfTokens -= numberOfTokens;
return true;
}
return false;
}
}
@Override
public void take() {
take(1);
}
@Override
public void take(long numberOfTokens) {
Preconditions.checkArgument(numberOfTokens > 0, "Number of tokens must be greater than 0.");
Preconditions.checkArgument(numberOfTokens <= capacity, "Number of tokens must not be greater than the capacity.");
while (true) {
if (tryTake(numberOfTokens)) {
break;
}
long timeUntilNextRefill = refillStrategy.getTimeUntilNextRefill(TimeUnit.NANOSECONDS);
if (timeUntilNextRefill > 0) {
Uninterruptibles.sleepUninterruptibly(timeUntilNextRefill, TimeUnit.NANOSECONDS);
}
}
}
@Override
public void refill(long numberOfTokens) {
synchronized (mutex) {
refillInternal(numberOfTokens);
}
}
private void refillInternal(long numberOfTokens) {
this.numberOfTokens = Math.min(capacity, Math.max(0, this.numberOfTokens + numberOfTokens));
}
@Override
public RefillStrategy getRefillStrategy() {
return refillStrategy;
}
@Override
public String toString() {
return "DefaultTokenBucket{" +
"name='" + name + '\'' +
", capacity=" + capacity +
", refillStrategy=" + refillStrategy +
", numberOfTokens=" + numberOfTokens +
'}';
}
}
| 708 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/FixedIntervalRefillStrategy.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.limiter.tokenbucket.internal;
import java.util.concurrent.TimeUnit;
import com.netflix.titus.common.util.DateTimeExt;
import com.netflix.titus.common.util.limiter.tokenbucket.RefillStrategy;
import com.netflix.titus.common.util.time.Clock;
public class FixedIntervalRefillStrategy implements RefillStrategy {
private final Object mutex = new Object();
private final long numberOfTokensPerInterval;
private final long intervalInNanos;
private final String toStringValue;
private long lastRefillTimeNano;
/**
* Make it volatile, so we do not have to sync for reading.
*/
private volatile long nextRefillTimeNano;
private final Clock clock;
public FixedIntervalRefillStrategy(long numberOfTokensPerInterval, long interval, TimeUnit unit, Clock clock) {
this.numberOfTokensPerInterval = numberOfTokensPerInterval;
this.clock = clock;
this.intervalInNanos = unit.toNanos(interval);
this.toStringValue = "FixedIntervalRefillStrategy{refillRate=" + DateTimeExt.toRateString(interval, numberOfTokensPerInterval, unit, "refill") + '}';
long nowNano = clock.nanoTime();
this.lastRefillTimeNano = nowNano - intervalInNanos;
this.nextRefillTimeNano = nowNano - intervalInNanos;
}
@Override
public long refill() {
long nowNano = clock.nanoTime();
if (nowNano < nextRefillTimeNano) {
return 0;
}
synchronized (mutex) {
if (nowNano < nextRefillTimeNano) {
return 0;
}
long numberOfIntervals = Math.max(0, (nowNano - lastRefillTimeNano) / intervalInNanos);
lastRefillTimeNano += numberOfIntervals * intervalInNanos;
nextRefillTimeNano = lastRefillTimeNano + intervalInNanos;
return numberOfIntervals * numberOfTokensPerInterval;
}
}
@Override
public long getTimeUntilNextRefill(TimeUnit unit) {
long nowNano = clock.nanoTime();
return unit.convert(Math.max(0, nextRefillTimeNano - nowNano), TimeUnit.NANOSECONDS);
}
@Override
public String toString() {
return toStringValue;
}
}
| 709 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/limiter/tokenbucket/internal/FixedIntervalTokenBucketSupplier.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.limiter.tokenbucket.internal;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.Evaluators;
import com.netflix.titus.common.util.ExceptionExt;
import com.netflix.titus.common.util.limiter.tokenbucket.FixedIntervalTokenBucketConfiguration;
import com.netflix.titus.common.util.limiter.tokenbucket.RefillStrategy;
import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket;
import com.netflix.titus.common.util.time.Clocks;
/**
* {@link TokenBucket} supplier which recreates a token bucket if any of its configurable parameters changes.
* The configuration parameters are read from {@link FixedIntervalTokenBucketConfiguration}.
*/
public class FixedIntervalTokenBucketSupplier implements Supplier<TokenBucket> {
private final String name;
private final FixedIntervalTokenBucketConfiguration configuration;
private final Consumer<TokenBucket> onChangeListener;
private final Optional<TitusRuntime> titusRuntime;
private volatile ActiveConfiguration activeConfiguration;
private final Object lock = new Object();
public FixedIntervalTokenBucketSupplier(String name,
FixedIntervalTokenBucketConfiguration configuration,
Consumer<TokenBucket> onChangeListener,
Optional<TitusRuntime> titusRuntime) {
this.name = name;
this.configuration = configuration;
this.onChangeListener = onChangeListener;
this.titusRuntime = titusRuntime;
this.activeConfiguration = reload();
}
@Override
public TokenBucket get() {
return isSame() ? activeConfiguration.getTokenBucket() : reload().getTokenBucket();
}
private boolean isSame() {
return activeConfiguration != null
&& activeConfiguration.getCapacity() == configuration.getCapacity()
&& activeConfiguration.getInitialNumberOfTokens() == configuration.getInitialNumberOfTokens()
&& activeConfiguration.getIntervalMs() == configuration.getIntervalMs()
&& activeConfiguration.getNumberOfTokensPerInterval() == configuration.getNumberOfTokensPerInterval();
}
private ActiveConfiguration reload() {
boolean same;
synchronized (lock) {
same = isSame();
if (!same) {
Evaluators.acceptNotNull(activeConfiguration, ActiveConfiguration::shutdown);
this.activeConfiguration = new ActiveConfiguration(configuration);
}
}
if (!same) {
ExceptionExt.silent(() -> onChangeListener.accept(activeConfiguration.getTokenBucket()));
}
return this.activeConfiguration;
}
private class ActiveConfiguration {
private final TokenBucket tokenBucket;
private final long capacity;
private final long initialNumberOfTokens;
private final long intervalMs;
private final long numberOfTokensPerInterval;
private final RefillStrategy refillStrategy;
private ActiveConfiguration(FixedIntervalTokenBucketConfiguration configuration) {
this.capacity = configuration.getCapacity();
this.initialNumberOfTokens = configuration.getInitialNumberOfTokens();
this.intervalMs = configuration.getIntervalMs();
this.numberOfTokensPerInterval = configuration.getNumberOfTokensPerInterval();
RefillStrategy baseRefillStrategy = new FixedIntervalRefillStrategy(
numberOfTokensPerInterval,
intervalMs, TimeUnit.MILLISECONDS,
titusRuntime.map(TitusRuntime::getClock).orElse(Clocks.system())
);
this.refillStrategy = titusRuntime.map(runtime ->
(RefillStrategy) new SpectatorRefillStrategyDecorator(name, baseRefillStrategy, runtime))
.orElse(baseRefillStrategy);
this.tokenBucket = new DefaultTokenBucket(
name,
capacity,
refillStrategy,
initialNumberOfTokens
);
}
private void shutdown() {
if (refillStrategy instanceof SpectatorRefillStrategyDecorator) {
((SpectatorRefillStrategyDecorator) refillStrategy).shutdown();
}
}
private long getCapacity() {
return capacity;
}
private long getInitialNumberOfTokens() {
return initialNumberOfTokens;
}
private long getIntervalMs() {
return intervalMs;
}
private long getNumberOfTokensPerInterval() {
return numberOfTokensPerInterval;
}
private TokenBucket getTokenBucket() {
return tokenBucket;
}
}
}
| 710 |
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/grpc/GrpcToReactUtil.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.grpc;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.base.Preconditions;
import com.google.protobuf.Empty;
import com.google.protobuf.Message;
import com.netflix.titus.common.util.CollectionsExt;
import io.grpc.stub.AbstractStub;
import io.grpc.stub.StreamObserver;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class GrpcToReactUtil {
/**
* For request/response GRPC calls, we set execution deadline at both Reactor and GRPC level. As we prefer the timeout
* be triggered by GRPC, which may give us potentially more insight, we adjust Reactor timeout value by this factor.
*/
public static final double RX_CLIENT_TIMEOUT_FACTOR = 1.2;
public static Method getGrpcMethod(AbstractStub<?> grpcStub, Method method, Set<Class> handlerTypes) {
List<Class> transferredParameters = Arrays.stream((Class[]) method.getParameterTypes())
.filter(type -> !handlerTypes.contains(type))
.collect(Collectors.toList());
Preconditions.checkArgument(transferredParameters.size() <= 1, "Method must have one or zero protobuf object parameters but is: %s", method);
Class<?> requestType = CollectionsExt.firstOrDefault(transferredParameters, Empty.class);
Preconditions.checkArgument(Message.class.isAssignableFrom(requestType), "Not protobuf message in method parameter: %s", method);
Class<?> returnType = method.getReturnType();
Preconditions.checkArgument(Flux.class.isAssignableFrom(returnType) || Mono.class.isAssignableFrom(returnType), "Flux or Mono return type expected but is: %s", returnType);
try {
return grpcStub.getClass().getMethod(method.getName(), requestType, StreamObserver.class);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("React method does not match any of the available GRPC stub methods: " + method);
}
}
public static String toMethodNameFromFullName(String fullName) {
int begin = fullName.indexOf('/');
Preconditions.checkState(begin >= 0, "Not GRPC full name: " + fullName);
Preconditions.checkState(begin + 1 < fullName.length(), "Not GRPC full name: " + fullName);
return Character.toLowerCase(fullName.charAt(begin + 1)) + fullName.substring(begin + 2);
}
public static boolean isEmptyToVoidResult(Method reactMethod, Method grpcMethod) {
Preconditions.checkArgument(reactMethod.getReturnType().isAssignableFrom(Mono.class) || reactMethod.getReturnType().isAssignableFrom(Flux.class));
return hasTypeParameter(reactMethod.getGenericReturnType(), 0, Void.class)
&& hasTypeParameter(grpcMethod.getGenericParameterTypes()[1], 0, Empty.class);
}
private static boolean hasTypeParameter(Type type, int position, Class<?> parameterClass) {
if (!(type instanceof ParameterizedType)) {
return false;
}
ParameterizedType ptype = (ParameterizedType) type;
Type[] typeArguments = ptype.getActualTypeArguments();
if (position >= typeArguments.length) {
return false;
}
Type parameterType = typeArguments[position];
return parameterClass.isAssignableFrom((Class<?>) parameterType);
}
}
| 711 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/GrpcToReactorClientFactory.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.grpc.reactor;
import io.grpc.ServiceDescriptor;
import io.grpc.stub.AbstractStub;
public interface GrpcToReactorClientFactory {
<GRPC_STUB extends AbstractStub<GRPC_STUB>, REACT_API> REACT_API apply(GRPC_STUB stub,
Class<REACT_API> apiType,
ServiceDescriptor serviceDescriptor);
}
| 712 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/GrpcToReactorServerFactory.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.grpc.reactor;
import io.grpc.ServerServiceDefinition;
import io.grpc.ServiceDescriptor;
public interface GrpcToReactorServerFactory {
<REACT_SERVICE> ServerServiceDefinition apply(ServiceDescriptor serviceDefinition, REACT_SERVICE reactService);
/**
* This method is used when the {@link REACT_SERVICE} is a CGLIB proxy and additional class details need to be provided to the factory.
* If the {@link REACT_SERVICE} is a CGLIB proxy class it does not retain generic type information from the proxy target class so a
* detailed description of the target class is needed.
*/
<REACT_SERVICE> ServerServiceDefinition apply(ServiceDescriptor serviceDefinition, REACT_SERVICE reactService, Class<REACT_SERVICE> reactorDetailedFallbackClass);
}
| 713 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/server/GrpcToReactorServerBuilder.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.grpc.reactor.server;
import java.util.function.Supplier;
import io.grpc.ServerServiceDefinition;
import io.grpc.ServiceDescriptor;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
class GrpcToReactorServerBuilder<REACT_SERVICE, CONTEXT> {
private final ServiceDescriptor serviceDescriptor;
private final REACT_SERVICE reactorService;
private Class<REACT_SERVICE> reactorDetailedFallbackClass;
private Class<CONTEXT> contextType;
private Supplier<CONTEXT> contextResolver;
private GrpcToReactorServerBuilder(ServiceDescriptor serviceDescriptor, REACT_SERVICE reactorService) {
this.serviceDescriptor = serviceDescriptor;
this.reactorService = reactorService;
}
GrpcToReactorServerBuilder<REACT_SERVICE, CONTEXT> withContext(Class<CONTEXT> contextType, Supplier<CONTEXT> contextResolver) {
this.contextType = contextType;
this.contextResolver = contextResolver;
return this;
}
GrpcToReactorServerBuilder<REACT_SERVICE, CONTEXT> withReactorFallbackClass(Class<REACT_SERVICE> reactorDetailedFallbackClass) {
this.reactorDetailedFallbackClass = reactorDetailedFallbackClass;
return this;
}
static <REACT_SERVICE, CONTEXT> GrpcToReactorServerBuilder<REACT_SERVICE, CONTEXT> newBuilder(
ServiceDescriptor grpcServiceDescriptor, REACT_SERVICE reactService) {
return new GrpcToReactorServerBuilder<>(grpcServiceDescriptor, reactService);
}
ServerServiceDefinition build() {
MethodHandlersBuilder<CONTEXT, REACT_SERVICE> handlersBuilder = new MethodHandlersBuilder<>(reactorService, serviceDescriptor, contextType, contextResolver, reactorDetailedFallbackClass);
ServerServiceDefinition.Builder builder = ServerServiceDefinition.builder(serviceDescriptor);
handlersBuilder.getUnaryMethodHandlers().forEach(handler -> {
builder.addMethod(handler.getMethodDescriptor(), asyncUnaryCall(handler));
});
handlersBuilder.getServerStreamingMethodHandlers().forEach(handler -> {
builder.addMethod(handler.getMethodDescriptor(), asyncServerStreamingCall(handler));
});
return builder.build();
}
}
| 714 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/server/DefaultGrpcToReactorServerFactory.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.grpc.reactor.server;
import java.util.function.Supplier;
import com.netflix.titus.common.util.grpc.reactor.GrpcToReactorServerFactory;
import io.grpc.ServerServiceDefinition;
import io.grpc.ServiceDescriptor;
public class DefaultGrpcToReactorServerFactory<CONTEXT> implements GrpcToReactorServerFactory {
private final Class<CONTEXT> contextType;
private final Supplier<CONTEXT> contextResolver;
public DefaultGrpcToReactorServerFactory(Class<CONTEXT> contextType, Supplier<CONTEXT> contextResolver) {
this.contextType = contextType;
this.contextResolver = contextResolver;
}
@Override
public <REACT_SERVICE> ServerServiceDefinition apply(ServiceDescriptor serviceDescriptor, REACT_SERVICE reactService) {
return apply(serviceDescriptor, reactService, (Class<REACT_SERVICE>) reactService.getClass());
}
@Override
public <REACT_SERVICE> ServerServiceDefinition apply(ServiceDescriptor serviceDescriptor, REACT_SERVICE reactService, Class<REACT_SERVICE> reactorDetailedFallbackClass) {
return GrpcToReactorServerBuilder.<REACT_SERVICE, CONTEXT>newBuilder(serviceDescriptor, reactService)
.withContext(contextType, contextResolver)
.withReactorFallbackClass(reactorDetailedFallbackClass)
.build();
}
}
| 715 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/server/MethodHandlersBuilder.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.grpc.reactor.server;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.base.Preconditions;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Empty;
import com.netflix.titus.common.util.ReflectionExt;
import io.grpc.MethodDescriptor;
import io.grpc.ServiceDescriptor;
import io.grpc.protobuf.ProtoMethodDescriptorSupplier;
import org.springframework.aop.support.AopUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.netflix.titus.common.util.grpc.GrpcToReactUtil.toMethodNameFromFullName;
class MethodHandlersBuilder<CONTEXT, REACT_SERVICE> {
private final Map<String, Method> reactorMethodMap;
private final Class<CONTEXT> contextType;
private final List<UnaryMethodHandler> unaryMethodHandlers;
private final List<ServerStreamingMethodHandler> serverStreamingMethodHandlers;
MethodHandlersBuilder(Object reactorService,
ServiceDescriptor serviceDefinition,
Class<CONTEXT> contextType,
Supplier<CONTEXT> contextResolver,
Class<REACT_SERVICE> reactorDetailedFallbackClass) {
// CGLIB proxies do not retain generic type info. For these proxies we rely on a detailed fallback class definition to derive generic type info.
Stream<Method> methodStream = AopUtils.isCglibProxy(reactorService) ? Stream.of(reactorDetailedFallbackClass.getMethods()) : Stream.of(reactorService.getClass().getMethods());
this.reactorMethodMap = methodStream
.filter(m -> !ReflectionExt.isObjectMethod(m))
.collect(Collectors.toMap(Method::getName, Function.identity()));
this.contextType = contextType;
List<UnaryMethodHandler> unaryMethodHandlers = new ArrayList<>();
List<ServerStreamingMethodHandler> serverStreamingMethodHandlers = new ArrayList<>();
serviceDefinition.getMethods().forEach(methodDescriptor -> {
GrpcToReactorMethodBinding binding = findReactorMethod(methodDescriptor);
if (binding.isMono()) {
unaryMethodHandlers.add(new UnaryMethodHandler<>(binding, contextResolver, reactorService));
} else {
serverStreamingMethodHandlers.add(new ServerStreamingMethodHandler<>(binding, contextResolver, reactorService));
}
});
this.unaryMethodHandlers = unaryMethodHandlers;
this.serverStreamingMethodHandlers = serverStreamingMethodHandlers;
}
List<UnaryMethodHandler> getUnaryMethodHandlers() {
return unaryMethodHandlers;
}
List<ServerStreamingMethodHandler> getServerStreamingMethodHandlers() {
return serverStreamingMethodHandlers;
}
private GrpcToReactorMethodBinding findReactorMethod(MethodDescriptor<?, ?> methodDescriptor) {
String methodName = toMethodNameFromFullName(methodDescriptor.getFullMethodName());
Method reactorMethod = reactorMethodMap.get(methodName);
Preconditions.checkNotNull(reactorMethod, "Cannot find corresponding Reactor method for: {}", methodDescriptor);
ProtoMethodDescriptorSupplier methodDescriptorSupplier = (ProtoMethodDescriptorSupplier) methodDescriptor.getSchemaDescriptor();
Descriptors.MethodDescriptor md = methodDescriptorSupplier.getMethodDescriptor();
String inputTypeName = md.getInputType().getName();
String outputTypeName = md.getOutputType().getName();
Class<?> reactorReturnType = reactorMethod.getReturnType();
boolean isMono = reactorReturnType.isAssignableFrom(Mono.class);
boolean isFlux = !isMono && reactorReturnType.isAssignableFrom(Flux.class);
Preconditions.checkArgument(isMono || isFlux, "Mono or Flux return types allowed only");
Type[] returnTypeParameters = ((ParameterizedType) reactorMethod.getGenericReturnType()).getActualTypeArguments();
Preconditions.checkArgument(
returnTypeParameters != null && returnTypeParameters.length == 1,
"Expected one type parameter in the return type: %s", methodDescriptor.getFullMethodName()
);
Class returnTypeParameter = (Class) returnTypeParameters[0];
// Check return types
if (returnTypeParameter == Void.class) {
Preconditions.checkArgument(
outputTypeName.equals("Empty"),
"Reactor Mono<Void>/Flux<Void> can be mapped to GRPC/Empty only: %s", methodDescriptor.getFullMethodName()
);
} else {
Preconditions.checkArgument(
returnTypeParameter.getSimpleName().equals(outputTypeName),
"Different GRPC and Reactor API return types: %s", methodDescriptor.getFullMethodName()
);
}
// Check method arguments
if (reactorMethod.getParameterCount() == 0) {
Preconditions.checkArgument(
inputTypeName.equals(Empty.class.getSimpleName()),
"Only Empty request argument allowed for Reactor methods with no parameters: %s", methodDescriptor.getFullMethodName()
);
return new GrpcToReactorMethodBinding<>(methodDescriptor, reactorMethod, -1, isMono, returnTypeParameter);
}
if (reactorMethod.getParameterCount() == 1) {
if (reactorMethod.getParameterTypes()[0] == contextType) {
Preconditions.checkArgument(
inputTypeName.equals(Empty.class.getSimpleName()),
"Only Empty request argument allowed for Reactor methods with no parameters: %s", methodDescriptor.getFullMethodName()
);
return new GrpcToReactorMethodBinding<>(methodDescriptor, reactorMethod, 0, isMono, returnTypeParameter);
}
Preconditions.checkArgument(
inputTypeName.equals(reactorMethod.getParameterTypes()[0].getSimpleName()),
"Reactor and GRPC parameter types do not match: %s", methodDescriptor.getFullMethodName()
);
return new GrpcToReactorMethodBinding<>(methodDescriptor, reactorMethod, -1, isMono, returnTypeParameter);
}
if (reactorMethod.getParameterCount() == 2) {
Preconditions.checkArgument(
reactorMethod.getParameterTypes()[0] == contextType || reactorMethod.getParameterTypes()[1] == contextType,
"Expected one GRPC method argument, and one CallMetadata value in Reactor method mapped to: %s", methodDescriptor.getFullMethodName()
);
int callMetadataPos = reactorMethod.getParameterTypes()[0] == contextType ? 0 : 1;
int grpcArgumentPos = callMetadataPos == 0 ? 1 : 0;
Preconditions.checkArgument(
inputTypeName.equals(reactorMethod.getParameterTypes()[grpcArgumentPos].getSimpleName()),
"Reactor and GRPC parameter types do not match: %s", methodDescriptor.getFullMethodName()
);
return new GrpcToReactorMethodBinding<>(methodDescriptor, reactorMethod, callMetadataPos, isMono, returnTypeParameter);
}
throw new IllegalArgumentException("Cannot map GRPC method to any reactor method: " + methodDescriptor.getFullMethodName());
}
}
| 716 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/server/GrpcToReactorMethodBinding.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.grpc.reactor.server;
import java.lang.reflect.Method;
import io.grpc.MethodDescriptor;
class GrpcToReactorMethodBinding<REQ, RESP> {
private final MethodDescriptor<REQ, RESP> methodDescriptor;
private final Method reactorMethod;
private final int callMetadataPos;
private final int grpcArgumentPos;
private final boolean isMono;
private final Class returnTypeParameter;
GrpcToReactorMethodBinding(MethodDescriptor<REQ, RESP> methodDescriptor,
Method reactorMethod,
int callMetadataPos,
boolean isMono,
Class returnTypeParameter) {
this.methodDescriptor = methodDescriptor;
this.reactorMethod = reactorMethod;
this.callMetadataPos = callMetadataPos;
this.grpcArgumentPos = callMetadataPos < 0
? (reactorMethod.getParameterCount() == 0 ? -1 : 0)
: (reactorMethod.getParameterCount() == 1 ? -1 : (callMetadataPos == 0 ? 1 : 0));
this.isMono = isMono;
this.returnTypeParameter = returnTypeParameter;
}
MethodDescriptor<REQ, RESP> getMethodDescriptor() {
return methodDescriptor;
}
Method getReactorMethod() {
return reactorMethod;
}
int getCallMetadataPos() {
return callMetadataPos;
}
int getGrpcArgumentPos() {
return grpcArgumentPos;
}
boolean isMono() {
return isMono;
}
Class getReturnTypeParameter() {
return returnTypeParameter;
}
}
| 717 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/server/AbstractMethodHandler.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.grpc.reactor.server;
import java.lang.reflect.InvocationTargetException;
import java.util.function.Supplier;
import io.grpc.MethodDescriptor;
import io.grpc.stub.ServerCallStreamObserver;
import io.grpc.stub.StreamObserver;
import org.reactivestreams.Publisher;
import reactor.core.Disposable;
abstract class AbstractMethodHandler<REQ, RESP, CONTEXT> {
private static final Object[] EMPTY_ARG_ARRAY = new Object[0];
final GrpcToReactorMethodBinding<REQ, RESP> binding;
private final Supplier<CONTEXT> contextResolver;
private final Object reactorService;
AbstractMethodHandler(GrpcToReactorMethodBinding<REQ, RESP> binding,
Supplier<CONTEXT> contextResolver,
Object reactorService) {
this.binding = binding;
this.contextResolver = contextResolver;
this.reactorService = reactorService;
}
MethodDescriptor<REQ, RESP> getMethodDescriptor() {
return binding.getMethodDescriptor();
}
void invoke(REQ request, StreamObserver<RESP> responseObserver) {
Object[] args;
if (binding.getCallMetadataPos() < 0) {
args = binding.getGrpcArgumentPos() < 0 ? EMPTY_ARG_ARRAY : new Object[]{request};
} else {
CONTEXT context = contextResolver.get();
if (binding.getCallMetadataPos() == 0) {
if (binding.getGrpcArgumentPos() < 0) {
args = new Object[]{context};
} else {
args = new Object[]{context, request};
}
} else {
if (binding.getCallMetadataPos() == 0) {
args = new Object[]{context, request};
} else {
args = new Object[]{request, context};
}
}
}
Publisher<RESP> result;
try {
result = (Publisher<RESP>) binding.getReactorMethod().invoke(reactorService, args);
} catch (InvocationTargetException e) {
responseObserver.onError(e.getCause());
return;
} catch (Exception e) {
responseObserver.onError(e);
return;
}
Disposable disposable = handleResult(result, responseObserver);
((ServerCallStreamObserver) responseObserver).setOnCancelHandler(disposable::dispose);
}
abstract Disposable handleResult(Publisher<RESP> result, StreamObserver<RESP> responseObserver);
}
| 718 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/server/UnaryMethodHandler.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.grpc.reactor.server;
import java.util.function.Supplier;
import com.google.protobuf.Empty;
import io.grpc.stub.StreamObserver;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.Disposable;
import reactor.core.publisher.Mono;
class UnaryMethodHandler<REQ, RESP, CONTEXT> extends AbstractMethodHandler<REQ, RESP, CONTEXT> implements io.grpc.stub.ServerCalls.UnaryMethod<REQ, RESP> {
private static final Logger logger = LoggerFactory.getLogger(UnaryMethodHandler.class);
UnaryMethodHandler(GrpcToReactorMethodBinding<REQ, RESP> binding,
Supplier<CONTEXT> contextResolver,
Object reactorService) {
super(binding, contextResolver, reactorService);
}
@Override
public void invoke(REQ request, StreamObserver<RESP> responseObserver) {
super.invoke(request, responseObserver);
}
@Override
Disposable handleResult(Publisher<RESP> result, StreamObserver<RESP> responseObserver) {
Mono<RESP> monoResult = Mono.from(result);
Disposable disposable;
if (binding.getReturnTypeParameter() == Void.class) {
disposable = monoResult.subscribe(
next -> {
},
e -> {
try {
responseObserver.onError(e);
} catch (Exception e2) {
logger.warn("Subscriber threw error in onError handler", e2);
}
},
() -> {
try {
// Void must be mapped to GRPC/Empty value.
responseObserver.onNext((RESP) Empty.getDefaultInstance());
try {
responseObserver.onCompleted();
} catch (Exception e) {
logger.warn("Subscriber threw error in onCompleted handler", e);
}
} catch (Exception e) {
logger.warn("Subscriber threw error in onNext handler. Retrying with onError", e);
try {
responseObserver.onError(e);
} catch (Exception e2) {
logger.warn("Subscriber threw error in onError handler", e2);
}
}
}
);
} else {
disposable = monoResult.subscribe(
value -> {
try {
responseObserver.onNext(value);
} catch (Exception e) {
logger.warn("Subscriber threw error in onNext handler. Retrying with onError", e);
try {
responseObserver.onError(e);
} catch (Exception e2) {
logger.warn("Subscriber threw error in onError handler", e2);
}
}
},
e -> {
try {
responseObserver.onError(e);
} catch (Exception e2) {
logger.warn("Subscriber threw error in onError handler", e2);
}
},
() -> {
try {
responseObserver.onCompleted();
} catch (Exception e) {
logger.warn("Subscriber threw error in onCompleted handler", e);
}
}
);
}
return disposable;
}
}
| 719 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/server/ServerStreamingMethodHandler.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.grpc.reactor.server;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.titus.common.util.rx.ReactorExt;
import io.grpc.stub.ServerCalls;
import io.grpc.stub.StreamObserver;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
class ServerStreamingMethodHandler<REQ, RESP, CONTEXT> extends AbstractMethodHandler<REQ, RESP, CONTEXT> implements ServerCalls.ServerStreamingMethod<REQ, RESP> {
private static final Logger logger = LoggerFactory.getLogger(ServerStreamingMethodHandler.class);
ServerStreamingMethodHandler(GrpcToReactorMethodBinding<REQ, RESP> binding,
Supplier<CONTEXT> contextResolver,
Object reactorService) {
super(binding, contextResolver, reactorService);
}
@Override
public void invoke(REQ request, StreamObserver<RESP> responseObserver) {
super.invoke(request, responseObserver);
}
@Override
Disposable handleResult(Publisher<RESP> result, StreamObserver<RESP> responseObserver) {
return internalHandleResult(result, responseObserver);
}
@VisibleForTesting
static <RESP> Disposable internalHandleResult(Publisher<RESP> result, StreamObserver<RESP> responseObserver) {
AtomicBoolean cancelled = new AtomicBoolean();
AtomicReference<Disposable> disposableRef = new AtomicReference<>();
Disposable disposable = Flux.from(result).subscribe(
value -> {
if (cancelled.get()) {
ReactorExt.safeDispose(disposableRef.get());
return;
}
try {
responseObserver.onNext(value);
} catch (Exception e) {
cancelled.set(true);
logger.warn("Subscriber threw error in onNext handler. Retrying with onError", e);
try {
responseObserver.onError(e);
} catch (Exception e2) {
logger.warn("Subscriber threw error in onError handler", e2);
}
ReactorExt.safeDispose(disposableRef.get());
}
},
e -> {
if (cancelled.get()) {
return;
}
try {
responseObserver.onError(e);
} catch (Exception e2) {
logger.warn("Subscriber threw error in onError handler", e2);
}
},
() -> {
if (cancelled.get()) {
return;
}
try {
responseObserver.onCompleted();
} catch (Exception e) {
logger.warn("Subscriber threw error in onCompleted handler", e);
}
}
);
disposableRef.set(disposable);
if (cancelled.get()) {
ReactorExt.safeDispose(disposable);
}
return disposable;
}
}
| 720 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/client/ReactorClientInvocationHandler.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.grpc.reactor.client;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.function.Function;
import org.reactivestreams.Publisher;
class ReactorClientInvocationHandler<REACT_API> implements InvocationHandler {
private final Map<Method, Function<Object[], Publisher>> methodMap;
private final String toStringValue;
ReactorClientInvocationHandler(Class<REACT_API> reactApi, Map<Method, Function<Object[], Publisher>> methodMap) {
this.methodMap = methodMap;
this.toStringValue = reactApi.getSimpleName() + "[react to GRPC bridge]";
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Function<Object[], Publisher> methodHandler = methodMap.get(method);
if (methodHandler != null) {
return methodHandler.apply(args);
}
if (method.getName().equals("toString")) {
return toStringValue;
}
return method.invoke(this, args);
}
}
| 721 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/client/FluxMethodBridge.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.grpc.reactor.client;
import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Function;
import com.google.common.base.Preconditions;
import com.google.protobuf.Empty;
import com.netflix.titus.common.util.grpc.GrpcToReactUtil;
import io.grpc.Deadline;
import io.grpc.MethodDescriptor;
import io.grpc.ServiceDescriptor;
import io.grpc.stub.AbstractStub;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.StreamObserver;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import static com.netflix.titus.common.util.grpc.GrpcToReactUtil.toMethodNameFromFullName;
class FluxMethodBridge<GRPC_STUB extends AbstractStub<GRPC_STUB>, CONTEXT> implements Function<Object[], Publisher> {
private final Method grpcMethod;
private final boolean streamingResponse;
private final int grpcArgPos;
private final int contextPos;
private final BiFunction<GRPC_STUB, Optional<CONTEXT>, GRPC_STUB> grpcStubDecorator;
private final GRPC_STUB grpcStub;
private final Duration timeout;
private final Duration reactorTimeout;
/**
* If grpcArgPos is less then zero, it means no GRPC argument is provided, and instead {@link Empty} value should be used.
* If contextPos is less then zero, it means the context value should be resolved as it is not passed directly by
* the client.
*/
FluxMethodBridge(Method reactMethod,
ServiceDescriptor grpcServiceDescriptor,
Method grpcMethod,
int grpcArgPos,
int contextPos,
BiFunction<GRPC_STUB, Optional<CONTEXT>, GRPC_STUB> grpcStubDecorator,
GRPC_STUB grpcStub,
Duration timeout,
Duration streamingTimeout) {
this.grpcArgPos = grpcArgPos;
this.contextPos = contextPos;
this.grpcStubDecorator = grpcStubDecorator;
this.grpcStub = grpcStub;
this.streamingResponse = grpcServiceDescriptor.getMethods().stream()
.filter(m -> toMethodNameFromFullName(m.getFullMethodName()).equals(reactMethod.getName()))
.findFirst()
.map(m -> m.getType() == MethodDescriptor.MethodType.SERVER_STREAMING)
.orElse(false);
Preconditions.checkArgument(
!GrpcToReactUtil.isEmptyToVoidResult(reactMethod, grpcMethod),
"Empty GRPC reply to Flux<Mono> mapping not supported (use Mono<Void> in API definition instead)"
);
this.grpcMethod = grpcMethod;
this.timeout = streamingResponse ? streamingTimeout : timeout;
this.reactorTimeout = Duration.ofMillis((long) (timeout.toMillis() * GrpcToReactUtil.RX_CLIENT_TIMEOUT_FACTOR));
}
@Override
public Publisher apply(Object[] args) {
Flux<Object> publisher = Flux.create(sink -> new FluxInvocation(sink, args));
return streamingResponse ? publisher : publisher.timeout(reactorTimeout);
}
private class FluxInvocation {
private FluxInvocation(FluxSink<Object> sink, Object[] args) {
StreamObserver<Object> grpcStreamObserver = new ClientResponseObserver<Object, Object>() {
@Override
public void beforeStart(ClientCallStreamObserver requestStream) {
sink.onCancel(() -> requestStream.cancel("React subscription cancelled", null));
}
@Override
public void onNext(Object value) {
sink.next(value);
}
@Override
public void onError(Throwable error) {
sink.error(error);
}
@Override
public void onCompleted() {
sink.complete();
}
};
Object[] grpcArgs = new Object[]{
grpcArgPos < 0 ? Empty.getDefaultInstance() : args[grpcArgPos],
grpcStreamObserver
};
GRPC_STUB invocationStub = handleCallMetadata(args)
.withDeadline(Deadline.after(timeout.toMillis(), TimeUnit.MILLISECONDS));
try {
grpcMethod.invoke(invocationStub, grpcArgs);
} catch (Exception e) {
sink.error(e);
}
}
private GRPC_STUB handleCallMetadata(Object[] args) {
Optional<CONTEXT> contextOptional = contextPos >= 0 ? (Optional<CONTEXT>) Optional.of(args[contextPos]) : Optional.empty();
return grpcStubDecorator.apply(grpcStub, contextOptional);
}
}
}
| 722 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/client/ReactorToGrpcClientBuilder.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.grpc.reactor.client;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.protobuf.Message;
import com.netflix.titus.common.util.grpc.GrpcToReactUtil;
import io.grpc.ServiceDescriptor;
import io.grpc.stub.AbstractStub;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
public class ReactorToGrpcClientBuilder<REACT_API, GRPC_STUB extends AbstractStub<GRPC_STUB>, CONTEXT> {
private static final long DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
@VisibleForTesting
public static final long DEFAULT_STREAMING_TIMEOUT_MS = 12 * 60 * 60_000;
private static final BiFunction EMPTY_STUB_DECORATOR = (stub, context) -> stub;
private final Class<REACT_API> reactApi;
private final GRPC_STUB grpcStub;
private final ServiceDescriptor grpcServiceDescriptor;
private final Class<CONTEXT> contextType;
private final Set<Class> nonGrpcParameters;
private Duration timeout;
private Duration streamingTimeout;
private BiFunction<GRPC_STUB, Optional<CONTEXT>, GRPC_STUB> grpcStubDecorator;
private ReactorToGrpcClientBuilder(Class<REACT_API> reactApi,
GRPC_STUB grpcStub,
ServiceDescriptor grpcServiceDescriptor,
Class<CONTEXT> contextType) {
this.reactApi = reactApi;
this.grpcStub = grpcStub;
this.grpcServiceDescriptor = grpcServiceDescriptor;
this.contextType = contextType;
this.nonGrpcParameters = Collections.singleton(this.contextType);
}
public ReactorToGrpcClientBuilder<REACT_API, GRPC_STUB, CONTEXT> withTimeout(Duration timeout) {
this.timeout = timeout;
return this;
}
public ReactorToGrpcClientBuilder<REACT_API, GRPC_STUB, CONTEXT> withStreamingTimeout(Duration streamingTimeout) {
this.streamingTimeout = streamingTimeout;
return this;
}
public ReactorToGrpcClientBuilder<REACT_API, GRPC_STUB, CONTEXT> withGrpcStubDecorator(BiFunction<GRPC_STUB, Optional<CONTEXT>, GRPC_STUB> grpcStubDecorator) {
this.grpcStubDecorator = grpcStubDecorator;
return this;
}
public static <REACT_API, GRPC_STUB extends AbstractStub<GRPC_STUB>, CONTEXT> ReactorToGrpcClientBuilder<REACT_API, GRPC_STUB, CONTEXT> newBuilder(
Class<REACT_API> reactApi,
GRPC_STUB grpcStub,
ServiceDescriptor grpcServiceDescriptor,
Class<CONTEXT> contextType) {
Preconditions.checkArgument(reactApi.isInterface(), "Interface type required");
return new ReactorToGrpcClientBuilder<>(reactApi, grpcStub, grpcServiceDescriptor, contextType);
}
public static <REACT_API, GRPC_STUB extends AbstractStub<GRPC_STUB>, CONTEXT> ReactorToGrpcClientBuilder<REACT_API, GRPC_STUB, CONTEXT> newBuilderWithDefaults(
Class<REACT_API> reactApi,
GRPC_STUB grpcStub,
ServiceDescriptor grpcServiceDescriptor,
Class<CONTEXT> contextType) {
Preconditions.checkArgument(reactApi.isInterface(), "Interface type required");
return new ReactorToGrpcClientBuilder<>(reactApi, grpcStub, grpcServiceDescriptor, contextType)
.withTimeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT_MS))
.withStreamingTimeout(Duration.ofMillis(DEFAULT_STREAMING_TIMEOUT_MS))
.withGrpcStubDecorator(EMPTY_STUB_DECORATOR);
}
public REACT_API build() {
Preconditions.checkNotNull(timeout, "GRPC request timeout not set");
Preconditions.checkNotNull(streamingTimeout, "GRPC streaming request timeout not set");
Preconditions.checkNotNull(grpcStubDecorator, "GRPC stub decorator not set");
Map<Method, Function<Object[], Publisher>> methodMap = buildMethodMap();
return (REACT_API) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[]{reactApi},
new ReactorClientInvocationHandler(reactApi, methodMap)
);
}
private Map<Method, Function<Object[], Publisher>> buildMethodMap() {
Map<Method, Function<Object[], Publisher>> mapping = new HashMap<>();
for (Method method : reactApi.getMethods()) {
mapping.put(method, createGrpcBridge(method));
}
return mapping;
}
private Function<Object[], Publisher> createGrpcBridge(Method reactMethod) {
int grpcArgPos = -1;
int callMetadataPos = -1;
Class<?>[] argTypes = reactMethod.getParameterTypes();
for (int i = 0; i < argTypes.length; i++) {
if (Message.class.isAssignableFrom(argTypes[i])) {
grpcArgPos = i;
}
if (contextType.isAssignableFrom(argTypes[i])) {
callMetadataPos = i;
}
}
Method grpcMethod = GrpcToReactUtil.getGrpcMethod(grpcStub, reactMethod, nonGrpcParameters);
if (reactMethod.getReturnType().isAssignableFrom(Mono.class)) {
return new MonoMethodBridge<>(
reactMethod,
grpcMethod,
grpcArgPos,
callMetadataPos,
grpcStubDecorator,
grpcStub,
timeout
);
}
return new FluxMethodBridge<>(
reactMethod,
grpcServiceDescriptor,
grpcMethod,
grpcArgPos,
callMetadataPos,
grpcStubDecorator,
grpcStub,
timeout,
streamingTimeout
);
}
}
| 723 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/grpc/reactor/client/MonoMethodBridge.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.grpc.reactor.client;
import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Function;
import com.google.protobuf.Empty;
import com.netflix.titus.common.util.grpc.GrpcToReactUtil;
import io.grpc.Deadline;
import io.grpc.stub.AbstractStub;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.StreamObserver;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoSink;
class MonoMethodBridge<GRPC_STUB extends AbstractStub<GRPC_STUB>, CONTEXT> implements Function<Object[], Publisher> {
private final Method grpcMethod;
private final int grpcArgPos;
private final int contextPos;
private final BiFunction<GRPC_STUB, Optional<CONTEXT>, GRPC_STUB> grpcStubDecorator;
private final GRPC_STUB grpcStub;
private final boolean emptyToVoidReply;
private final Duration timeout;
private final Duration reactorTimeout;
/**
* If grpcArgPos is less then zero, it means no GRPC argument is provided, and instead {@link Empty} value should be used.
* If contextPos is less then zero, it means the context value should be resolved as it is not passed directly by
* the client.
*/
MonoMethodBridge(Method reactMethod,
Method grpcMethod,
int grpcArgPos,
int contextPos,
BiFunction<GRPC_STUB, Optional<CONTEXT>, GRPC_STUB> grpcStubDecorator,
GRPC_STUB grpcStub,
Duration timeout) {
this.grpcMethod = grpcMethod;
this.grpcArgPos = grpcArgPos;
this.contextPos = contextPos;
this.grpcStubDecorator = grpcStubDecorator;
this.grpcStub = grpcStub;
this.emptyToVoidReply = GrpcToReactUtil.isEmptyToVoidResult(reactMethod, grpcMethod);
this.timeout = timeout;
this.reactorTimeout = Duration.ofMillis((long) (timeout.toMillis() * GrpcToReactUtil.RX_CLIENT_TIMEOUT_FACTOR));
}
@Override
public Publisher apply(Object[] args) {
return Mono.create(sink -> new MonoInvocation(sink, args)).timeout(reactorTimeout);
}
private class MonoInvocation {
private MonoInvocation(MonoSink<Object> sink, Object[] args) {
StreamObserver<Object> grpcStreamObserver = new ClientResponseObserver<Object, Object>() {
@Override
public void beforeStart(ClientCallStreamObserver requestStream) {
sink.onCancel(() -> requestStream.cancel("React subscription cancelled", null));
}
@Override
public void onNext(Object value) {
if (emptyToVoidReply) {
sink.success();
} else {
sink.success(value);
}
}
@Override
public void onError(Throwable error) {
sink.error(error);
}
@Override
public void onCompleted() {
sink.success();
}
};
Object[] grpcArgs = new Object[]{
grpcArgPos < 0 ? Empty.getDefaultInstance() : args[grpcArgPos],
grpcStreamObserver
};
GRPC_STUB invocationStub = handleCallMetadata(args)
.withDeadline(Deadline.after(timeout.toMillis(), TimeUnit.MILLISECONDS));
try {
grpcMethod.invoke(invocationStub, grpcArgs);
} catch (Exception e) {
sink.error(e);
}
}
private GRPC_STUB handleCallMetadata(Object[] args) {
Optional<CONTEXT> contextOptional = contextPos >= 0 ? (Optional<CONTEXT>) Optional.of(args[contextPos]) : Optional.empty();
return grpcStubDecorator.apply(grpcStub, contextOptional);
}
}
}
| 724 |
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/tuple/Pair.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.tuple;
import java.util.function.Function;
/**
*
*/
public class Pair<L, R> {
private final L left;
private final R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
public L getLeft() {
return left;
}
public R getRight() {
return right;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair<?, ?> pair = (Pair<?, ?>) o;
if (left != null ? !left.equals(pair.left) : pair.left != null) {
return false;
}
return right != null ? right.equals(pair.right) : pair.right == null;
}
@Override
public int hashCode() {
int result = left != null ? left.hashCode() : 0;
result = 31 * result + (right != null ? right.hashCode() : 0);
return result;
}
public <LM> Pair<LM, R> mapLeft(Function<L, LM> transformer) {
return Pair.of(transformer.apply(left), right);
}
public <RM> Pair<L, RM> mapRight(Function<R, RM> transformer) {
return Pair.of(left, transformer.apply(right));
}
@Override
public String toString() {
return "Pair{left=" + left + ", right=" + right + '}';
}
public static <L, R> Pair<L, R> of(L left, R right) {
return new Pair<>(left, right);
}
public static <T> Pair<T, T> same(T value) {
return Pair.of(value, value);
}
}
| 725 |
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/tuple/Either.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.tuple;
import java.util.function.Function;
/**
* A container type that holds either a value or an error. It provides a collection of additional methods
* similar two {@link java.util.Optional}.
*/
public class Either<T, E> {
private final T value;
private final E error;
private Either(T value, E error) {
this.value = value;
this.error = error;
}
public T getValue() {
return value;
}
public E getError() {
return error;
}
public boolean hasValue() {
return value != null;
}
public boolean hasError() {
return !hasValue();
}
public <U> Either<U, ? extends E> flatMap(Function<T, Either<U, ? extends E>> mapper) {
if (hasError()) {
return ofError(error);
}
return mapper.apply(value);
}
public <U> Either<U, E> map(Function<T, U> mapper) {
if (hasError()) {
return ofError(error);
}
return ofValue(mapper.apply(value));
}
public T must() {
if (value != null) {
return value;
}
if (error == null) {
throw new IllegalStateException("neither value nor error set");
}
if (error instanceof RuntimeException) {
throw (RuntimeException) error;
}
if (error instanceof Throwable) {
throw new IllegalStateException("value not set", (Throwable) error);
}
throw new IllegalStateException("value not set");
}
public T onErrorGet(Function<E, T> fallback) {
if (hasValue()) {
return value;
}
return fallback.apply(error);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Either<?, ?> either = (Either<?, ?>) o;
if (value != null ? !value.equals(either.value) : either.value != null) {
return false;
}
return error != null ? error.equals(either.error) : either.error == null;
}
@Override
public int hashCode() {
int result = value != null ? value.hashCode() : 0;
result = 31 * result + (error != null ? error.hashCode() : 0);
return result;
}
@Override
public String toString() {
return hasValue()
? "Either{value=" + value + '}'
: "Either{error=" + error + '}';
}
public static <T, E> Either<T, E> ofValue(T value) {
return new Either<>(value, null);
}
public static <T, E> Either<T, E> ofError(E error) {
return new Either<>(null, error);
}
}
| 726 |
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/tuple/Triple.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.tuple;
import java.util.function.Function;
/**
*/
public class Triple<A, B, C> {
private final A first;
private final B second;
private final C third;
public Triple(A first, B second, C third) {
this.first = first;
this.second = second;
this.third = third;
}
public A getFirst() {
return first;
}
public B getSecond() {
return second;
}
public C getThird() {
return third;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Triple<?, ?, ?> triple = (Triple<?, ?, ?>) o;
if (first != null ? !first.equals(triple.first) : triple.first != null) {
return false;
}
if (second != null ? !second.equals(triple.second) : triple.second != null) {
return false;
}
return third != null ? third.equals(triple.third) : triple.third == null;
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
result = 31 * result + (third != null ? third.hashCode() : 0);
return result;
}
public <AM> Triple<AM, B, C> mapFirst(Function<A, AM> transformer) {
return Triple.of(transformer.apply(first), second, third);
}
public <BM> Triple<A, BM, C> mapSecond(Function<B, BM> transformer) {
return Triple.of(first, transformer.apply(second), third);
}
public <CM> Triple<A, B, CM> mapThird(Function<C, CM> transformer) {
return Triple.of(first, second, transformer.apply(third));
}
@Override
public String toString() {
return "Triple{" +
"first=" + first +
", second=" + second +
", third=" + third +
'}';
}
public static <A, B, C> Triple<A, B, C> of(A first, B second, C third) {
return new Triple<>(first, second, third);
}
}
| 727 |
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/tuple/Quadruple.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.tuple;
/**
*/
public class Quadruple<A, B, C, D> {
private final A first;
private final B second;
private final C thrid;
private final D fourth;
public Quadruple(A first, B second, C thrid, D fourth) {
this.first = first;
this.second = second;
this.thrid = thrid;
this.fourth = fourth;
}
public A getFirst() {
return first;
}
public B getSecond() {
return second;
}
public C getThrid() {
return thrid;
}
public D getFourth() {
return fourth;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Quadruple<?, ?, ?, ?> quadruple = (Quadruple<?, ?, ?, ?>) o;
if (first != null ? !first.equals(quadruple.first) : quadruple.first != null) {
return false;
}
if (second != null ? !second.equals(quadruple.second) : quadruple.second != null) {
return false;
}
if (thrid != null ? !thrid.equals(quadruple.thrid) : quadruple.thrid != null) {
return false;
}
return fourth != null ? fourth.equals(quadruple.fourth) : quadruple.fourth == null;
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
result = 31 * result + (thrid != null ? thrid.hashCode() : 0);
result = 31 * result + (fourth != null ? fourth.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Quadruple{" +
"first=" + first +
", second=" + second +
", thrid=" + thrid +
", fourth=" + fourth +
'}';
}
public static <A, B, C, D> Quadruple<A, B, C, D> of(A first, B second, C third, D fourth) {
return new Quadruple<>(first, second, third, fourth);
}
}
| 728 |
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/guice/ActivationLifecycle.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.guice;
import java.util.List;
import com.netflix.titus.common.util.guice.annotation.Activator;
import com.netflix.titus.common.util.guice.annotation.Deactivator;
import com.netflix.titus.common.util.tuple.Pair;
/**
* Service activation/deactivation lifecycle handler. Use {@link Activator} and {@link Deactivator} annotations
* to instrument your services.
*/
public interface ActivationLifecycle {
/**
* Returns true if a given service instance is active.
*/
<T> boolean isActive(T instance);
/**
* Activate all services.
*/
void activate();
/**
* Deactivate all services.
*/
void deactivate();
/**
* Returns total activation time or -1 if none-of the services is activated yet or activation is in progress.
*/
long getActivationTimeMs();
/**
* Returns service activation time or -1 if a service is not activated yet or its activation is in progress.
* List elements are ordered according to the service activation order.
*/
List<Pair<String, Long>> getServiceActionTimesMs();
}
| 729 |
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/guice/ContainerEventBusModule.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.guice;
import com.google.inject.AbstractModule;
import com.google.inject.matcher.Matchers;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.guice.annotation.ProxyConfiguration;
import com.netflix.titus.common.util.guice.internal.ActivationProvisionListener;
import com.netflix.titus.common.util.guice.internal.DefaultContainerEventBus;
import com.netflix.titus.common.util.guice.internal.ProxyMethodInterceptor;
/**
*/
public final class ContainerEventBusModule extends AbstractModule {
@Override
protected void configure() {
bind(ContainerEventBus.class).to(DefaultContainerEventBus.class);
// Activation lifecycle
ActivationProvisionListener activationProvisionListener = new ActivationProvisionListener();
bind(ActivationLifecycle.class).toInstance(activationProvisionListener);
bindListener(Matchers.any(), activationProvisionListener);
// Proxies
bindInterceptor(
Matchers.annotatedWith(ProxyConfiguration.class),
Matchers.any(),
new ProxyMethodInterceptor(getProvider(ActivationLifecycle.class), getProvider(TitusRuntime.class))
);
}
@Override
public boolean equals(Object obj) {
return getClass().equals(obj.getClass());
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@Override
public String toString() {
return "ContainerEventBusModule[]";
}
}
| 730 |
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/guice/ContainerEventBus.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.guice;
import java.lang.reflect.Method;
/**
* Existing Governator implementation of the event bus dispatcher, but also Guava's evenbus do not
* preserve the execution order of the event publishing. It is critical for an instance lifecycle management,
* that it executes according to dependency graph or in the reverse order.
*/
public interface ContainerEventBus {
interface ContainerEvent {
}
class ContainerStartedEvent implements ContainerEvent {
}
interface ContainerEventListener<T extends ContainerEvent> {
void onEvent(T event);
}
void registerListener(Object instance, Method method, Class<? extends ContainerEvent> eventType);
<T extends ContainerEvent> void registerListener(Class<T> eventType, ContainerEventListener<T> eventListener);
void registerListener(ContainerEventListener<? extends ContainerEvent> eventListener);
void submitInOrder(ContainerEvent event);
void submitInReversedOrder(ContainerEvent event);
}
| 731 |
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/guice/ProxyType.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.guice;
/**
*/
public enum ProxyType {
Logging, Spectator, ActiveGuard
}
| 732 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice/internal/DefaultContainerEventBus.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.guice.internal;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.inject.Singleton;
import com.google.common.reflect.TypeToken;
import com.netflix.titus.common.util.guice.ContainerEventBus;
@Singleton
public class DefaultContainerEventBus implements ContainerEventBus {
private final Method eventListenerMethod;
private final List<SubscriberProxy> subscriptionsInRegistrationOrder = new CopyOnWriteArrayList<>();
private final List<SubscriberProxy> subscriptionsInReverseOrder = new CopyOnWriteArrayList<>();
public DefaultContainerEventBus() {
try {
this.eventListenerMethod = ContainerEventListener.class.getDeclaredMethod("onEvent", ContainerEvent.class);
} catch (Exception e) {
throw new RuntimeException("Failed to cache ApplicationEventListener method", e);
}
}
@Override
public void registerListener(Object instance, Method method, Class<? extends ContainerEvent> eventType) {
addSubscription(new SubscriberProxy(instance, method, eventType));
}
@Override
public <T extends ContainerEvent> void registerListener(Class<T> eventType, ContainerEventListener<T> eventListener) {
addSubscription(new SubscriberProxy(eventListener, eventListenerMethod, eventType));
}
@Override
public void registerListener(ContainerEventListener<? extends ContainerEvent> eventListener) {
Type[] genericInterfaces = eventListener.getClass().getGenericInterfaces();
for (Type type : genericInterfaces) {
if (ContainerEventListener.class.isAssignableFrom(TypeToken.of(type).getRawType())) {
ParameterizedType ptype = (ParameterizedType) type;
Class<?> rawType = TypeToken.of(ptype.getActualTypeArguments()[0]).getRawType();
addSubscription(new SubscriberProxy(eventListener, eventListenerMethod, rawType));
return;
}
}
}
@Override
public void submitInOrder(ContainerEvent event) {
submit(event, subscriptionsInRegistrationOrder);
}
@Override
public void submitInReversedOrder(ContainerEvent event) {
submit(event, subscriptionsInReverseOrder);
}
private void submit(ContainerEvent event, List<SubscriberProxy> subscriptions) {
Iterator<SubscriberProxy> it = subscriptions.iterator();
while (it.hasNext()) {
SubscriberProxy proxy = it.next();
try {
proxy.invokeEventHandler(event);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(e);
}
}
}
private void addSubscription(SubscriberProxy proxy) {
subscriptionsInRegistrationOrder.add(proxy);
subscriptionsInReverseOrder.add(proxy);
}
static class SubscriberProxy {
private final Object handlerInstance;
private final Method handlerMethod;
private final Class<?> acceptedType;
SubscriberProxy(Object handlerInstance, Method handlerMethod, Class<?> acceptedType) {
this.handlerInstance = handlerInstance;
this.handlerMethod = handlerMethod;
this.acceptedType = acceptedType;
}
void invokeEventHandler(ContainerEvent event)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (acceptedType.isAssignableFrom(event.getClass())) {
if (!handlerMethod.isAccessible()) {
handlerMethod.setAccessible(true);
}
handlerMethod.invoke(handlerInstance, event);
}
}
}
}
| 733 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice/internal/ProxyMethodInterceptor.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.guice.internal;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.ReflectionExt;
import com.netflix.titus.common.util.guice.ActivationLifecycle;
import com.netflix.titus.common.util.guice.ProxyType;
import com.netflix.titus.common.util.guice.annotation.ProxyConfiguration;
import com.netflix.titus.common.util.proxy.LoggingProxyBuilder;
import com.netflix.titus.common.util.proxy.ProxyInvocationChain;
import com.netflix.titus.common.util.proxy.ProxyInvocationHandler;
import com.netflix.titus.common.util.proxy.internal.DefaultProxyInvocationChain;
import com.netflix.titus.common.util.proxy.internal.GuardingInvocationHandler;
import com.netflix.titus.common.util.proxy.internal.SpectatorInvocationHandler;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*/
@Singleton
public class ProxyMethodInterceptor implements MethodInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ProxyMethodInterceptor.class);
private final LoadingCache<Class<?>, InstanceWrapper> instanceToWrapperMap = CacheBuilder.newBuilder()
.build(new CacheLoader<Class<?>, InstanceWrapper>() {
@Override
public InstanceWrapper load(Class<?> instanceType) throws Exception {
return buildProxy(instanceType);
}
});
private final LoadingCache<ClassMethodPair, Optional<InstanceWrapper>> methodToWrapperMap = CacheBuilder.newBuilder()
.build(new CacheLoader<ClassMethodPair, Optional<InstanceWrapper>>() {
@Override
public Optional<InstanceWrapper> load(ClassMethodPair id) throws Exception {
InstanceWrapper wrapper = instanceToWrapperMap.get(id.instanceType);
if (wrapper.isWrapped(id.method)) {
return Optional.of(wrapper);
}
return Optional.empty();
}
});
private final Provider<ActivationLifecycle> activationLifecycle;
private final Provider<TitusRuntime> titusRuntimeProvider;
@Inject
public ProxyMethodInterceptor(Provider<ActivationLifecycle> activationLifecycle, Provider<TitusRuntime> titusRuntimeProvider) {
this.activationLifecycle = activationLifecycle;
this.titusRuntimeProvider = titusRuntimeProvider;
}
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Class<?> instanceType = ((Method) methodInvocation.getStaticPart()).getDeclaringClass();
Method effectiveMethod = ReflectionExt.findInterfaceMethod(methodInvocation.getMethod()).orElse(methodInvocation.getMethod());
ClassMethodPair id = new ClassMethodPair(instanceType, effectiveMethod);
Optional<InstanceWrapper> wrapper = methodToWrapperMap.get(id);
if (wrapper.isPresent()) {
return wrapper.get().invoke(methodInvocation, effectiveMethod);
}
return methodInvocation.proceed();
}
private InstanceWrapper buildProxy(Class<?> instanceType) {
Optional<ProxyConfiguration> configurationOpt = findProxyConfiguration(instanceType);
if (!configurationOpt.isPresent()) {
return new InstanceWrapper();
}
Optional<Class<?>> interfOpt = findInterface(instanceType);
if (!interfOpt.isPresent()) {
return new InstanceWrapper();
}
return new InstanceWrapper(configurationOpt.get(), interfOpt.get());
}
private Optional<ProxyConfiguration> findProxyConfiguration(Class<?> instanceType) {
ProxyConfiguration configuration = instanceType.getAnnotation(ProxyConfiguration.class);
if (configuration == null || CollectionsExt.isNullOrEmpty(configuration.types())) {
return Optional.empty();
}
return Optional.of(configuration);
}
private Optional<Class<?>> findInterface(Class<?> instanceType) {
Class<?>[] interfaces = instanceType.getInterfaces();
if (CollectionsExt.isNullOrEmpty(interfaces)) {
return Optional.empty();
}
Class interf = interfaces[0];
if (interfaces.length > 1) {
logger.warn("Multiple interfaces found, while proxy supports single interfaces only: {}. Wrapping {}",
instanceType.getName(),
interf.getName()
);
}
return Optional.of(interf);
}
static class ClassMethodPair {
private final Class<?> instanceType;
private final Method method;
ClassMethodPair(Class<?> instanceType, Method method) {
this.instanceType = instanceType;
this.method = method;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClassMethodPair that = (ClassMethodPair) o;
if (instanceType != that.instanceType) {
return false;
}
return method != null ? method.equals(that.method) : that.method == null;
}
@Override
public int hashCode() {
int result = instanceType != null ? instanceType.hashCode() : 0;
result = 31 * result + (method != null ? method.hashCode() : 0);
return result;
}
}
private final static ProxyInvocationHandler<MethodInvocation> EXECUTING_HANDLER =
(proxy, method, args, nativeHandler, chain) -> nativeHandler.proceed();
class InstanceWrapper {
private final Class<?> interf;
private final ProxyInvocationChain<MethodInvocation> chain;
InstanceWrapper() {
this.interf = null;
this.chain = new DefaultProxyInvocationChain<>(Collections.singletonList(EXECUTING_HANDLER));
}
InstanceWrapper(ProxyConfiguration configuration, Class<?> interf) {
this.interf = interf;
this.chain = new DefaultProxyInvocationChain<>(buildInterceptors(configuration, interf));
}
boolean isWrapped(Method method) {
try {
return interf != null && interf.getMethod(method.getName(), method.getParameterTypes()) != null;
} catch (NoSuchMethodException e) {
return false;
}
}
Object invoke(MethodInvocation methodInvocation, Method effectiveMethod) throws Throwable {
return chain.invoke(methodInvocation.getThis(), effectiveMethod, methodInvocation.getArguments(), methodInvocation);
}
private List<ProxyInvocationHandler<MethodInvocation>> buildInterceptors(ProxyConfiguration configuration, Class<?> interf) {
List<ProxyInvocationHandler<MethodInvocation>> interceptors = new ArrayList<>();
for (ProxyType type : configuration.types()) {
switch (type) {
case Logging:
interceptors.add(new LoggingProxyBuilder(interf, null).titusRuntime(titusRuntimeProvider.get()).buildHandler());
break;
case Spectator:
interceptors.add(new SpectatorInvocationHandler<>(interf.getSimpleName(), interf, titusRuntimeProvider.get(), true));
break;
case ActiveGuard:
interceptors.add(new GuardingInvocationHandler<>(interf, instance -> activationLifecycle.get().isActive(instance)));
break;
}
}
interceptors.add(EXECUTING_HANDLER);
return interceptors;
}
}
}
| 734 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice/internal/ActivationProvisionListener.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.guice.internal;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import com.google.inject.spi.ProvisionListener;
import com.netflix.governator.annotations.SuppressLifecycleUninitialized;
import com.netflix.titus.common.util.ReflectionExt;
import com.netflix.titus.common.util.guice.ActivationLifecycle;
import com.netflix.titus.common.util.guice.annotation.Activator;
import com.netflix.titus.common.util.guice.annotation.Deactivator;
import com.netflix.titus.common.util.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Guice {@link ProvisionListener} that scans services for presence of {@link Activator} and {@link Deactivator}
* annotations, and adds them to activation/deactivation lifecycle.
* <p>
* Deactivations happen in the reverse order of activations.
*/
@Singleton
@SuppressLifecycleUninitialized
public class ActivationProvisionListener implements ActivationLifecycle, ProvisionListener {
private static final Logger logger = LoggerFactory.getLogger(ActivationProvisionListener.class);
/**
* Keep all services that need activation/deactivation as a {@link Set} to avoid activating the same instance
* multiple times. <b>Note:</b> the {@link Set} implementation used <b>must</b> preserve insertion order, since
* deactivation needs to happen in the reverse order of activation.
*/
private final Set<ServiceHolder> services = new CopyOnWriteArraySet<>();
private long activationTime = -1;
@Override
public <T> void onProvision(ProvisionInvocation<T> provision) {
T injectee = provision.provision();
if (injectee == null) {
return;
}
ServiceHolder holder = new ServiceHolder(injectee);
if (holder.isEmpty()) {
return;
}
services.add(holder);
}
@Override
public <T> boolean isActive(T instance) {
for (ServiceHolder service : services) {
if (service.getInjectee() == instance) {
return service.isActivated();
}
}
return false;
}
@Override
public void activate() {
long startTime = System.currentTimeMillis();
logger.info("Activating services");
services.forEach(ServiceHolder::activate);
this.activationTime = System.currentTimeMillis() - startTime;
logger.info("Service activation finished in {}[ms]", activationTime);
}
@Override
public void deactivate() {
long startTime = System.currentTimeMillis();
logger.info("Deactivating services");
List<ServiceHolder> reversed = new ArrayList<>(services);
Collections.reverse(reversed);
reversed.forEach(ServiceHolder::deactivate);
logger.info("Service deactivation finished in {}[ms]", System.currentTimeMillis() - startTime);
}
@Override
public long getActivationTimeMs() {
return activationTime;
}
@Override
public List<Pair<String, Long>> getServiceActionTimesMs() {
return services.stream()
.map(holder -> Pair.of(holder.getName(), holder.getActivationTime()))
.collect(Collectors.toList());
}
static class ServiceHolder {
private final Object injectee;
private final String name;
private final List<Method> activateMethods;
private final List<Method> deactivateMethods;
private volatile boolean activated;
private volatile long activationTime = -1;
ServiceHolder(Object injectee) {
this.injectee = injectee;
this.name = injectee.getClass().getSimpleName();
this.activateMethods = ReflectionExt.findAnnotatedMethods(injectee, Activator.class);
this.deactivateMethods = ReflectionExt.findAnnotatedMethods(injectee, Deactivator.class);
}
Object getInjectee() {
return injectee;
}
String getName() {
return name;
}
boolean isActivated() {
return activated;
}
long getActivationTime() {
return activationTime;
}
boolean isEmpty() {
return activateMethods.isEmpty() && deactivateMethods.isEmpty();
}
void activate() {
logger.info("Activating service {}", name);
if (activated) {
logger.warn("Skipping activation process for service {}, as it is already active", name);
return;
}
long startTime = System.currentTimeMillis();
for (Method m : activateMethods) {
try {
m.invoke(injectee);
} catch (Exception e) {
logger.warn("Service {} activation failure after {}[ms]", name, System.currentTimeMillis() - startTime, e);
throw new IllegalStateException(name + " service activation failure", e);
}
}
activated = true;
this.activationTime = System.currentTimeMillis() - startTime;
logger.warn("Service {} activated in {}[ms]", name, activationTime);
}
void deactivate() {
logger.info("Deactivating service {}", name);
if (!activated) {
logger.warn("Skipping deactivation process for service {}, as it is not active", name);
return;
}
long startTime = System.currentTimeMillis();
for (Method m : deactivateMethods) {
try {
m.invoke(injectee);
} catch (Exception e) {
// Do not propagate exception in the deactivation phase
logger.warn("Service {} deactivation failure after {}[ms]", name, System.currentTimeMillis() - startTime, e);
}
}
long deactivationTime = System.currentTimeMillis() - startTime;
logger.warn("Service {} deactivated in {}[ms]", name, deactivationTime);
activated = false;
activationTime = -1;
}
/**
* Two service holders are considered equal if they are holding the same instance (based on object identity).
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ServiceHolder)) {
return false;
}
ServiceHolder other = (ServiceHolder) obj;
return this.injectee == other.injectee;
}
@Override
public int hashCode() {
return injectee.hashCode();
}
}
}
| 735 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice/annotation/ProxyConfiguration.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.guice.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.netflix.titus.common.util.guice.ProxyType;
/**
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ProxyConfiguration {
ProxyType[] types();
}
| 736 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice/annotation/Activator.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.guice.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Method with {@link Activator} annotation is executed as part of active/standby lifecycle processing.
*/
@Retention(RUNTIME)
@Target(METHOD)
public @interface Activator {
}
| 737 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/guice/annotation/Deactivator.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.guice.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Method with {@link Deactivator} annotation is executed as part of active/standby lifecycle processing.
*/
@Retention(RUNTIME)
@Target(METHOD)
public @interface Deactivator {
}
| 738 |
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/code/CodeInvariants.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.code;
/**
* {@link CodeInvariants} registers code invariant violations in functions or entities, which are usually not fatal
* (system self-corrects itself), but are important to track and fix.
*/
public abstract class CodeInvariants {
/**
* Registers an expectation that <code>condition</code> is true.
* @param condition A boolean that is expected to be true.
* @param message For when <code>condition</code> is actually false, a
* <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html#syntax">format string</a>
* which should include information to help debug why <code>condition</code>
* is false.
* @param args Arguments to the format string.
* @return <code>this</code>
*/
public abstract CodeInvariants isTrue(boolean condition, String message, Object... args);
/**
* Registers an expectation that <code>value</code> is not null.
* @param value A value that is expected to be non-null.
* @param message For when <code>value</code> is actually null, a
* <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html#syntax">format string</a>
* which should include information to help debug why <code>value</code> is
* null.
* @param args Arguments to the format string.
* @return <code>this</code>
*/
public abstract CodeInvariants notNull(Object value, String message, Object... args);
/**
* Registers an inconsistency.
* @param message A <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html#syntax">format string</a>
* which should include information to help debug the cause of the inconsistency.
* @param args Arguments to the format string.
* @return <code>this</code>
*/
public abstract CodeInvariants inconsistent(String message, Object... args);
/**
* Registers that an unexpected error has occurred.
* @param message A message string which should include information to help
* debug the cause of the unexpected error.
* @param e An exception object, typically the unexpected error that occurred.
* @return <code>this</code>
*/
public abstract CodeInvariants unexpectedError(String message, Exception e);
/**
* Registers that an unexpected error has occurred.
* @param message A <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html#syntax">format string</a>
* which should include information to help debug the cause of the unexpected
* error.
* @param args Arguments to the format string.
* @return <code>this</code>
*/
public abstract CodeInvariants unexpectedError(String message, Object... args);
}
| 739 |
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/code/LoggingCodeInvariants.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.code;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import com.netflix.titus.common.util.limiter.Limiters;
import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket;
import com.netflix.titus.common.util.time.Clock;
import com.netflix.titus.common.util.time.Clocks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Writes code invariant violations to a log file.
*/
public class LoggingCodeInvariants extends CodeInvariants {
private static final Logger logger = LoggerFactory.getLogger(LoggingCodeInvariants.class);
private static final long DROPPED_LOGS_INTERVAL_MS = 5_000;
private static final CodeInvariants INSTANCE = new LoggingCodeInvariants(
Limiters.createFixedIntervalTokenBucket(
"invariants", 1000, 1000, 100, 1, TimeUnit.SECONDS, Clocks.system()
),
Clocks.system()
);
private final TokenBucket tokenBucket;
private final Clock clock;
private final AtomicLong dropped = new AtomicLong();
private volatile long droppedReportTimestamp;
public LoggingCodeInvariants(TokenBucket tokenBucket, Clock clock) {
this.tokenBucket = tokenBucket;
this.clock = clock;
}
public CodeInvariants isTrue(boolean condition, String message, Object... args) {
if (!condition) {
inconsistent(message, args);
}
return this;
}
public CodeInvariants notNull(Object value, String message, Object... args) {
if (value == null) {
inconsistent(message, args);
}
return this;
}
public CodeInvariants inconsistent(String message, Object... args) {
if (!canWrite()) {
return this;
}
if (args.length == 0) {
logger.warn(message);
}
try {
if (logger.isWarnEnabled()) {
logger.warn(String.format(message, args));
}
} catch (Exception e) {
String errorMessage = message + " (" + e.getMessage() + ')';
logger.warn(errorMessage);
logger.debug(errorMessage, e);
}
return this;
}
public CodeInvariants unexpectedError(String message, Exception e) {
if (!canWrite()) {
return this;
}
if (e == null) {
logger.warn(message);
} else {
String exceptionMessage = e.getMessage() != null ? e.getMessage() : "";
StackTraceElement[] stackTrace = e.getStackTrace();
String errorLocation = (stackTrace != null && stackTrace.length > 0)
? stackTrace[0].toString()
: "no data";
logger.warn("{}: error={}({}), at={}", message, e.getClass().getSimpleName(), exceptionMessage, errorLocation);
logger.debug(message, e);
}
return this;
}
public CodeInvariants unexpectedError(String message, Object... args) {
if (!canWrite()) {
return this;
}
if (logger.isWarnEnabled()) {
logger.warn(String.format(message, args));
}
return this;
}
private boolean canWrite() {
if (tokenBucket.tryTake()) {
return true;
}
dropped.incrementAndGet();
long dropReportDelayMs = clock.wallTime() - droppedReportTimestamp;
if (dropReportDelayMs > DROPPED_LOGS_INTERVAL_MS) {
long current = dropped.getAndSet(0);
if (current > 0) {
logger.warn("Dropped invariant violation logs: count={}", current);
droppedReportTimestamp = clock.wallTime();
}
}
return false;
}
public static CodeInvariants getDefault() {
return INSTANCE;
}
}
| 740 |
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/code/RecordingCodeInvariants.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.code;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static com.netflix.titus.common.util.ExceptionExt.doTry;
public class RecordingCodeInvariants extends CodeInvariants {
private final List<String> violations = new CopyOnWriteArrayList<>();
public List<String> getViolations() {
return new ArrayList<>(violations);
}
@Override
public CodeInvariants isTrue(boolean condition, String message, Object... args) {
if (!condition) {
violations.add(doTry(() -> String.format(message, args)).orElse("Invalid pattern or arguments: " + message));
}
return this;
}
@Override
public CodeInvariants notNull(Object value, String message, Object... args) {
return isTrue(value != null, message, args);
}
@Override
public CodeInvariants inconsistent(String message, Object... args) {
return isTrue(false, message, args);
}
@Override
public CodeInvariants unexpectedError(String message, Exception e) {
return isTrue(false, message);
}
@Override
public CodeInvariants unexpectedError(String message, Object... args) {
return isTrue(false, message, args);
}
}
| 741 |
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/code/CodePointTracker.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.code;
/**
* {@link CodePointTracker} helps to track places in code that are expected to be unreachable.
* If a code point is reached (executed), an information about this fact is registered.
*/
public abstract class CodePointTracker {
private static volatile CodePointTracker INSTANCE;
public void markReachable() {
markReachable(getCodePointFromStackFrame(Thread.currentThread().getStackTrace()[2], "<no_context>"));
}
public void markReachable(String context) {
markReachable(getCodePointFromStackFrame(Thread.currentThread().getStackTrace()[2], context));
}
protected abstract void markReachable(CodePoint codePoint);
public static void mark() {
getDefaultInstance().markReachable(getCodePointFromStackFrame(Thread.currentThread().getStackTrace()[2], "<no_context>"));
}
public static void mark(String context) {
getDefaultInstance().markReachable(getCodePointFromStackFrame(Thread.currentThread().getStackTrace()[2], context));
}
public static void setDefault(CodePointTracker codePointTracker) {
INSTANCE = codePointTracker;
}
private static CodePointTracker getDefaultInstance() {
if (INSTANCE == null) {
INSTANCE = new LoggingCodePointTracker();
}
return INSTANCE;
}
private static CodePoint getCodePointFromStackFrame(StackTraceElement callerFrame, String context) {
return new CodePoint(callerFrame.getClassName(), callerFrame.getMethodName(), callerFrame.getLineNumber(), context);
}
static class CodePoint {
private final String className;
private final String methodName;
private final int lineNumber;
private final String context;
CodePoint(String className, String methodName, int lineNumber, String context) {
this.className = className;
this.methodName = methodName;
this.lineNumber = lineNumber;
this.context = context;
}
String getClassName() {
return className;
}
String getMethodName() {
return methodName;
}
int getLineNumber() {
return lineNumber;
}
String getContext() {
return context;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CodePoint codePoint = (CodePoint) o;
if (lineNumber != codePoint.lineNumber) {
return false;
}
if (className != null ? !className.equals(codePoint.className) : codePoint.className != null) {
return false;
}
if (methodName != null ? !methodName.equals(codePoint.methodName) : codePoint.methodName != null) {
return false;
}
return context != null ? context.equals(codePoint.context) : codePoint.context == null;
}
@Override
public int hashCode() {
int result = className != null ? className.hashCode() : 0;
result = 31 * result + (methodName != null ? methodName.hashCode() : 0);
result = 31 * result + lineNumber;
result = 31 * result + (context != null ? context.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "CodePoint{" +
"className='" + className + '\'' +
", methodName='" + methodName + '\'' +
", lineNumber=" + lineNumber +
", context='" + context + '\'' +
'}';
}
}
}
| 742 |
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/code/CompositeCodeInvariants.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.code;
import java.util.List;
import static java.util.Arrays.asList;
public class CompositeCodeInvariants extends CodeInvariants {
private final List<CodeInvariants> codeInvariants;
public CompositeCodeInvariants(CodeInvariants... codeInvariants) {
this(asList(codeInvariants));
}
public CompositeCodeInvariants(List<CodeInvariants> codeInvariants) {
this.codeInvariants = codeInvariants;
}
@Override
public CodeInvariants isTrue(boolean condition, String message, Object... args) {
codeInvariants.forEach(i -> i.isTrue(condition, message, args));
return this;
}
@Override
public CodeInvariants notNull(Object value, String message, Object... args) {
codeInvariants.forEach(i -> i.notNull(value, message, args));
return this;
}
@Override
public CodeInvariants inconsistent(String message, Object... args) {
codeInvariants.forEach(i -> i.inconsistent(message, args));
return this;
}
@Override
public CodeInvariants unexpectedError(String message, Exception e) {
codeInvariants.forEach(i -> i.unexpectedError(message, e));
return this;
}
@Override
public CodeInvariants unexpectedError(String message, Object... args) {
codeInvariants.forEach(i -> i.unexpectedError(message, args));
return this;
}
}
| 743 |
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/code/SpectatorCodePointTracker.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.code;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link CodePointTracker} implementation that records all encounters in the metrics registry.
* Additionally, each first occurrence of a code point/context is logged.
*/
public class SpectatorCodePointTracker extends CodePointTracker {
private static final Logger logger = LoggerFactory.getLogger(SpectatorCodePointTracker.class);
private final Registry registry;
/* Visible for testing */ final ConcurrentMap<CodePoint, Counter> marked = new ConcurrentHashMap<>();
public SpectatorCodePointTracker(Registry registry) {
this.registry = registry;
}
protected void markReachable(CodePoint codePoint) {
if (!marked.containsKey(codePoint)) {
if (marked.putIfAbsent(codePoint, createCounter(codePoint)) == null) {
markFirst(codePoint);
}
}
marked.get(codePoint).increment();
}
private Counter createCounter(CodePoint codePoint) {
return registry.counter(
"titus.codePoint",
"class", codePoint.getClassName(),
"method", codePoint.getMethodName() + 'L' + codePoint.getLineNumber()
);
}
private void markFirst(CodePoint codePoint) {
logger.warn("Hit {}", codePoint);
}
}
| 744 |
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/code/LoggingCodePointTracker.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.code;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple {@link CodePointTracker} implementation that logs all encounters into the log file.
*/
public class LoggingCodePointTracker extends CodePointTracker {
private static final Logger logger = LoggerFactory.getLogger(LoggingCodePointTracker.class);
@Override
protected void markReachable(CodePoint codePoint) {
logger.warn("Hit {}", codePoint);
}
}
| 745 |
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/code/SpectatorCodeInvariants.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.code;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
public class SpectatorCodeInvariants extends CodeInvariants {
private final Counter violations;
public SpectatorCodeInvariants(Id rootId, Registry registry) {
this.violations = registry.counter(rootId);
}
@Override
public CodeInvariants isTrue(boolean condition, String message, Object... args) {
if (!condition) {
violations.increment();
}
return this;
}
@Override
public CodeInvariants notNull(Object value, String message, Object... args) {
if (value == null) {
violations.increment();
}
return this;
}
@Override
public CodeInvariants inconsistent(String message, Object... args) {
violations.increment();
return this;
}
@Override
public CodeInvariants unexpectedError(String message, Exception e) {
violations.increment();
return this;
}
@Override
public CodeInvariants unexpectedError(String message, Object... args) {
violations.increment();
return this;
}
}
| 746 |
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/time/TestClock.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.time;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Month;
import java.util.concurrent.TimeUnit;
/**
*/
public interface TestClock extends Clock {
long advanceTime(long interval, TimeUnit timeUnit);
default long advanceTime(Duration duration) {
return advanceTime(duration.toMillis(), TimeUnit.MILLISECONDS);
}
default TestClock resetDate(int year, Month month, int day) {
throw new IllegalStateException("method not supported");
}
default TestClock resetTime(int hour, int minute, int second) {
throw new IllegalStateException("method not supported");
}
default TestClock jumpForwardTo(DayOfWeek dayOfWeek) {
throw new IllegalStateException("method not supported");
}
}
| 747 |
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/time/TestWorldClock.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.time;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.util.concurrent.TimeUnit;
import com.netflix.titus.common.util.DateTimeExt;
class TestWorldClock implements TestClock {
private OffsetDateTime dateTime;
TestWorldClock(String zoneId, int year, Month month, int day) {
this.dateTime = OffsetDateTime.of(year, month.getValue(), day, 0, 0, 0, 0, DateTimeExt.toZoneOffset(zoneId));
}
TestWorldClock(String zoneId) {
this.dateTime = OffsetDateTime.of(LocalDateTime.now(), DateTimeExt.toZoneOffset(zoneId));
}
@Override
public long advanceTime(long interval, TimeUnit timeUnit) {
this.dateTime = dateTime.plusNanos(timeUnit.toNanos(interval));
return wallTime();
}
@Override
public TestClock resetDate(int year, Month month, int dayOfMonth) {
this.dateTime = dateTime.withYear(year).withMonth(month.getValue()).withDayOfMonth(dayOfMonth);
return this;
}
@Override
public TestClock resetTime(int hour, int minute, int second) {
this.dateTime = dateTime.withHour(hour).withMinute(minute).withSecond(second);
return this;
}
@Override
public TestClock jumpForwardTo(DayOfWeek dayOfWeek) {
int expected = dayOfWeek.getValue();
int current = dateTime.getDayOfWeek().getValue();
if (current == expected) {
return this;
}
int plusDays = expected > current
? expected - current
: 7 - (current - expected);
this.dateTime = dateTime.plusDays(plusDays);
return this;
}
@Override
public long nanoTime() {
throw new IllegalStateException("Method not supported");
}
@Override
public long wallTime() {
return dateTime.toEpochSecond() * 1_000;
}
}
| 748 |
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/time/Clocks.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.time;
import java.time.Month;
import java.util.concurrent.TimeUnit;
import com.netflix.titus.common.util.time.internal.DefaultTestClock;
import com.netflix.titus.common.util.time.internal.SystemClock;
import rx.Scheduler;
import rx.schedulers.TestScheduler;
/**
*/
public class Clocks {
public static Clock system() {
return SystemClock.INSTANCE;
}
public static Clock scheduler(Scheduler scheduler) {
return new Clock() {
@Override
public long nanoTime() {
return TimeUnit.MILLISECONDS.toNanos(scheduler.now());
}
@Override
public long wallTime() {
return scheduler.now();
}
};
}
public static TestClock test() {
return new DefaultTestClock();
}
public static TestClock testWorldClock() {
return new TestWorldClock("UTC");
}
public static TestClock testWorldClock(String zoneId) {
return new TestWorldClock(zoneId);
}
public static TestClock testWorldClock(int year, Month month, int day) {
return new TestWorldClock("UTC", year, month, day);
}
public static TestClock testScheduler(TestScheduler testScheduler) {
return new TestClock() {
@Override
public long advanceTime(long interval, TimeUnit timeUnit) {
testScheduler.advanceTimeBy(interval, timeUnit);
return testScheduler.now();
}
@Override
public long nanoTime() {
return TimeUnit.MILLISECONDS.toNanos(testScheduler.now());
}
@Override
public long wallTime() {
return testScheduler.now();
}
};
}
}
| 749 |
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/time/Clock.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.time;
public interface Clock {
/**
* Time elapsed in nanoseconds.
*/
long nanoTime();
/**
* Current time in milliseconds, equivalent to {@link System#currentTimeMillis()}.
*/
long wallTime();
/**
* Returns true, of the current time is past the given timestamp.
*/
default boolean isPast(long timestamp) {
return wallTime() > timestamp;
}
}
| 750 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/time | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/time/internal/SystemClock.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.time.internal;
import com.netflix.titus.common.util.time.Clock;
/**
*/
public class SystemClock implements Clock {
public static final Clock INSTANCE = new SystemClock();
@Override
public long wallTime() {
return System.currentTimeMillis();
}
@Override
public long nanoTime() {
return System.nanoTime();
}
}
| 751 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/time | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/time/internal/DefaultTestClock.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.time.internal;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.time.TestClock;
/**
*/
public class DefaultTestClock implements TestClock {
private volatile long elapsedTimeNs;
@Override
public long advanceTime(long interval, TimeUnit timeUnit) {
Preconditions.checkArgument(interval >= 0, "Time can move only forward, while requested" + interval + timeUnit);
return elapsedTimeNs += timeUnit.toNanos(interval);
}
@Override
public long nanoTime() {
return elapsedTimeNs;
}
@Override
public long wallTime() {
return elapsedTimeNs / 1000_000;
}
}
| 752 |
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/concurrency/CallbackCountDownLatch.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.concurrency;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
/**
* A {@link CountDownLatch} that executes a callback when its countdown reaches zero. The callback action will be
* executed asynchronously by the provided {@link Executor}, or synchronously in the Thread that calls the last
* <tt>countDown()</tt> when no {@link Executor} is provided.
*/
public class CallbackCountDownLatch extends CountDownLatch {
private final CompletableFuture<Void> future;
public CallbackCountDownLatch(int size, Runnable callback) {
this(size, callback, null);
}
public CallbackCountDownLatch(int size, Runnable callback, Executor executor) {
super(size);
future = new CompletableFuture<>();
if (executor == null) {
future.thenRun(callback);
} else {
future.thenRunAsync(callback, executor);
}
if (size == 0) {
future.complete(null);
}
}
@Override
public void countDown() {
super.countDown();
if (getCount() <= 0) {
future.complete(null);
}
}
}
| 753 |
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/closeable/CloseableReference.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.closeable;
import java.util.function.Consumer;
import com.google.common.base.Preconditions;
/**
* A reference holder to a resource with attached close action.
*/
public interface CloseableReference<T> extends AutoCloseable {
T get();
boolean isClosed();
/**
* Override without exception in the signature.
*/
@Override
void close();
static <T> Builder<T> newBuilder() {
return new Builder<>();
}
static <T> CloseableReference<T> referenceOf(T value) {
return CloseableReference.<T>newBuilder()
.withResource(value)
.withCloseAction(() -> {
// nothing
})
.build();
}
static <T> CloseableReference<T> referenceOf(T value, Consumer<T> closeAction) {
return CloseableReference.<T>newBuilder()
.withResource(value)
.withCloseAction(() -> closeAction.accept(value))
.build();
}
class Builder<T> {
private static final Runnable NO_OP_ON_SUCCESS = () -> {
};
private static final Consumer<Throwable> NO_OP_ON_ERROR = e -> {
};
private T resource;
private Runnable closeAction;
private boolean serialize;
private boolean swallowException;
private Runnable onSuccessCallback = NO_OP_ON_SUCCESS;
private Consumer<Throwable> onErrorCallback = NO_OP_ON_ERROR;
public Builder<T> withResource(T resource) {
this.resource = resource;
return this;
}
public Builder<T> withCloseAction(Runnable closeAction) {
this.closeAction = closeAction;
return this;
}
public Builder<T> withSerialize(boolean serialize) {
this.serialize = serialize;
return this;
}
public Builder<T> withSwallowException(boolean swallowException) {
this.swallowException = swallowException;
return this;
}
public Builder<T> withOnSuccessCallback(Runnable onSuccessCallback) {
this.onSuccessCallback = onSuccessCallback == null ? NO_OP_ON_SUCCESS : onSuccessCallback;
return this;
}
public Builder<T> withOnErrorCallback(Consumer<Throwable> onErrorCallback) {
this.onErrorCallback = onErrorCallback == null ? NO_OP_ON_ERROR : onErrorCallback;
return this;
}
public CloseableReference<T> build() {
Preconditions.checkNotNull(resource, "Closeable resource is null");
Preconditions.checkNotNull(closeAction, "Closeable action is null");
return new DefaultCloseableReference<>(resource, closeAction, serialize, swallowException, onSuccessCallback, onErrorCallback);
}
}
}
| 754 |
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/closeable/CloseableDependency.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.closeable;
import javax.annotation.PreDestroy;
/**
* Dependency injected instrumented wrapper for {@link CloseableReference}.
*/
public class CloseableDependency<T> {
private final CloseableReference<T> closeableReference;
private CloseableDependency(CloseableReference<T> closeableReference) {
this.closeableReference = closeableReference;
}
public T get() {
return closeableReference.get();
}
@PreDestroy
public void close() {
closeableReference.close();
}
public static <T> CloseableDependency<T> of(CloseableReference<T> closeableReference) {
return new CloseableDependency<>(closeableReference);
}
}
| 755 |
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/closeable/DefaultCloseableReference.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.closeable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import com.netflix.titus.common.util.ExceptionExt;
class DefaultCloseableReference<T> implements CloseableReference<T> {
private final T resource;
private final Runnable closeAction;
private final boolean serialize;
private final boolean swallowException;
private final Runnable onSuccessCallback;
private final Consumer<Throwable> onErrorCallback;
private final AtomicBoolean closed = new AtomicBoolean();
DefaultCloseableReference(T resource,
Runnable closeAction,
boolean serialize,
boolean swallowException,
Runnable onSuccessCallback,
Consumer<Throwable> onErrorCallback) {
this.resource = resource;
this.closeAction = closeAction;
this.serialize = serialize;
this.swallowException = swallowException;
this.onSuccessCallback = onSuccessCallback;
this.onErrorCallback = onErrorCallback;
}
@Override
public T get() {
return resource;
}
@Override
public boolean isClosed() {
return closed.get();
}
@Override
public void close() {
if (closed.getAndSet(true)) {
return;
}
try {
doClose();
ExceptionExt.silent(onSuccessCallback::run);
} catch (Throwable e) {
ExceptionExt.silent(() -> onErrorCallback.accept(e));
if (!swallowException) {
throw e;
}
}
}
private void doClose() {
if (serialize) {
synchronized (closed) {
closeAction.run();
}
} else {
closeAction.run();
}
}
}
| 756 |
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/archaius2/ArchaiusProxyInvocationHandler.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.archaius2;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import com.google.common.base.Preconditions;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
import com.netflix.archaius.api.annotations.PropertyName;
import com.netflix.titus.common.environment.MyEnvironment;
import com.netflix.titus.common.util.ReflectionExt;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.common.util.tuple.Either;
import com.netflix.titus.common.util.unit.TimeUnitExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class ArchaiusProxyInvocationHandler implements InvocationHandler {
private static final Logger logger = LoggerFactory.getLogger(ArchaiusProxyInvocationHandler.class);
private interface MethodHandler {
Object get() throws Throwable;
}
private final Class<?> apiInterface;
private final String prefix;
private final MyEnvironment environment;
private final Map<Method, MethodHandler> methodWrappers;
ArchaiusProxyInvocationHandler(Class<?> apiInterface, String prefix, MyEnvironment environment) {
Preconditions.checkArgument(apiInterface.isInterface(), "Not interface: %s", apiInterface);
this.apiInterface = apiInterface;
String effectivePrefix = prefix;
if (prefix == null) {
Configuration configurationAnnotation = apiInterface.getAnnotation(Configuration.class);
effectivePrefix = configurationAnnotation != null ? configurationAnnotation.prefix() : null;
}
this.prefix = StringExt.isEmpty(effectivePrefix) ? "" : (effectivePrefix.endsWith(".") ? effectivePrefix : effectivePrefix + '.');
this.environment = environment;
Map<Method, MethodHandler> methodWrappers = new HashMap<>();
for (Method method : apiInterface.getMethods()) {
Preconditions.checkArgument(
method.getParameterCount() == 0 || method.isDefault(),
"Method with no parameters expected or a default method"
);
if (!method.isDefault()) {
methodWrappers.put(method, new PropertyMethodHandler(method));
}
}
this.methodWrappers = methodWrappers;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.isDefault()) {
return ReflectionExt.invokeDefault(proxy, apiInterface, method, args);
}
MethodHandler wrapper = methodWrappers.get(method);
if (wrapper != null) {
return wrapper.get();
}
// Must be one of the Object methods.
return method.invoke(this);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(apiInterface.getSimpleName()).append('{');
methodWrappers.forEach((method, handler) -> {
if (handler instanceof PropertyMethodHandler) {
builder.append(handler).append(", ");
}
});
builder.setLength(builder.length() - 2);
builder.append('}');
return builder.toString();
}
static <I> I newProxy(Class<I> apiInterface, String prefix, MyEnvironment environment) {
Preconditions.checkArgument(apiInterface.isInterface(), "Java interface expected");
return (I) Proxy.newProxyInstance(
apiInterface.getClassLoader(),
new Class[]{apiInterface},
new ArchaiusProxyInvocationHandler(apiInterface, prefix, environment)
);
}
private class PropertyMethodHandler implements MethodHandler {
private final String key;
private final String baseKeyName;
private final String defaultValue;
private final Method method;
private volatile ValueHolder valueHolder;
private PropertyMethodHandler(Method method) {
this.method = method;
this.key = buildKeyName(method);
this.baseKeyName = buildKeyBaseName(key);
DefaultValue defaultAnnotation = method.getAnnotation(DefaultValue.class);
this.defaultValue = defaultAnnotation == null ? null : defaultAnnotation.value();
this.valueHolder = new ValueHolder(method, environment.getProperty(key, defaultValue));
}
@Override
public Object get() {
String currentString = environment.getProperty(key, defaultValue);
if (Objects.equals(currentString, valueHolder.getStringValue())) {
return valueHolder.getValue();
}
try {
this.valueHolder = new ValueHolder(method, currentString);
} catch (Exception e) {
// Do not propagate exception. Return the previous result.
logger.debug("Bad property value: key={}, value={}", key, currentString);
}
return valueHolder.getValue();
}
@Override
public String toString() {
return baseKeyName + '=' + valueHolder.getValue();
}
private String buildKeyName(Method method) {
PropertyName propertyNameAnnotation = method.getAnnotation(PropertyName.class);
if (propertyNameAnnotation != null) {
return StringExt.isEmpty(prefix) ? propertyNameAnnotation.name() : prefix + propertyNameAnnotation.name();
}
Either<String, IllegalArgumentException> baseName = StringExt.nameFromJavaBeanGetter(method.getName());
if (baseName.hasError()) {
throw baseName.getError();
}
return StringExt.isEmpty(prefix) ? baseName.getValue() : prefix + baseName.getValue();
}
private String buildKeyBaseName(String key) {
int idx = key.lastIndexOf('.');
return idx < 0 ? key : key.substring(idx + 1);
}
}
private static class ValueHolder {
private final String stringValue;
private final Object value;
private ValueHolder(Method method, String stringValue) {
Class<?> valueType = method.getReturnType();
Preconditions.checkArgument(!valueType.isPrimitive() || stringValue != null, "Configuration value cannot be null for primitive types");
this.stringValue = stringValue;
if (stringValue == null) {
if (List.class.isAssignableFrom(valueType)) {
this.value = Collections.emptyList();
} else if (Set.class.isAssignableFrom(valueType)) {
this.value = Collections.emptySet();
} else {
this.value = null;
}
} else if (String.class.equals(valueType)) {
this.value = stringValue;
} else if (Long.class.equals(valueType) || long.class.equals(valueType)) {
this.value = Long.parseLong(stringValue);
} else if (Integer.class.equals(valueType) || int.class.equals(valueType)) {
this.value = Integer.parseInt(stringValue);
} else if (Double.class.equals(valueType) || double.class.equals(valueType)) {
this.value = Double.parseDouble(stringValue);
} else if (Float.class.equals(valueType) || float.class.equals(valueType)) {
this.value = Float.parseFloat(stringValue);
} else if (Boolean.class.equals(valueType) || boolean.class.equals(valueType)) {
this.value = Boolean.parseBoolean(stringValue);
} else if (Duration.class.equals(valueType)) {
long intervalMs = TimeUnitExt.toMillis(stringValue).orElseThrow(() -> new IllegalArgumentException("Invalid time interval: " + stringValue));
this.value = Duration.ofMillis(intervalMs);
} else if (List.class.isAssignableFrom(valueType)) {
ParameterizedType genericReturnType = (ParameterizedType) method.getGenericReturnType();
this.value = parseList(genericReturnType.getActualTypeArguments()[0], stringValue);
} else if (Set.class.isAssignableFrom(valueType)) {
ParameterizedType genericReturnType = (ParameterizedType) method.getGenericReturnType();
this.value = new HashSet<>(parseList(genericReturnType.getActualTypeArguments()[0], stringValue));
} else {
throw new IllegalArgumentException("Not supported configuration type: " + method);
}
}
public String getStringValue() {
return stringValue;
}
private Object getValue() {
return value;
}
private List<String> parseList(Type elementType, String stringValue) {
Preconditions.checkArgument(elementType.equals(String.class), "Only List<String> supported");
return StringExt.splitByComma(stringValue);
}
}
}
| 757 |
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/archaius2/SpringConfig.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.archaius2;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.netflix.archaius.api.Config;
import com.netflix.archaius.config.AbstractConfig;
import com.netflix.titus.common.util.StringExt;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
public class SpringConfig extends AbstractConfig {
private final String prefix;
private final Environment environment;
public SpringConfig(String prefix, Environment environment) {
this.prefix = formatPrefix(prefix);
this.environment = environment;
}
@Override
public Object getRawProperty(String key) {
return environment.getProperty(fullKey(key));
}
@Override
public boolean containsKey(String key) {
return environment.containsProperty(fullKey(key));
}
@Override
public Iterator<String> getKeys() {
return getAllProperties().keySet().iterator();
}
@Override
public Config getPrefixedView(String prefix) {
return new SpringConfig(this.prefix + prefix, environment);
}
@Override
public boolean isEmpty() {
return getAllProperties().isEmpty();
}
private String fullKey(String key) {
return prefix.isEmpty() ? key : prefix + key;
}
/**
* Based on the following recommendation: https://github.com/spring-projects/spring-framework/issues/14874
*/
private Map<String, Object> getAllProperties() {
Map<String, Object> all = new HashMap<>();
if (environment instanceof ConfigurableEnvironment) {
for (PropertySource<?> propertySource : ((ConfigurableEnvironment) environment).getPropertySources()) {
if (propertySource instanceof EnumerablePropertySource) {
for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
if (key.startsWith(prefix)) {
all.put(key.substring(prefix.length()), propertySource.getProperty(key));
}
}
}
}
}
return all;
}
static String formatPrefix(String prefix) {
return StringExt.isEmpty(prefix) ? "" : (prefix.endsWith(".") ? prefix : prefix + '.');
}
}
| 758 |
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/archaius2/Archaius2Ext.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.archaius2;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import com.google.common.base.Preconditions;
import com.netflix.archaius.ConfigProxyFactory;
import com.netflix.archaius.DefaultPropertyFactory;
import com.netflix.archaius.api.Config;
import com.netflix.archaius.api.Property;
import com.netflix.archaius.api.PropertyRepository;
import com.netflix.archaius.config.MapConfig;
import com.netflix.titus.common.environment.MyEnvironment;
import com.netflix.titus.common.environment.MyEnvironments;
import com.netflix.titus.common.util.Evaluators;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.common.util.closeable.CloseableReference;
import org.springframework.core.env.Environment;
import reactor.core.publisher.Flux;
public final class Archaius2Ext {
private static final Config EMPTY_CONFIG = new MapConfig(Collections.emptyMap());
private static final ConfigProxyFactory DEFAULT_CONFIG_PROXY_FACTORY = new ConfigProxyFactory(
EMPTY_CONFIG,
EMPTY_CONFIG.getDecoder(),
DefaultPropertyFactory.from(EMPTY_CONFIG)
);
/**
* Parse string value like "1, 10, 1000" to an array of {@link Duration} values, assuming the values represent
* milliseconds.
*/
public static Supplier<List<Duration>> asDurationList(Supplier<String> configSupplier) {
Function<String, List<Duration>> memoizedFunction = Evaluators.memoizeLast(v -> StringExt.parseDurationMsList(v).orElse(Collections.emptyList()));
return () -> memoizedFunction.apply(configSupplier.get());
}
/**
* Observe property value changes. Emits current value on subscriptions.
*/
public static <T> Flux<T> watch(Property<T> property) {
Flux<T> observer = Flux.create(emitter -> {
Property.Subscription subscription = property.subscribe(emitter::next);
emitter.onCancel(subscription::unsubscribe);
});
return Flux.just(property.get()).concatWith(observer);
}
/**
* See {@link #watch(Property)}.
*/
public static <T> Flux<T> watch(PropertyRepository propertyRepository, String key, Class<T> type) {
return watch(propertyRepository.get(key, type));
}
/**
* Create Archaius based configuration object initialized with default values. Defaults can be overridden
* by providing key/value pairs as parameters.
*/
public static <C> C newConfiguration(Class<C> configType, String... keyValuePairs) {
if (keyValuePairs.length == 0) {
return DEFAULT_CONFIG_PROXY_FACTORY.newProxy(configType);
}
Preconditions.checkArgument(keyValuePairs.length % 2 == 0, "Expected even number of arguments");
Map<String, String> props = new HashMap<>();
int len = keyValuePairs.length / 2;
for (int i = 0; i < len; i++) {
props.put(keyValuePairs[i * 2], keyValuePairs[i * 2 + 1]);
}
Config config = new MapConfig(props);
return newConfiguration(configType, config);
}
/**
* Create Archaius based configuration object initialized with default values. Overrides can be provided
* via the properties parameter.
*/
public static <C> C newConfiguration(Class<C> configType, Map<String, String> properties) {
return newConfiguration(configType, new MapConfig(properties));
}
/**
* Create Archaius based configuration object based by the given {@link Config}.
*/
public static <C> C newConfiguration(Class<C> configType, Config config) {
ConfigProxyFactory factory = new ConfigProxyFactory(config, config.getDecoder(), DefaultPropertyFactory.from(config));
return factory.newProxy(configType);
}
/**
* Create Archaius based configuration object based by the given {@link Config}.
*/
public static <C> C newConfiguration(Class<C> configType, String prefix, Config config) {
ConfigProxyFactory factory = new ConfigProxyFactory(config, config.getDecoder(), DefaultPropertyFactory.from(config));
return factory.newProxy(configType, prefix);
}
public static <C> C newConfiguration(Class<C> configType, MyEnvironment environment) {
return ArchaiusProxyInvocationHandler.newProxy(configType, null, environment);
}
public static <C> C newConfiguration(Class<C> configType, String prefix, MyEnvironment environment) {
return ArchaiusProxyInvocationHandler.newProxy(configType, prefix, environment);
}
/**
* Given object, return configuration associated with it. For properties:
* a.pattern=a.*
* a.intValue=123
* b.pattern=b.*
* b.intValue=345
* c.pattern=.*
* c.intValue=0
* <p>
* Evaluate patterns in the alphabetic order until first matches, and map the property subtree onto configuration
* interface. If nothing matches, returns the default value.
*/
public static <OBJECT, CONFIG> ObjectConfigurationResolver<OBJECT, CONFIG> newObjectConfigurationResolver(
Config configuration,
Function<OBJECT, String> selectorFieldAccessor,
Class<CONFIG> configType,
CONFIG defaultConfig) {
return new Archaius2ObjectConfigurationResolver<>(
configuration,
selectorFieldAccessor,
configType,
defaultConfig
);
}
/**
* See {@link #newObjectConfigurationResolver(Config, Function, Class, Object)}. As Spring environment does not support
* configuration change callbacks, so we have to make an explicit periodic updates.
*
* @param updateTrigger on each emitted item from this {@link Flux} instance, a configuration update is made
* @return resolver instance with a closable reference. Calling {@link CloseableReference#close()}, terminates
* configuration update subscription.
*/
@Deprecated
public static <OBJECT, CONFIG> CloseableReference<ObjectConfigurationResolver<OBJECT, CONFIG>> newObjectConfigurationResolver(
String prefix,
Environment environment,
Function<OBJECT, String> selectorFieldAccessor,
Class<CONFIG> configType,
CONFIG defaultConfig,
Flux<Long> updateTrigger) {
String formattedPrefix = SpringConfig.formatPrefix(prefix);
MyEnvironment wrapper = MyEnvironments.newSpring(environment);
return PeriodicallyRefreshingObjectConfigurationResolver.newInstance(
new SpringConfig(formattedPrefix, environment),
selectorFieldAccessor,
root -> newConfiguration(configType, formattedPrefix + root, wrapper),
defaultConfig,
updateTrigger
);
}
/**
* Write {@link Config} to {@link String}.
*/
public static String toString(Config config) {
StringBuilder sb = new StringBuilder("{");
for (Iterator<String> it = config.getKeys(); it.hasNext(); ) {
String key = it.next();
sb.append(key).append('=').append(config.getString(key, ""));
if (it.hasNext()) {
sb.append(", ");
}
}
return sb.append('}').toString();
}
}
| 759 |
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/archaius2/PeriodicallyRefreshingObjectConfigurationResolver.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.archaius2;
import java.time.Duration;
import java.util.function.Function;
import com.netflix.archaius.api.Config;
import com.netflix.titus.common.util.closeable.CloseableReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.util.retry.Retry;
/**
* Spring Environment does not provide change callbacks. In this integration we refresh the data periodically using the
* provided update trigger.
*/
class PeriodicallyRefreshingObjectConfigurationResolver<OBJECT, CONFIG> implements ObjectConfigurationResolver<OBJECT, CONFIG> {
private static final Logger logger = LoggerFactory.getLogger(PeriodicallyRefreshingObjectConfigurationResolver.class);
private static final Duration RETRY_INTERVAL = Duration.ofSeconds(5);
private final Config configuration;
private final Archaius2ObjectConfigurationResolver<OBJECT, CONFIG> delegate;
PeriodicallyRefreshingObjectConfigurationResolver(Config configuration,
Function<OBJECT, String> selectorFieldAccessor,
Function<String, CONFIG> dynamicProxyFactory,
CONFIG defaultConfig) {
this.configuration = configuration;
this.delegate = new Archaius2ObjectConfigurationResolver<>(
configuration,
selectorFieldAccessor,
dynamicProxyFactory,
defaultConfig
);
}
@Override
public CONFIG resolve(OBJECT object) {
return delegate.resolve(object);
}
void refresh() {
try {
delegate.onConfigUpdated(configuration);
} catch (Exception e) {
logger.warn("Refresh error: {}", e.getMessage());
logger.debug("Stack trace", e);
}
}
static <OBJECT, CONFIG> CloseableReference<ObjectConfigurationResolver<OBJECT, CONFIG>> newInstance(Config configuration,
Function<OBJECT, String> selectorFieldAccessor,
Function<String, CONFIG> dynamicProxyFactory,
CONFIG defaultConfig,
Flux<Long> updateTrigger) {
PeriodicallyRefreshingObjectConfigurationResolver<OBJECT, CONFIG> resolver = new PeriodicallyRefreshingObjectConfigurationResolver<>(
configuration, selectorFieldAccessor, dynamicProxyFactory, defaultConfig
);
Disposable disposable = updateTrigger
.retryWhen(Retry.backoff(Long.MAX_VALUE, RETRY_INTERVAL))
.subscribe(tick -> resolver.refresh());
return CloseableReference.<ObjectConfigurationResolver<OBJECT, CONFIG>>newBuilder()
.withResource(resolver)
.withCloseAction(disposable::dispose)
.withSwallowException(true)
.build();
}
}
| 760 |
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/archaius2/Archaius2ObjectConfigurationResolver.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.archaius2;
import java.io.Closeable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import com.netflix.archaius.api.Config;
import com.netflix.archaius.api.ConfigListener;
import com.netflix.titus.common.util.PropertiesExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class Archaius2ObjectConfigurationResolver<OBJECT, CONFIG> implements ObjectConfigurationResolver<OBJECT, CONFIG>, ConfigListener, Closeable {
private static final Logger logger = LoggerFactory.getLogger(Archaius2ObjectConfigurationResolver.class);
private final Config configuration;
private final Function<OBJECT, String> selectorFieldAccessor;
private final Function<String, CONFIG> dynamicProxyFactory;
private final CONFIG defaultConfig;
private volatile SortedMap<String, Rule<CONFIG>> configMap = Collections.emptySortedMap();
Archaius2ObjectConfigurationResolver(Config configuration,
Function<OBJECT, String> selectorFieldAccessor,
Class<CONFIG> configType,
CONFIG defaultConfig) {
this(configuration,
selectorFieldAccessor,
root -> Archaius2Ext.newConfiguration(configType, root, configuration),
defaultConfig
);
}
Archaius2ObjectConfigurationResolver(Config configuration,
Function<OBJECT, String> selectorFieldAccessor,
Function<String, CONFIG> dynamicProxyFactory,
CONFIG defaultConfig) {
this.configuration = configuration;
this.selectorFieldAccessor = selectorFieldAccessor;
this.dynamicProxyFactory = dynamicProxyFactory;
this.defaultConfig = defaultConfig;
configuration.addListener(this);
doUpdate();
}
@Override
public void close() {
configuration.removeListener(this);
}
@Override
public CONFIG resolve(OBJECT object) {
if (object == null) {
return defaultConfig;
}
String selectorValue = selectorFieldAccessor.apply(object);
if (selectorValue == null) {
return defaultConfig;
}
for (Map.Entry<String, Rule<CONFIG>> entry : configMap.entrySet()) {
Rule<CONFIG> rule = entry.getValue();
if (rule.getPattern().matcher(selectorValue).matches()) {
return rule.getConfig();
}
}
return defaultConfig;
}
@Override
public void onConfigAdded(Config config) {
doUpdate();
}
@Override
public void onConfigRemoved(Config config) {
doUpdate();
}
@Override
public void onConfigUpdated(Config config) {
doUpdate();
}
@Override
public void onError(Throwable error, Config config) {
logger.debug("Configuration error", error);
}
private void doUpdate() {
List<String> keys = Lists.newArrayList(configuration.getKeys());
Set<String> roots = PropertiesExt.getRootNames(keys, 1);
SortedMap<String, Rule<CONFIG>> newConfigMap = new TreeMap<>();
roots.forEach(root -> processSubKeys(root).ifPresent(value -> newConfigMap.put(root, value)));
this.configMap = newConfigMap;
}
private Optional<Rule<CONFIG>> processSubKeys(String root) {
String patternProperty = root + ".pattern";
String patternString = configuration.getString(patternProperty, null);
if (patternString == null) {
return Optional.empty();
}
Rule<CONFIG> previous = configMap.get(root);
Pattern pattern;
if (previous != null && previous.getPatternString().equals(patternString)) {
pattern = previous.getPattern();
} else {
try {
pattern = Pattern.compile(patternString);
} catch (Exception e) {
logger.warn("Invalid regular expression in property {}: {}", patternProperty, patternString);
return Optional.ofNullable(previous);
}
}
if (previous != null) {
return Optional.of(new Rule<>(patternString, pattern, previous.getConfig()));
}
return Optional.of(new Rule<>(patternString, pattern, dynamicProxyFactory.apply(root)));
}
private static class Rule<CONFIG> {
private final String patternString;
private final Pattern pattern;
private final CONFIG config;
private Rule(String patternString, Pattern pattern, CONFIG config) {
this.patternString = patternString;
this.pattern = pattern;
this.config = config;
}
private String getPatternString() {
return patternString;
}
private Pattern getPattern() {
return pattern;
}
private CONFIG getConfig() {
return config;
}
}
}
| 761 |
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/archaius2/ObjectConfigurationResolver.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.archaius2;
/**
* Given object, return configuration associated with it.
*/
public interface ObjectConfigurationResolver<OBJECT, CONFIG> {
CONFIG resolve(OBJECT object);
}
| 762 |
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/archaius2/Archaius2ConfigurationLogger.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.archaius2;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.archaius.api.Config;
import com.netflix.archaius.api.config.CompositeConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Write the resolved archaius2 configuration to the log file. This is one time operation executed
* during the container bootstrap.
*/
@Singleton
public class Archaius2ConfigurationLogger {
private static final Logger logger = LoggerFactory.getLogger(Archaius2ConfigurationLogger.class);
@Inject
public Archaius2ConfigurationLogger(Config config) {
Properties props = new Properties();
config.getKeys().forEachRemaining(k -> props.put(k, config.getString(k)));
// Print loaded properties
ConfigLogVisitor visitor = new ConfigLogVisitor();
config.accept(visitor);
// We do not log this directly in the visitor callback to avoid deadlock on the System.props Hashtable, and log4j
// internal synchronizer.
visitor.output.forEach(logger::info);
}
private static class ConfigLogVisitor implements CompositeConfig.CompositeVisitor<Void> {
private String prefix = "";
private final List<String> output = new ArrayList<>();
@Override
public Void visitKey(String key, Object value) {
output.add(String.format("%s%s = %s", prefix, key, value));
return null;
}
@Override
public Void visitChild(String name, Config child) {
output.add(String.format("%sConfig: %s", prefix, name));
prefix += " ";
child.accept(this);
prefix = prefix.substring(0, prefix.length() - 2);
return null;
}
}
}
| 763 |
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/feature/FeatureGuardWhiteListConfiguration.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.feature;
import com.netflix.archaius.api.annotations.DefaultValue;
/**
* Feature activation configuration. Each instantiation of this configuration should start with a feature specific prefix.
*/
public interface FeatureGuardWhiteListConfiguration {
/**
* If set to false, the feature is disabled. If set to true, the feature activation is determined by evaluating
* the remaining predicates.
*/
@DefaultValue("true")
boolean isFeatureEnabled();
/**
* White list. If matches, the feature is enabled.
*/
@DefaultValue("NOTHING")
String getWhiteList();
/**
* Black list. If matches, the feature is disabled.
*/
@DefaultValue("NOTHING")
String getBlackList();
}
| 764 |
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/feature/FeatureGuardForField.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.feature;
import java.util.function.Function;
class FeatureGuardForField<T> implements FeatureGuard<T> {
private final Function<T, String> accessor;
private final FeatureGuard<String> delegate;
FeatureGuardForField(Function<T, String> accessor, FeatureGuard<String> delegate) {
this.accessor = accessor;
this.delegate = delegate;
}
@Override
public FeatureGuardResult matches(T value) {
if (value == null) {
return FeatureGuardResult.Undecided;
}
return delegate.matches(accessor.apply(value));
}
}
| 765 |
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/feature/FeatureGuardForMap.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.feature;
import java.util.Map;
import java.util.function.Function;
import com.netflix.titus.common.util.StringExt;
/**
* A matcher that evaluates all key/value pairs from a map against a provided delegate.
*/
class FeatureGuardForMap<T> implements FeatureGuard<T> {
private final Function<T, Map<String, String>> accessor;
private final FeatureGuard<String> delegate;
FeatureGuardForMap(Function<T, Map<String, String>> accessor, FeatureGuard<String> delegate) {
this.accessor = accessor;
this.delegate = delegate;
}
@Override
public FeatureGuardResult matches(T value) {
if (value == null) {
return FeatureGuardResult.Undecided;
}
Map<String, String> attributes = accessor.apply(value);
for (String attributeKey : attributes.keySet()) {
String attributeValue = attributes.get(attributeKey);
String joined = attributeKey + '=' + StringExt.nonNull(attributeValue);
FeatureGuardResult result = delegate.matches(joined);
switch (result) {
case Approved:
case Denied:
return result;
case Undecided:
break;
}
}
return FeatureGuardResult.Undecided;
}
}
| 766 |
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/feature/FeatureGuards.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.feature;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import com.netflix.titus.common.util.feature.FeatureGuard.FeatureGuardResult;
public class FeatureGuards {
private static final FeatureGuard ALWAYS_APPROVED = value -> FeatureGuardResult.Approved;
private static final FeatureGuard ALWAYS_DENIED = value -> FeatureGuardResult.Denied;
private static final FeatureGuard ALWAYS_UNDECIDED = value -> FeatureGuardResult.Undecided;
/**
* If multiple feature guards are give, they are evaluated in order until one returns result {@link FeatureGuardResult#Approved}
* or {@link FeatureGuardResult#Denied}. If all of them return {@link FeatureGuardResult#Undecided}, the result is false.
*/
public static <T> Predicate<T> toPredicate(FeatureGuard<T>... featureGuard) {
if (featureGuard.length == 0) {
return value -> false;
}
if (featureGuard.length == 1) {
return value -> featureGuard[0].matches(value) == FeatureGuardResult.Approved;
}
return value -> {
for (FeatureGuard<T> next : featureGuard) {
FeatureGuardResult result = next.matches(value);
switch (result) {
case Approved:
return true;
case Denied:
return false;
case Undecided:
// Move to the next one
}
}
return false;
};
}
public static FeatureGuardWhiteListBuilder newWhiteList() {
return new FeatureGuardWhiteListBuilder();
}
public static FeatureGuardWhiteListBuilder newWhiteListFromConfiguration(FeatureGuardWhiteListConfiguration configuration) {
return new FeatureGuardWhiteListBuilder()
.withTurnOnPredicate(configuration::isFeatureEnabled)
.withWhiteListRegExpSupplier("whiteList", configuration::getWhiteList)
.withBlackListRegExpSupplier("blackList", configuration::getBlackList);
}
public static <T> FeatureGuard<T> fromField(Function<T, String> accessor, FeatureGuard<String> delegate) {
return new FeatureGuardForField<>(accessor, delegate);
}
/**
* A matcher that evaluates all key/value pairs from a map against a provided delegate.
*/
public static <T> FeatureGuard<T> fromMap(Function<T, Map<String, String>> accessor, FeatureGuard<String> delegate) {
return new FeatureGuardForMap<>(accessor, delegate);
}
public static <T> FeatureGuard<T> alwaysApproved() {
return ALWAYS_APPROVED;
}
public static <T> FeatureGuard<T> alwaysDenied() {
return ALWAYS_DENIED;
}
public static <T> FeatureGuard<T> alwaysUndecided() {
return ALWAYS_UNDECIDED;
}
}
| 767 |
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/feature/FeatureGuardWhiteListBuilder.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.feature;
import java.util.function.Predicate;
import java.util.function.Supplier;
import com.netflix.titus.common.util.RegExpExt;
import com.netflix.titus.common.util.feature.FeatureGuardWithPredicates.PredicateConfig;
import com.netflix.titus.common.util.feature.FeatureGuardWithPredicates.StepRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FeatureGuardWhiteListBuilder {
private static final Logger logger = LoggerFactory.getLogger(FeatureGuardWhiteListBuilder.class);
private Supplier<Boolean> turnOnPredicate;
private int regExpFlags;
private String whiteListRegExpSupplierName;
private Supplier<String> whiteListRegExpSupplier;
private String blackListRegExpSupplierName;
private Supplier<String> blackListRegExpSupplier;
public FeatureGuardWhiteListBuilder withTurnOnPredicate(Supplier<Boolean> turnOnPredicate) {
this.turnOnPredicate = turnOnPredicate;
return this;
}
public FeatureGuardWhiteListBuilder withRegExpFlags(int regExpFlags) {
this.regExpFlags = regExpFlags;
return this;
}
public FeatureGuardWhiteListBuilder withWhiteListRegExpSupplier(String name, Supplier<String> supplier) {
this.whiteListRegExpSupplierName = name;
this.whiteListRegExpSupplier = supplier;
return this;
}
public FeatureGuardWhiteListBuilder withBlackListRegExpSupplier(String name, Supplier<String> supplier) {
this.blackListRegExpSupplierName = name;
this.blackListRegExpSupplier = supplier;
return this;
}
public FeatureGuard<String> build() {
return new FeatureGuardWithPredicates(
new PredicateConfig(StepRule.StopOnFalse, value -> turnOnPredicate.get(), false),
new PredicateConfig(StepRule.StopOnTrue, newRegExpPredicate(whiteListRegExpSupplier, whiteListRegExpSupplierName), false),
new PredicateConfig(StepRule.StopOnTrue, newRegExpPredicate(blackListRegExpSupplier, blackListRegExpSupplierName), true)
);
}
private Predicate<String> newRegExpPredicate(Supplier<String> regExpSupplier, String regExpSupplierName) {
Predicate<String> whiteListPredicate;
if (regExpSupplier == null) {
whiteListPredicate = value -> true;
} else {
whiteListPredicate = value ->
RegExpExt.dynamicMatcher(regExpSupplier, regExpSupplierName, regExpFlags, logger)
.apply(value)
.matches();
}
return whiteListPredicate;
}
}
| 768 |
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/feature/FeatureComplianceTypes.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.feature;
import java.util.Arrays;
import com.netflix.spectator.api.Registry;
public final class FeatureComplianceTypes {
public static <T> FeatureCompliance<T> collectComplianceMetrics(Registry registry, FeatureCompliance<T> delegate) {
return new FeatureComplianceMetricsCollector<>(registry, delegate);
}
public static <T> FeatureCompliance<T> logNonCompliant(FeatureCompliance<T> delegate) {
return new FeatureComplianceLogger<>(delegate);
}
@SafeVarargs
public static <T> FeatureCompliance<T> mergeComplianceValidators(FeatureCompliance<T>... delegates) {
return new FeatureComplianceAggregator<>(Arrays.asList(delegates));
}
}
| 769 |
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/feature/FeatureComplianceAggregator.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.feature;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class FeatureComplianceAggregator<T> implements FeatureCompliance<T> {
private static final Logger logger = LoggerFactory.getLogger(FeatureComplianceAggregator.class);
private final List<FeatureCompliance<T>> delegates;
FeatureComplianceAggregator(List<FeatureCompliance<T>> delegates) {
Preconditions.checkArgument(delegates.size() > 1, "Composite used for less than two delegates");
this.delegates = delegates;
}
@Override
public Optional<NonComplianceList<T>> checkCompliance(T value) {
List<NonComplianceList<T>> combinedResult = new ArrayList<>();
delegates.forEach(d -> {
try {
d.checkCompliance(value).ifPresent(combinedResult::add);
} catch (Exception e) {
logger.warn("[{}] Unexpected error during compliance checking for value: {}", FeatureComplianceAggregator.class.getSimpleName(), value);
combinedResult.add(NonComplianceList.of(
d.getClass().getSimpleName(),
value,
Collections.singletonMap("unexpectedError", e.getMessage()),
String.format("Unexpected error during data validation: errorMessage=%s", e.getMessage())
));
}
});
return combinedResult.isEmpty() ? Optional.empty() : NonComplianceList.merge(combinedResult);
}
}
| 770 |
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/feature/FeatureCompliance.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.feature;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* {@link FeatureCompliance} tracks information about invocations that could not be executed, because of
* some incompatibility with a newly introduced feature. Instances of this class should be used in parallel with
* the {@link FeatureGuard} instances to record information for diagnostic purposes.
*/
public interface FeatureCompliance<T> {
/**
* Checks feature compliance of a given value object.
*
* @return {@link Optional#empty()} if compliant, non-empty if violations found.
*/
Optional<NonComplianceList<T>> checkCompliance(T value);
class NonCompliance<T> {
private final String featureId;
private final T value;
private final Map<String, String> context;
private final String errorMessage;
private NonCompliance(String featureId, T value, Map<String, String> context, String errorMessage) {
this.featureId = featureId;
this.value = value;
this.context = context;
this.errorMessage = errorMessage;
}
public String getFeatureId() {
return featureId;
}
public T getValue() {
return value;
}
public Map<String, String> getContext() {
return context;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NonCompliance<?> that = (NonCompliance<?>) o;
return Objects.equals(featureId, that.featureId) &&
Objects.equals(value, that.value) &&
Objects.equals(context, that.context);
}
@Override
public int hashCode() {
return Objects.hash(featureId, value, context);
}
public String toErrorMessage() {
return errorMessage;
}
@Override
public String toString() {
return "NonCompliance{" +
"featureId='" + featureId + '\'' +
", value=" + value +
", context=" + context +
", errorMessage='" + errorMessage + '\'' +
'}';
}
}
class NonComplianceList<T> {
private final List<NonCompliance<T>> violations;
private NonComplianceList(List<NonCompliance<T>> violations) {
this.violations = violations;
}
public List<NonCompliance<T>> getViolations() {
return violations;
}
public Optional<NonCompliance<T>> findViolation(String featureId) {
return violations.stream().filter(v -> v.getFeatureId().equals(featureId)).findFirst();
}
public static <T> NonComplianceList<T> of(String featureId, T value, Map<String, String> context, String errorMessage) {
return new NonComplianceList<>(Collections.singletonList(new NonCompliance<>(featureId, value, context, errorMessage)));
}
public static <T> Optional<NonComplianceList<T>> merge(List<NonComplianceList<T>> items) {
if (items.isEmpty()) {
return Optional.empty();
}
if (items.size() == 1) {
return Optional.of(items.get(0));
}
List<NonCompliance<T>> violations = items.stream().flatMap(tNonComplianceViolations -> tNonComplianceViolations.getViolations().stream()).collect(Collectors.toList());
return Optional.of(new NonComplianceList<>(violations));
}
}
}
| 771 |
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/feature/FeatureGuard.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.feature;
public interface FeatureGuard<T> {
enum FeatureGuardResult {
Approved,
Denied,
Undecided
}
FeatureGuardResult matches(T value);
}
| 772 |
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/feature/FeatureComplianceDecorator.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.feature;
import java.util.Collections;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class FeatureComplianceDecorator<T> implements FeatureCompliance<T> {
private static final Logger logger = LoggerFactory.getLogger(FeatureComplianceDecorator.class);
private final FeatureCompliance<T> delegate;
protected FeatureComplianceDecorator(FeatureCompliance<T> delegate) {
this.delegate = delegate;
}
@Override
public Optional<NonComplianceList<T>> checkCompliance(T value) {
try {
return delegate.checkCompliance(value).map(nonCompliance -> {
processViolations(value, nonCompliance);
return nonCompliance;
});
} catch (Exception e) {
logger.warn("[{}] Unexpected error during compliance checking for value: {}", delegate.getClass().getSimpleName(), value);
return Optional.of(NonComplianceList.of(
delegate.getClass().getSimpleName(),
value,
Collections.singletonMap("unexpectedError", e.getMessage()),
String.format("Unexpected error during data validation: errorMessage=%s", e.getMessage())
));
}
}
protected abstract void processViolations(T value, NonComplianceList<T> nonCompliance);
}
| 773 |
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/feature/FeatureGuardWithPredicates.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.feature;
import java.util.function.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class FeatureGuardWithPredicates implements FeatureGuard<String> {
private static final Logger logger = LoggerFactory.getLogger(FeatureGuardWithPredicates.class);
private final PredicateConfig[] predicateConfigs;
FeatureGuardWithPredicates(PredicateConfig... predicateConfigs) {
this.predicateConfigs = predicateConfigs;
}
@Override
public FeatureGuardResult matches(String value) {
try {
return matchesString(value);
} catch (Exception e) {
logger.warn("Feature status evaluation failure: value={}, error={}", value, e.getMessage());
logger.debug("Stack trace", e);
return FeatureGuardResult.Denied;
}
}
private FeatureGuardResult matchesString(String value) {
for (PredicateConfig predicateConfig : predicateConfigs) {
boolean result = predicateConfig.getPredicate().test(value);
if (result) {
if (predicateConfig.getStepRule() == StepRule.StopOnTrue) {
return predicateConfig.toResult(true);
}
} else {
if (predicateConfig.getStepRule() == StepRule.StopOnFalse) {
return predicateConfig.toResult(false);
}
}
if (predicateConfig.getStepRule() == StepRule.StopOnAny) {
return predicateConfig.toResult(result);
}
}
return FeatureGuardResult.Undecided;
}
enum StepRule {
StopOnFalse,
StopOnTrue,
StopOnAny,
}
static class PredicateConfig {
private final StepRule stepRule;
private final Predicate<String> predicate;
private final boolean negative;
PredicateConfig(StepRule stepRule, Predicate<String> predicate, boolean negative) {
this.stepRule = stepRule;
this.predicate = predicate;
this.negative = negative;
}
StepRule getStepRule() {
return stepRule;
}
Predicate<String> getPredicate() {
return predicate;
}
FeatureGuardResult toResult(boolean predicateResult) {
boolean result = negative != predicateResult;
return result ? FeatureGuardResult.Approved : FeatureGuardResult.Denied;
}
}
}
| 774 |
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/feature/FeatureComplianceMetricsCollector.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.feature;
import com.netflix.spectator.api.Registry;
class FeatureComplianceMetricsCollector<T> extends FeatureComplianceDecorator<T> {
private static final String VIOLATIONS = "titus.feature.compliance.violations";
private final Registry registry;
FeatureComplianceMetricsCollector(Registry registry, FeatureCompliance<T> delegate) {
super(delegate);
this.registry = registry;
}
@Override
protected void processViolations(T value, NonComplianceList<T> nonCompliance) {
nonCompliance.getViolations().forEach(violation -> registry.counter(VIOLATIONS, "featureId", violation.getFeatureId()).increment());
}
}
| 775 |
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/feature/FeatureRollout.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.feature;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Annotation that defines the strategy for rolling out of a new feature.
*/
@Retention(RUNTIME)
@Target({FIELD, METHOD})
public @interface FeatureRollout {
/**
* Feature unique identifier.
*/
String featureId();
/**
* Rollout deadline date.
*/
String deadline();
/**
* Feature description.
*/
String description();
}
| 776 |
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/feature/FeatureComplianceLogger.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.feature;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class FeatureComplianceLogger<T> extends FeatureComplianceDecorator<T> {
private static final Logger logger = LoggerFactory.getLogger(FeatureComplianceLogger.class);
FeatureComplianceLogger(FeatureCompliance<T> delegate) {
super(delegate);
}
@Override
protected void processViolations(T value, NonComplianceList<T> nonCompliance) {
String featureIds = nonCompliance.getViolations().stream().map(NonCompliance::getFeatureId).collect(Collectors.joining(","));
if (logger.isDebugEnabled()) {
logger.debug("[{}] Non compliant value: value={}, violations={}", featureIds, value, nonCompliance.getViolations());
} else {
logger.info("[{}] Compliance violations={}", featureIds, nonCompliance.getViolations());
}
}
}
| 777 |
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/spectator/AuthorizationMetrics.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.spectator;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
public class AuthorizationMetrics {
private static final String AUTHORIZATION_METRICS_ROOT = "titus.authorization.";
private static final String AUTHORIZATION_RESULT_TAG = "result";
private static final String AUTHORIZATION_RESOURCE_TAG = "resource";
private static final String AUTHORIZATION_DOMAIN_TAG = "domain";
private static final String AUTHORIZATION_ERROR_TAG = "error";
private final Registry registry;
private final Id authorizationId;
public AuthorizationMetrics(String authorizationName, Registry registry) {
this.registry = registry;
authorizationId = registry.createId(AUTHORIZATION_METRICS_ROOT + authorizationName);
}
public void incrementAuthorizationSuccess(String resourceName, String securityDomain) {
registry.counter(authorizationId
.withTag(AUTHORIZATION_RESULT_TAG, "success")
.withTag(AUTHORIZATION_RESOURCE_TAG, resourceName)
.withTag(AUTHORIZATION_DOMAIN_TAG, securityDomain)
).increment();
}
public void incrementAuthorizationError(String resourceName, String securityDomain, String errorReason) {
registry.counter(authorizationId
.withTag(AUTHORIZATION_RESULT_TAG, "failure")
.withTag(AUTHORIZATION_RESOURCE_TAG, resourceName)
.withTag(AUTHORIZATION_DOMAIN_TAG, securityDomain)
.withTag(AUTHORIZATION_ERROR_TAG, errorReason)
).increment();
}
}
| 778 |
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/spectator/MultiDimensionalGauge.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.spectator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import com.netflix.titus.common.util.CollectionsExt;
/**
* See {@link SpectatorExt#multiDimensionalGauge(Id, Collection, Registry)}.
*/
public class MultiDimensionalGauge {
private final Id rootId;
private final int dimension;
private final List<String> discerningTagNames;
private final Registry registry;
/**
* Discerning tag names ordered from 0 to N-1. The number assigned to a tag name is used as an index in the
* data structures in this class to address this tag's value. The order is consistent with the order in
* {@link #discerningTagNames} list.
*/
private final Map<String, Integer> tagNamesOrder;
/**
* Maps ordered list of values identifying each gauge to the gauge itself.
*/
@VisibleForTesting
final ConcurrentMap<List<String>, Gauge> gaugesByTagValues = new ConcurrentHashMap<>();
private final AtomicLong nextRevision = new AtomicLong();
private volatile long lastCommitted = -1;
MultiDimensionalGauge(Id rootId, Collection<String> discerningTagNames, Registry registry) {
Preconditions.checkArgument(discerningTagNames.size() > 0, "At least one discerning tag name expected");
this.rootId = rootId;
this.dimension = discerningTagNames.size();
this.discerningTagNames = new ArrayList<>(discerningTagNames);
this.tagNamesOrder = order(this.discerningTagNames);
this.registry = registry;
}
public Setter beginUpdate() {
return new Setter(nextRevision.getAndIncrement());
}
public void remove() {
synchronized (gaugesByTagValues) {
gaugesByTagValues.forEach((tagValues, gauge) -> gauge.set(0));
gaugesByTagValues.clear();
}
}
private Map<String, Integer> order(List<String> discerningTagNames) {
Map<String, Integer> tagNamesOrder = new HashMap<>();
for (int i = 0; i < discerningTagNames.size(); i++) {
tagNamesOrder.put(discerningTagNames.get(i), i);
}
return tagNamesOrder;
}
public class Setter {
private final long revisionId;
private final Map<List<String>, Double> newValues = new HashMap<>();
private Setter(long revisionId) {
this.revisionId = revisionId;
}
public Setter set(List<String> keyValueList, double value) {
Preconditions.checkArgument(keyValueList.size() == dimension * 2, "Incorrect number of key/value pairs");
List<String> tagValues = new ArrayList<>(dimension);
for (int i = 0; i < dimension; i += 1) {
tagValues.add("");
}
for (int i = 0; i < dimension; i++) {
String tagName = keyValueList.get(i * 2);
Preconditions.checkArgument(tagNamesOrder.containsKey(tagName), "Invalid tag name: %s", tagName);
int idx = tagNamesOrder.get(tagName);
tagValues.set(idx, keyValueList.get(i * 2 + 1));
}
newValues.put(tagValues, value);
return this;
}
public MultiDimensionalGauge commit() {
synchronized (gaugesByTagValues) {
// Silently ignore updates that older than the currently committed state.
if (lastCommitted > revisionId) {
return MultiDimensionalGauge.this;
}
refreshGauges();
lastCommitted = revisionId;
}
return MultiDimensionalGauge.this;
}
private void refreshGauges() {
// Reset no longer observed gauges.
Set<List<String>> toRemove = CollectionsExt.copyAndRemove(gaugesByTagValues.keySet(), newValues.keySet());
toRemove.forEach(tagValues -> gaugesByTagValues.remove(tagValues).set(0));
// Add/update observed gauges.
newValues.forEach((tagValues, gaugeValue) -> gaugesByTagValues.computeIfAbsent(tagValues, this::newGauge).set(gaugeValue));
}
private Gauge newGauge(List<String> tagValues) {
List<Tag> tags = new ArrayList<>(dimension);
for (int i = 0; i < dimension; i++) {
tags.add(new BasicTag(discerningTagNames.get(i), tagValues.get(i)));
}
return registry.gauge(rootId.withTags(tags));
}
}
}
| 779 |
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/spectator/MetricSelector.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.spectator;
import java.util.Optional;
/**
* Provides a metric object associated with the given set of tag values. API inspired by Prometheus API.
*/
public interface MetricSelector<METRIC> {
/**
* Provides a metric object associated with the given set of tag values. The tag value order must match the
* tag name order. If metric object cannot be returned (for example because tagValues length does not match tagNames
* length), returns {@link Optional#empty()}.
*/
Optional<METRIC> withTags(String... tagValues);
}
| 780 |
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/spectator/ContinuousSubscriptionMetrics.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.spectator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.api.patterns.PolledMeter;
import rx.Completable;
import rx.Observable;
import rx.Single;
/**
* This produces a <tt>Transformer</tt> that instruments a {@link Completable}, {@link Single}, or {@link Observable}
* with metrics to determine its latency as well as how long it has been since it last completed. This is useful when it
* gets continuously scheduled but has the following limitations:
* <ul>
* <li>This class only measures the latency based on the first subscription until the first complete.</li>
* <li>The same instance of this transformer must be used in order to keep the complete timestamp history.</li>
* </ul>
*/
public class ContinuousSubscriptionMetrics {
private final Registry registry;
private final Timer latency;
private final AtomicBoolean shouldRemove;
private final AtomicBoolean hasSubscribed;
private final AtomicLong latencyStart;
private final AtomicLong lastCompleteTimestamp;
private final Id timeSinceLastCompleteId;
private CompletableTransformer asCompletable;
ContinuousSubscriptionMetrics(String root, List<Tag> commonTags, Registry registry) {
this.registry = registry;
this.latency = registry.timer(root + ".latency", commonTags);
this.shouldRemove = new AtomicBoolean(false);
this.hasSubscribed = new AtomicBoolean(false);
this.latencyStart = new AtomicLong(0);
this.lastCompleteTimestamp = new AtomicLong(registry.clock().wallTime());
this.timeSinceLastCompleteId = registry.createId(root + ".timeSinceLastComplete", commonTags);
PolledMeter.using(registry)
.withId(timeSinceLastCompleteId)
.monitorValue(this, ContinuousSubscriptionMetrics::getTimeSinceLastComplete);
asCompletable = new CompletableTransformer();
}
public void remove() {
shouldRemove.set(true);
PolledMeter.remove(registry, timeSinceLastCompleteId);
}
public Completable.Transformer asCompletable() {
return asCompletable;
}
public <T> Single.Transformer<T, T> asSingle() {
return new SingleTransformer<T>();
}
public <T> Observable.Transformer<T, T> asObservable() {
return new ObservableTransformer<T>();
}
private void onSubscribe() {
if (!shouldRemove.get() && !hasSubscribed.get()) {
hasSubscribed.set(true);
latencyStart.set(registry.clock().wallTime());
}
}
private void onCompleted() {
if (!shouldRemove.get()) {
final long end = registry.clock().wallTime();
latency.record(end - latencyStart.get(), TimeUnit.MILLISECONDS);
lastCompleteTimestamp.set(registry.clock().wallTime());
hasSubscribed.set(false);
}
}
private long getTimeSinceLastComplete() {
if (shouldRemove.get()) {
return 0;
}
return registry.clock().wallTime() - lastCompleteTimestamp.get();
}
private class CompletableTransformer implements Completable.Transformer {
@Override
public Completable call(Completable completable) {
return completable
.doOnSubscribe(ignored -> onSubscribe())
.doOnCompleted(ContinuousSubscriptionMetrics.this::onCompleted);
}
}
private class SingleTransformer<T> implements Single.Transformer<T, T> {
@Override
public Single<T> call(Single<T> single) {
return single
.doOnSubscribe(ContinuousSubscriptionMetrics.this::onSubscribe)
.doOnError(ignored -> onCompleted())
.doOnSuccess(ignored -> onCompleted());
}
}
private class ObservableTransformer<T> implements Observable.Transformer<T, T> {
@Override
public Observable<T> call(Observable<T> completable) {
return completable
.doOnSubscribe(ContinuousSubscriptionMetrics.this::onSubscribe)
.doOnCompleted(ContinuousSubscriptionMetrics.this::onCompleted);
}
}
}
| 781 |
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/spectator/ActionMetrics.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.spectator;
import java.io.Closeable;
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.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.api.patterns.PolledMeter;
/**
* A collection of metrics for tracking successful and failed action executions.
*/
public class ActionMetrics implements Closeable {
private final String root;
private final Registry registry;
private final Iterable<Tag> commonTags;
private final Counter successCounter;
private final Map<Class<? extends Throwable>, Counter> exceptionCounters = new ConcurrentHashMap<>();
private final Timer latencyTimerOnSuccess;
private final Timer latencyTimerOnError;
private final Id sinceLastExecutionId;
private final AtomicLong lastCompletionRef;
public ActionMetrics(Id rootId, Registry registry) {
this.root = rootId.name();
this.commonTags = rootId.tags();
this.registry = registry;
this.successCounter = registry.counter(registry.createId(root, commonTags).withTag("status", "success"));
this.latencyTimerOnSuccess = registry.timer(registry.createId(root + ".latency", commonTags).withTag("status", "success"));
this.latencyTimerOnError = registry.timer(registry.createId(root + ".latency", commonTags).withTag("status", "failure"));
this.sinceLastExecutionId = registry.createId(root + ".sinceLastCompletion", commonTags);
this.lastCompletionRef = new AtomicLong(registry.clock().wallTime());
PolledMeter.using(registry).withId(sinceLastExecutionId).monitorValue(lastCompletionRef);
}
@Override
public void close() {
PolledMeter.remove(registry, sinceLastExecutionId);
}
public long start() {
return registry.clock().wallTime();
}
public void success() {
successCounter.increment();
lastCompletionRef.set(registry.clock().wallTime());
}
public void finish(long startTime) {
success();
latencyTimerOnSuccess.record(registry.clock().wallTime() - startTime, TimeUnit.MILLISECONDS);
}
public void failure(Throwable error) {
failure(-1, error);
}
public void failure(long startTime, Throwable error) {
lastCompletionRef.set(registry.clock().wallTime());
if (startTime >= 0) {
latencyTimerOnError.record(registry.clock().wallTime() - startTime, TimeUnit.MILLISECONDS);
}
Counter exceptionCounter = exceptionCounters.get(error.getClass());
if (exceptionCounter == null) {
Id errorId = registry.createId(root, commonTags)
.withTag("status", "failure")
.withTag("exception", error.getClass().getSimpleName());
exceptionCounter = registry.counter(errorId);
exceptionCounters.put(error.getClass(), exceptionCounter);
}
exceptionCounter.increment();
}
}
| 782 |
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/spectator/SubscriptionMetrics.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.spectator;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import rx.Observable;
/**
* RxJava subscription metrics.
*/
class SubscriptionMetrics<T> implements Observable.Transformer<T, T> {
private final Registry registry;
private final Id rootId;
private final Counter onNextCounter;
private final AtomicInteger unsubscribed;
private final AtomicLong lastEmitTimestamp;
SubscriptionMetrics(String root, Class<?> aClass, Registry registry) {
this(root, Collections.singletonList(new BasicTag("class", aClass.getSimpleName())), registry);
}
SubscriptionMetrics(String root, List<Tag> commonTags, Registry registry) {
this.rootId = registry.createId(root, commonTags);
this.registry = registry;
this.onNextCounter = registry.counter(root + ".onNext", commonTags);
this.unsubscribed = registry.gauge(rootId.withTag("status", "unsubscribed"), new AtomicInteger());
this.lastEmitTimestamp = new AtomicLong(registry.clock().wallTime());
registry.gauge(
registry.createId(root + ".lastEmit", commonTags),
0L,
this::getTimeSinceLastEmit
);
}
@Override
public Observable<T> call(Observable<T> source) {
return source
.doOnNext(next -> {
onNextCounter.increment();
lastEmitTimestamp.set(registry.clock().wallTime());
})
.doOnError(e -> registry.gauge(rootId.withTags("status", "error", "error", e.getClass().getSimpleName()), 1))
.doOnCompleted(() -> registry.gauge(rootId.withTag("status", "success"), 1))
.doOnUnsubscribe(() -> unsubscribed.set(1));
}
private long getTimeSinceLastEmit(long value) {
return unsubscribed.get() == 0 ? registry.clock().wallTime() - lastEmitTimestamp.get() : 0;
}
}
| 783 |
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/spectator/ValueRangeMetrics.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.spectator;
import java.util.function.Function;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
/**
* Monitors a value, and a collection of buckets, each denoting a value range. If a current value is within a
* particular bucket/range, its gauge is set to 1. All the other buckets are set to 0.
* If a current value is less than zero, all gauge values are set to 0.
*/
public class ValueRangeMetrics<SOURCE> {
public ValueRangeMetrics(Id rootId, long[] levels, SOURCE source, Function<SOURCE, Long> valueSupplier, Registry registry) {
buildValueGauge(rootId, source, valueSupplier, registry);
buildValueLevelGauges(rootId, levels, source, valueSupplier, registry);
}
private void buildValueGauge(Id rootId, SOURCE source, Function<SOURCE, Long> valueSupplier, Registry registry) {
registry.gauge(
registry.createId(rootId.name() + "current", rootId.tags()),
source, sourceArg -> {
long newValue = valueSupplier.apply(sourceArg);
return newValue < 0 ? 0 : newValue;
}
);
}
private void buildValueLevelGauges(Id rootId, long[] levels, SOURCE source, Function<SOURCE, Long> valueSupplier, Registry registry) {
Id levelsId = registry.createId(rootId.name() + "level", rootId.tags());
for (int i = 0; i < levels.length; i++) {
final long previous = i == 0 ? -1 : levels[i - 1];
long level = levels[i];
registry.gauge(levelsId.withTag("level", Long.toString(level)), source, sourceArg -> {
long newValue = valueSupplier.apply(sourceArg);
if (newValue < 0) {
return 0;
}
return newValue > previous && newValue <= level ? 1 : 0;
});
}
final long lastLevel = levels[levels.length - 1];
registry.gauge(levelsId.withTag("level", "unbounded"), source, sourceArg -> {
long newValue = valueSupplier.apply(sourceArg);
if (newValue < 0) {
return 0;
}
return newValue > lastLevel ? 1 : 0;
});
}
public static <SOURCE> ValueRangeMetrics<SOURCE> metricsOf(Id rootId,
long[] levels,
SOURCE source,
Function<SOURCE, Long> valueSupplier,
Registry registry) {
return new ValueRangeMetrics<>(rootId, levels, source, valueSupplier, registry);
}
}
| 784 |
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/spectator/ExecutionMetrics.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.spectator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.titus.common.util.CollectionsExt;
/**
* A collection of metrics for tracking successful and failed action executions.
*/
public class ExecutionMetrics {
private final String root;
private final Registry registry;
private final List<Tag> commonTags;
private final Counter successCounter;
private final Counter errorCounter;
private final Map<Class<? extends Throwable>, Counter> exceptionCounters = new ConcurrentHashMap<>();
private final AtomicLong successLatency = new AtomicLong();
private final AtomicLong failureLatency = new AtomicLong();
public ExecutionMetrics(String root, Class<?> aClass, Registry registry) {
this(root, aClass, registry, new ArrayList<>());
}
public ExecutionMetrics(String root, Class<?> aClass, Registry registry, List<Tag> additionalTags) {
this.root = root;
this.registry = registry;
this.commonTags = CollectionsExt.copyAndAdd(additionalTags, new BasicTag("class", aClass.getSimpleName()));
this.successCounter = registry.counter(registry.createId(root, commonTags).withTag("status", "success"));
this.errorCounter = registry.counter(registry.createId(root, commonTags).withTag("status", "failure"));
Id successLatencyId = registry.createId(root + ".latency", commonTags).withTag("status", "success");
PolledMeter.using(registry).withId(successLatencyId).monitorValue(successLatency);
Id failureLatencyId = registry.createId(root + ".latency", commonTags).withTag("status", "failure");
PolledMeter.using(registry).withId(failureLatencyId).monitorValue(failureLatency);
}
public void success() {
successCounter.increment();
}
public void success(long startTime) {
success();
successLatency.set(registry.clock().wallTime() - startTime);
failureLatency.set(0);
}
public void failure(Throwable error) {
Counter exceptionCounter = exceptionCounters.get(error.getClass());
if (exceptionCounter == null) {
Id errorId = registry.createId(root, commonTags).withTag("exception", error.getClass().getSimpleName());
exceptionCounter = registry.counter(errorId);
exceptionCounters.put(error.getClass(), exceptionCounter);
}
errorCounter.increment();
exceptionCounter.increment();
}
public void failure(Throwable error, long startTime) {
failure(error);
successLatency.set(0);
failureLatency.set(registry.clock().wallTime() - startTime);
}
}
| 785 |
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/spectator/IamConnectorMetrics.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.spectator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
public class IamConnectorMetrics {
public enum IamMethods {
CanAgentAssume,
GetIamRole
}
public static final String METRICS_ROOT = "titus.iam.connector";
private final Registry registry;
private final Map<String, ExecutionMetrics> methodMetricsMap;
private final Class<?> iamConnectorClass;
public IamConnectorMetrics(Class<?> aClass, Registry registry) {
this.registry = registry;
methodMetricsMap = new ConcurrentHashMap<>();
iamConnectorClass = aClass;
for (IamMethods methodName : IamMethods.values()) {
// Create ExecutionMetrics that are preconfigured with the appropriate tags. This
// allows latency metrics to be collected per method.
List<Tag> tags = new ArrayList<>();
String methodNameStr = methodName.name();
tags.add(new BasicTag("method", methodNameStr));
methodMetricsMap.put(methodNameStr,
new ExecutionMetrics(METRICS_ROOT, iamConnectorClass, registry, tags));
}
}
public void success(IamMethods method, long startTime) {
getOrCreateMetrics(method).success(startTime);
}
public void failure(IamMethods method, Throwable error, long startTime) {
getOrCreateMetrics(method).failure(error, startTime);
}
// Creates an execution metric for the methodName if it doesn't exist. Returns the
// metric if it exists already.
private ExecutionMetrics getOrCreateMetrics(IamMethods methodName) {
String methodNameStr = methodName.name();
if (methodMetricsMap.containsKey(methodNameStr)) {
return methodMetricsMap.get(methodNameStr);
}
List<Tag> tags = new ArrayList<>();
tags.add(new BasicTag("methodName", methodNameStr));
ExecutionMetrics metric = new ExecutionMetrics(METRICS_ROOT, iamConnectorClass, registry, tags);
methodMetricsMap.put(methodNameStr, metric);
return metric;
}
}
| 786 |
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/spectator/ValueRangeCounter.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.spectator;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
public class ValueRangeCounter {
private static final String UNBOUNDED = "unbounded";
@VisibleForTesting
final Map<Long, Counter> counters;
private final Counter first;
@VisibleForTesting
final Counter unbounded;
private final long[] levels;
public ValueRangeCounter(Id rootId, long[] levels, Function<Long, String> levelFormatter, Registry registry) {
this.levels = levels;
Map<Long, Counter> counters = new HashMap<>();
for (long level : levels) {
counters.put(level, registry.counter(rootId.withTag("level", levelFormatter.apply(level))));
}
this.counters = counters;
this.first = counters.get(levels[0]);
this.unbounded = registry.counter(rootId.withTag("level", UNBOUNDED));
}
public void recordLevel(long level) {
if (level < levels[0]) {
first.increment();
} else if (level >= levels[levels.length - 1]) {
unbounded.increment();
} else {
counters.get(toConfiguredLevel(level)).increment();
}
}
private long toConfiguredLevel(long level) {
for (long l : levels) {
if (level < l) {
return l;
}
}
return levels[levels.length - 1];
}
public static Function<Long, String> newSortableFormatter(long[] levels) {
if (levels.length <= 1) {
return level -> Long.toString(level);
}
long maxValue = levels[levels.length - 1];
if (maxValue < 1) {
return level -> Long.toString(level);
}
int digitCount = (int) Math.floor(Math.log10(maxValue)) + 1;
return value -> String.format("%0" + digitCount + "d", value);
}
}
| 787 |
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/spectator/DatabaseMetrics.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.spectator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
/**
* This class contains generic methods to publish database-specific metrics.
*/
public class DatabaseMetrics {
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 static final String ROOT_NAME = ".jooq.";
private static final String OPERATION_LATENCY = "latency";
private static final String OPERATION_ERROR = "error";
private static final String STATUS_TAG = "status";
private static final String RECORD_OP_TAG = "operation";
private static final String RECORD_COUNT_TAG = "count";
private static final String RECORD_TABLE_TAG = "table";
private static final String RECORD_ERROR_CLASS = "class";
private final Id operationLatency;
private final Id errorCounter;
private final MetricSelector<ValueRangeCounter> latencyBuckets;
private enum Operations {
INSERT,
SELECT,
SCAN,
DELETE,
}
private final Registry registry;
public DatabaseMetrics(Registry registry, String metricsNamespace, String databaseName) {
List<Tag> commonTags = Collections.emptyList();
this.registry = registry;
String metricsRoot = metricsNamespace + ROOT_NAME;
this.operationLatency = registry.createId(metricsRoot + databaseName + "." + OPERATION_LATENCY, commonTags);
this.errorCounter = registry.createId(metricsRoot + databaseName + "." + OPERATION_ERROR, commonTags);
this.latencyBuckets = SpectatorExt.newValueRangeCounterSortable(
registry.createId(metricsRoot + databaseName + ".latencyBuckets"),
new String[]{RECORD_TABLE_TAG, RECORD_OP_TAG, STATUS_TAG},
LEVELS,
registry
);
}
public void registerInsertLatency(long startTimeMs, int numRecordsInserted, String tableName, List<Tag> additionalTags) {
List<Tag> tags = new ArrayList<>();
tags.add(new BasicTag(RECORD_COUNT_TAG, Integer.toString(numRecordsInserted)));
registerLatency(Operations.INSERT, tableName, Stream.concat(tags.stream(),
additionalTags.stream()).collect(Collectors.toList()),
System.currentTimeMillis() - startTimeMs);
}
public void registerScanLatency(long startTimeMs, String tableName, List<Tag> additionalTags) {
registerLatency(Operations.SCAN, tableName, additionalTags, System.currentTimeMillis() - startTimeMs);
}
public void registerSelectLatency(long startTimeMs, String tableName, List<Tag> additionalTags) {
registerLatency(Operations.SELECT, tableName, additionalTags, System.currentTimeMillis() - startTimeMs);
}
public void registerDeleteLatency(long startTimeMs, int numRecordsDeleted, String tableName, List<Tag> additionalTags) {
List<Tag> tags = new ArrayList<>();
tags.add(new BasicTag(RECORD_COUNT_TAG, Integer.toString(numRecordsDeleted)));
registerLatency(Operations.DELETE, tableName, Stream.concat(tags.stream(),
additionalTags.stream()).collect(Collectors.toList()),
System.currentTimeMillis() - startTimeMs);
}
public void registerInsertError(long startTimeMs, String tableName, Throwable throwable, Iterable<Tag> additionalTags) {
registerError(Operations.INSERT, tableName, throwable, additionalTags, System.currentTimeMillis() - startTimeMs);
}
public void registerInsertError(String tableName, Throwable throwable, Iterable<Tag> additionalTags) {
registerError(Operations.INSERT, tableName, throwable, additionalTags, 0);
}
public void registerSelectError(long startTimeMs, String tableName, Throwable throwable, Iterable<Tag> additionalTags) {
registerError(Operations.SELECT, tableName, throwable, additionalTags, System.currentTimeMillis() - startTimeMs);
}
public void registerSelectError(String tableName, Throwable throwable, Iterable<Tag> additionalTags) {
registerError(Operations.SELECT, tableName, throwable, additionalTags, 0);
}
public void registerDeleteError(long startTimeMs, String tableName, Throwable throwable, Iterable<Tag> additionalTags) {
registerError(Operations.DELETE, tableName, throwable, additionalTags, System.currentTimeMillis() - startTimeMs);
}
public void registerDeleteError(String tableName, Throwable throwable, Iterable<Tag> additionalTags) {
registerError(Operations.DELETE, tableName, throwable, additionalTags, 0);
}
private void registerLatency(Operations op, String tableName, List<Tag> additionalTags, long latencyMs) {
Id delayId = operationLatency
.withTags(RECORD_TABLE_TAG, tableName)
.withTag(RECORD_OP_TAG, op.name())
.withTags(additionalTags);
registry.timer(delayId).record(latencyMs, TimeUnit.MILLISECONDS);
// Tag order: RECORD_TABLE_TAG, RECORD_OP_TAG, STATUS_TAG
latencyBuckets.withTags(tableName, op.name(), "success").ifPresent(m -> m.recordLevel(latencyMs));
}
private void registerError(Operations op, String tableName, Throwable throwable, Iterable<Tag> additionalTags, long latencyMs) {
registry.counter(errorCounter
.withTag(RECORD_OP_TAG, op.name())
.withTag(RECORD_TABLE_TAG, tableName)
.withTags(RECORD_ERROR_CLASS, throwable.getClass().getSimpleName())
.withTags(additionalTags))
.increment();
// Tag order: RECORD_TABLE_TAG, RECORD_OP_TAG, STATUS_TAG
latencyBuckets.withTags(tableName, op.name(), "error").ifPresent(m -> m.recordLevel(latencyMs));
}
}
| 788 |
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/spectator/FsmMetricsImpl.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.spectator;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
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.StringExt;
/**
* Metrics collector for a Finite State Machine (FSM). It reports the current state of an FSM, and the state transitions.
* If the FSM reaches the terminal state, the current state indicators are cleared to prevent infinite accumulation.
* If multiple state transitions happen simultaneously, the result state is undefined. Callers are expected to serialize
* all updates.
*/
class FsmMetricsImpl<S> implements SpectatorExt.FsmMetrics<S> {
private final Function<S, String> nameOf;
private final Function<S, Boolean> finalStateEval;
private final Registry registry;
private final Id baseStateId;
private final Id baseUpdatesId;
private final AtomicReference<StateHolder> currentState;
FsmMetricsImpl(Id rootId,
Function<S, String> nameOf,
Function<S, Boolean> finalStateEval,
S initialState,
Registry registry) {
this.nameOf = nameOf;
this.finalStateEval = finalStateEval;
this.registry = registry;
String effectiveRootName = rootId.name().endsWith(".") ? rootId.name() : rootId.name() + '.';
this.baseStateId = registry.createId(effectiveRootName + "currentState", rootId.tags());
this.baseUpdatesId = registry.createId(effectiveRootName + "updates", rootId.tags());
this.currentState = new AtomicReference<>(new StateHolder(initialState, ""));
}
@Override
public void transition(S nextState) {
transition(nextState, "");
}
@Override
public void transition(S nextState, String reason) {
boolean isCurrentFinal = finalStateEval.apply(currentState.get().state);
if (isCurrentFinal || currentState.get().state == nextState) {
return;
}
currentState.getAndSet(new StateHolder(nextState, reason)).leaveState();
}
enum StateHolderLifecycle {Active, Inactive, Removable}
private class StateHolder {
private final Registry registry;
private final S state;
private final Id currentStateId;
private volatile StateHolderLifecycle lifecycle;
private StateHolder(S state, String reason) {
String stateName = nameOf.apply(state);
this.state = state;
this.lifecycle = StateHolderLifecycle.Active;
this.registry = FsmMetricsImpl.this.registry;
Id currentUpdateId = baseUpdatesId.withTag("state", stateName);
if (StringExt.isNotEmpty(reason)) {
currentUpdateId = currentUpdateId.withTag("reason", reason);
}
registry.counter(currentUpdateId).increment();
this.currentStateId = baseStateId.withTag("state", stateName);
if (!finalStateEval.apply(state)) {
PolledMeter.using(registry).withId(this.currentStateId).monitorValue(this,
// Be sure to access all fields via 'self' object in this method
self -> {
switch (self.lifecycle) {
case Active:
return 1;
case Inactive:
self.lifecycle = StateHolderLifecycle.Removable;
return 0;
}
// Removable
PolledMeter.remove(self.registry, self.currentStateId);
return 0;
}
);
}
}
private void leaveState() {
this.lifecycle = StateHolderLifecycle.Inactive;
}
}
}
| 789 |
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/spectator/DynamicTagProcessor.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.spectator;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import com.netflix.spectator.api.Id;
class DynamicTagProcessor<METRIC> implements MetricSelector<METRIC> {
private final Id rootId;
private final String[] tagNames;
private final Function<Id, METRIC> metricFactory;
private final ConcurrentMap<Tags, METRIC> metrics = new ConcurrentHashMap<>();
DynamicTagProcessor(Id rootId,
String[] tagNames,
Function<Id, METRIC> metricFactory) {
this.rootId = rootId;
this.tagNames = tagNames;
this.metricFactory = metricFactory;
}
@Override
public Optional<METRIC> withTags(String... tagValues) {
if (tagValues.length != tagNames.length) {
return Optional.empty();
}
Tags tags = new Tags(tagNames, tagValues);
METRIC metric = metrics.get(tags);
if (metric != null) {
return Optional.of(metric);
}
metric = metrics.computeIfAbsent(tags, t -> {
Id id = buildIdOf(tagValues);
return metricFactory.apply(id);
});
return Optional.of(metric);
}
private Id buildIdOf(String[] tagValues) {
Id id = rootId;
for (int i = 0; i < tagValues.length; i++) {
id = id.withTag(tagNames[i], tagValues[i]);
}
return id;
}
private static class Tags {
private final Map<String, String> tagMap;
private Tags(String[] tagNames, String[] tagValues) {
Map<String, String> tagMap = new HashMap<>();
for (int i = 0; i < tagNames.length; i++) {
tagMap.put(tagNames[i], tagValues[i]);
}
this.tagMap = tagMap;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Tags tags = (Tags) o;
return Objects.equals(tagMap, tags.tagMap);
}
@Override
public int hashCode() {
return Objects.hash(tagMap);
}
}
}
| 790 |
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/spectator/SpectatorExt.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.spectator;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Predicate;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import rx.Observable;
/**
* Collection of generic higher level metrics built on top of Spectator.
*/
public final class SpectatorExt {
public static final int MAX_TAG_VALUE_LENGTH = 120;
private static final int UUID_LENGTH = UUID.randomUUID().toString().length();
public interface FsmMetrics<S> {
void transition(S nextState);
void transition(S nextState, String reason);
}
private SpectatorExt() {
}
/**
* Spectator tag value size is limited to {@link #MAX_TAG_VALUE_LENGTH}. Tags with values larger than this are
* dropped from metrics. This function trims long values to fit into the Spectator constraints.
*/
public static String trimTagValue(String value) {
if (value == null || value.isEmpty() || value.length() <= MAX_TAG_VALUE_LENGTH) {
return value;
}
return value.substring(0, MAX_TAG_VALUE_LENGTH);
}
/**
* Return a unique tag value with the provided base (value prefix), and a collision predicate.
* The returned value is guaranteed to be unique and within the Spectator tag value limits.
*/
public static String uniqueTagValue(String base, Predicate<String> collisionCheck) {
String trimmed = trimTagValue(base);
if (!collisionCheck.test(trimmed)) {
return trimmed;
}
String trimmedBase = (trimmed.length() + 1 + UUID_LENGTH) <= MAX_TAG_VALUE_LENGTH
? trimmed + '#'
: trimmed.substring(0, MAX_TAG_VALUE_LENGTH - UUID_LENGTH - 1) + '#';
String value;
do {
value = trimmedBase + UUID.randomUUID();
} while (collisionCheck.test(value));
return value;
}
/**
* Metric collector for a Finite State Machine (FSM). It reports a current state of an FSM, and the state transitions.
* If FSM reaches the terminal state, the current state indicators are cleared, to prevent infinite accumulation.
*/
public static <E extends Enum<E>> FsmMetrics<E> fsmMetrics(Id rootId,
Function<E, Boolean> finalStateEval,
E initialState,
Registry registry) {
return new FsmMetricsImpl<>(rootId, Enum::name, finalStateEval, initialState, registry);
}
/**
* Monitors a value, and a collection of buckets, each denoting a value range. If a current value is within a
* particular bucket/range, its gauge is set to 1. All the other buckets are set to 0.
* If a current value is less than zero, all gauge values are set to 0.
*/
public static <SOURCE> ValueRangeMetrics<SOURCE> valueRangeMetrics(Id rootId,
long[] levels,
SOURCE source,
Function<SOURCE, Long> valueSupplier,
Registry registry) {
return ValueRangeMetrics.metricsOf(rootId, levels, source, valueSupplier, registry);
}
/**
* Collection of counters for value ranges.
*/
public static ValueRangeCounter newValueRangeCounter(Id rootId, long[] levels, Registry registry) {
return new ValueRangeCounter(rootId, levels, level -> Long.toString(level), registry);
}
/**
* Collection of counters for value ranges. The 'level' tag values aligned and prefixed by 0 so text sorting is possible.
*/
public static ValueRangeCounter newValueRangeCounterSortable(Id rootId, long[] levels, Registry registry) {
return new ValueRangeCounter(rootId, levels, ValueRangeCounter.newSortableFormatter(levels), registry);
}
/**
* Collection of counters for value ranges with a dynamic set of tag names.
*/
public static MetricSelector<ValueRangeCounter> newValueRangeCounter(Id rootId, String[] tagNames, long[] levels, Registry registry) {
return new DynamicTagProcessor<>(
rootId,
tagNames,
id -> new ValueRangeCounter(id, levels, level -> Long.toString(level), registry)
);
}
/**
* Collection of counters for value ranges with a dynamic set of tag names.
* The 'level' tag values aligned and prefixed by 0 so text sorting is possible.
*/
public static MetricSelector<ValueRangeCounter> newValueRangeCounterSortable(Id rootId, String[] tagNames, long[] levels, Registry registry) {
return new DynamicTagProcessor<>(
rootId,
tagNames,
id -> new ValueRangeCounter(id, levels, ValueRangeCounter.newSortableFormatter(levels), registry)
);
}
/**
* Creates a composite gauge consisting of a set of basic gauges each with a unique set of discerning tags.
*/
public static MultiDimensionalGauge multiDimensionalGauge(Id rootId, Collection<String> discerningTagNames, Registry registry) {
return new MultiDimensionalGauge(rootId, discerningTagNames, registry);
}
/**
* RxJava subscription metrics.
*/
public static <T> Observable.Transformer<T, T> subscriptionMetrics(String rootName, List<Tag> commonTags, Registry registry) {
return new SubscriptionMetrics<>(rootName, commonTags, registry);
}
/**
* RxJava subscription metrics.
*/
public static <T> Observable.Transformer<T, T> subscriptionMetrics(String rootName, Class<?> type, Registry registry) {
return new SubscriptionMetrics<>(rootName, type, registry);
}
/**
* RxJava subscription metrics.
*/
public static <T> Observable.Transformer<T, T> subscriptionMetrics(String rootName, Registry registry) {
return new SubscriptionMetrics<>(rootName, Collections.emptyList(), registry);
}
/**
* RxJava metrics transformer for {@link Observable observables}, {@link rx.Completable completables}, or
* {@link rx.Single singles} that are continuously scheduled.
*/
public static ContinuousSubscriptionMetrics continuousSubscriptionMetrics(String rootName, List<Tag> tags, Registry registry) {
return new ContinuousSubscriptionMetrics(rootName, tags, registry);
}
/**
* Collection of metrics for tracking a status of an action run periodically.
*/
public static ActionMetrics actionMetrics(String rootName, List<Tag> tags, Registry registry) {
return new ActionMetrics(registry.createId(rootName, tags), registry);
}
/**
* Collection of metrics for tracking a status of an action run periodically.
*/
public static ActionMetrics actionMetrics(Id rootId, Registry registry) {
return new ActionMetrics(rootId, registry);
}
}
| 791 |
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/collections/ConcurrentHashMultimap.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.collections;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.netflix.titus.common.util.CollectionsExt;
/**
* A concurrent (thread safe) Map that allows multiple unique values per key, with pluggable logic for determining
* uniqueness and resolving conflicts.
* <p>
* Multiple values per key are kept as a <tt>HashMap</tt>, and determining uniqueness for each key is defined by a
* pluggable <tt>Function</tt> that extracts unique identifiers for each value. Conflicts on a key are resolved by a
* pluggable <tt>ConflictResolver</tt> as well.
* <p>
* This is inspired by Guava's HashMultiMap, and can be seen as a concurrent (thread safe) and lock-free implementation
* of it. Writes use optimistic concurrency control and may be retried until succeeded. Reads are done without any
* locking and return a point in time snapshot for each key. Modifications in each key are atomic and implemented with
* copy-on-write of the current value.
*
* @param <K> type of keys. They must have a correct implementations of <tt>equals()</tt> and <tt>hashCode()</tt>
* @param <V> type of values. Operations on values will use <tt>equals()</tt>, so it is hightly recommended it is properly implemented
*/
@ParametersAreNonnullByDefault
public class ConcurrentHashMultimap<K, V> implements Multimap<K, V> {
private final ConcurrentMap<K, Map<Object, V>> entries = new ConcurrentHashMap<>();
private final ValueIdentityExtractor<V> valueIdentityExtractor;
private final ConflictResolver<V> defaultConflictResolver;
public ConcurrentHashMultimap(ValueIdentityExtractor<V> valueIdentityExtractor, ConflictResolver<V> conflictResolver) {
this.valueIdentityExtractor = valueIdentityExtractor;
this.defaultConflictResolver = conflictResolver;
}
/**
* Atomically adds a value for a key. Conflict resolution happens through a ConflictResolver if another existing
* value with the same identity already exists.
*
* @param key must have a reasonable implementation of equals() and hashCode()
* @param value to be added, that can be uniquely identified by a ValueIdentityExtractor
* @return true if the Map was updated, false if the existing value was kept, as per conflict resolution (ConflictResolver).
*/
@Override
public boolean put(@Nullable K key, @Nullable V value) {
Preconditions.checkNotNull(key);
Preconditions.checkNotNull(value);
return putWithConflictResolution(key, value, defaultConflictResolver);
}
private boolean putWithConflictResolution(K key, V newValue, ConflictResolver<V> conflictResolver) {
// this can be updated multiple times by the compute call below. The last write wins. Never rely on its default value.
final AtomicBoolean modified = new AtomicBoolean(false);
final Object id = valueIdentityExtractor.apply(newValue);
entries.compute(key, (ignored, values) -> {
if (values == null) {
values = new HashMap<>();
}
if (!values.containsKey(id)) {
modified.set(true);
return CollectionsExt.copyAndAdd(values, id, newValue);
}
// conflict detected
if (conflictResolver.shouldReplace(values.get(id), newValue)) {
modified.set(true);
return CollectionsExt.copyAndAdd(values, id, newValue);
}
modified.set(false);
return values;
});
return modified.get();
}
/**
* Atomically removes a value from a key, based on its unique identity (provided by <tt>ValueIdentityExtractor</tt>).
*
* @param key must be of a type compatible with the type defined for the <tt>MultiMap</tt>
* @param value must be of a value comaptible with the type defined for the <tt>MultiMap</tt>
* @return if the <tt>MultiMap</tt> changed
* @throws ClassCastException if the key or value Objects are not appropriate for this <tt>MultiMap</tt>.
*/
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
K keyTyped = (K) key;
V valueTyped = (V) value;
return key != null && value != null && removeIf(keyTyped, valueTyped, v -> true);
}
/**
* Atomically removes a value from a key, based on its unique identity (provided by <tt>ValueIdentityExtractor</tt>).
* In cases where this <tt>Map</tt> is being updated with different items for the same identity, the third <tt>Predicate</tt>
* param can be used to determine if the current value associated with the unique identity is the one to be removed.
* <p>
* This allows atomic updates in a <tt>compareAndDelete</tt> style to avoid race conditions.
*
* @param key containing the value to be removed
* @param value to be removed from the key
* @return true if the <tt>MultiMap</tt> changed
*/
public boolean removeIf(K key, V value, Predicate<V> match) {
// this can be updated multiple times by the compute call below. The last write wins. Never rely on its default value.
final AtomicBoolean modified = new AtomicBoolean(false);
final Object id = valueIdentityExtractor.apply(value);
entries.compute(key, (ignored, values) -> {
if (values == null) {
modified.set(false);
return null;
}
if (!values.containsKey(id)) {
modified.set(false);
return values;
}
V currentValue = values.get(id);
if (!match.test(currentValue)) {
modified.set(false);
return values;
}
modified.set(true);
Map<Object, V> newValues = CollectionsExt.copyAndRemove(values, id);
if (newValues.isEmpty()) {
return null;
}
return newValues;
});
return modified.get();
}
/**
* This is thread safe, but not atomic. It is equivalent to calling <tt>put</tt> for each value.
*
* @return if the <tt>MultiMap</tt> was modified
*/
@Override
public boolean putAll(@Nullable K key, Iterable<? extends V> values) {
Preconditions.checkNotNull(key);
return StreamSupport.stream(values.spliterator(), false)
.map(value -> put(key, value))
.reduce(false, (acc, modified) -> acc || modified);
}
/**
* This is thread safe, but not atomic. It is equivalent to calling <tt>putAll</tt> for each key in the provided
* <tt>MultiMap</tt>.
*
* @param values to be added
* @return if the <tt>MultiMap</tt> was modified
*/
@Override
public boolean putAll(Multimap<? extends K, ? extends V> values) {
return values.asMap().entrySet().stream()
.map(entry -> putAll(entry.getKey(), entry.getValue()))
.reduce(false, (acc, modified) -> acc || modified);
}
/**
* Replace values (based on their identity provided by <tt>ValueIdentityExtractor</tt>) ignoring the conflict
* resolution logic. This can be used to force replace some items associated with a key.
* <p>
* The entire operation is not atomic, and is almost equivalent to multiple calls to <tt>put()</tt>. The returned
* <tt>Collection</tt> must be ignored, since it will not contain which items were replaced.
* <p>
* TODO: track replaced items
*
* @return this breaks the contract of the MultiMap interface and does not return the modified items
*/
@Override
public Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
Preconditions.checkNotNull(key);
values.forEach(v -> putWithConflictResolution(key, v, (e, n) -> true));
return ImmutableList.of();
}
/**
* Atomically removes all values associated with a key.
*
* @param key must be compatible with the type defined for this MultiMap
* @return the removed values
* @throws ClassCastException if the key is not compatible with this <tt>MultiMap</tt>
*/
@Override
public Collection<V> removeAll(@Nullable Object key) {
if (key == null) {
return Collections.emptyList();
}
return Collections.unmodifiableCollection(entries.remove(key).values());
}
/**
* Atomically removes all entries from the Map
*/
@Override
public void clear() {
entries.clear();
}
@Override
public Collection<V> get(@Nullable K key) {
if (key == null) {
return ImmutableList.of();
}
final Map<Object, V> entries = this.entries.get(key);
if (entries == null) {
return null;
}
return entries.values();
}
@Override
public Set<K> keySet() {
return entries.keySet();
}
/**
* Copies contents into an immutable <tt>Multiset</tt> view.
*
* @return a copied view of all keys, with counts for each one of them
*/
@Override
public Multiset<K> keys() {
final ImmutableMultiset.Builder<K> builder = ImmutableMultiset.builder();
entries.forEach((key, values) -> builder.setCount(key, values.size()));
return builder.build();
}
/**
* Return a view of all values. Multiple values with the same identity (as provided by <tt>ValueIdentityExtractor</tt>
* may be present if they are associated with multiple keys.
*
* @return a copied view of all values, modifications will not be reflected back
*/
@Override
public Collection<V> values() {
return entryStream().map(Map.Entry::getValue).collect(Collectors.toList());
}
/**
* Copy and transform into a <tt>Collection</tt> of entries. Note that for a <tt>MultiMap</tt>, the same key can
* appear multiple times in the returned collection.
*
* @return a copy of this <tt>MultiMap</tt>, modifications will not be reflected back on this
*/
@Override
public Collection<Map.Entry<K, V>> entries() {
return entryStream().collect(Collectors.toList());
}
/**
* This scans all items and is O(N).
*
* @return the total number of values in the
*/
@Override
public int size() {
return (int) entryStream().count();
}
private Stream<Map.Entry<K, V>> entryStream() {
return entries.entrySet().stream()
.flatMap(entry -> entry.getValue().values().stream()
.map(value -> SimpleEntry.of(entry.getKey(), value)));
}
@Override
public boolean isEmpty() {
return entries.isEmpty();
}
@Override
public boolean containsKey(@Nullable Object key) {
return key != null && entries.containsKey(key);
}
/**
* Scans each key for a given value, based on its unique identity (provided by <tt>ValueIdentityExtractor</tt>)
*
* @param value must be compatible with this <tt>MultiMap</tt>
* @return true if the value is found in at least one key
* @throws ClassCastException when the value is not compatible
*/
@Override
public boolean containsValue(@Nullable Object value) {
if (value == null) {
return false;
}
final Object id = valueIdentityExtractor.apply((V) value);
return entries.entrySet().stream().map(Map.Entry::getValue).anyMatch(values -> values.containsKey(id));
}
/**
* @param key must be compatible
* @param value must be compatible
* @return true if the key contains a value based on its unique identity (provided by <tt>ValueIdentityProvider</tt>)
* @throws ClassCastException when the provided key or value are not compatible
*/
@Override
public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
final Object id = valueIdentityExtractor.apply((V) value);
return entries.get(key).containsKey(id);
}
/**
* The returned <tt>Map</tt> has the same concurrency semantics as <tt>java.util.concurrent.ConcurrentMap</tt>,
* in particular iterators on the returned view will operate on a point in time snapshot and may or may not see
* concurrent modifications.
*
* @return a read only (i.e.: <tt>Collections.unmodifiableMap()</tt>) view of the MultiMap as a <tt>java.util.Map</tt>.
* Values for each key are also read only and changes on them will not be reflected in the source MultiMap.
*/
@Override
public Map<K, Collection<V>> asMap() {
// this assumes the entries Map can not contain null values, which should be true for ConcurrentMap implementations
return Maps.transformValues(entries, Map::values);
}
/**
* <tt>java.util.function.Function</tt> with logic for extracting unique identifiers for each value. Uniqueness is
* defined by <tt>equals()</tt> and <tt>hashCode()</tt> of the returned identifier <tt>Object</tt>.
* <p>
* Returned identifiers are heavily encouraged to be immutable, since they will be used as keys in a <tt>Map</tt>,
* and modifications will not be reflected in Collections they are being held in.
*/
public interface ValueIdentityExtractor<V> extends Function<V, Object> {
}
/**
* Logic for conflict resolution when a new value would replace an existing one with the same identity.
* Implementations must return true if the existing value must be replaced.
*
* @param <V> type of items that will conflict. Implementations will receive the old,new
*/
public interface ConflictResolver<V> extends BiFunction<V, V, Boolean> {
/**
* @param existing value to be replaced
* @param replacement potential new value
* @return true if the existing value should be replaced
*/
boolean shouldReplace(V existing, V replacement);
@Override
default Boolean apply(V existing, V replacement) {
return shouldReplace(existing, replacement);
}
}
}
| 792 |
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/collections/OneItemIterator.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;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class OneItemIterator<T> implements Iterator<T> {
private final T item;
private boolean returned;
public OneItemIterator(T item) {
this.item = item;
}
@Override
public boolean hasNext() {
return !returned;
}
@Override
public T next() {
if (returned) {
throw new NoSuchElementException("no more items to return");
}
returned = true;
return item;
}
}
| 793 |
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/collections/TwoItemIterator.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;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class TwoItemIterator<T> implements Iterator<T> {
private final T item1;
private final T item2;
private boolean returned1;
private boolean returned2;
public TwoItemIterator(T item1, T item2) {
this.item1 = item1;
this.item2 = item2;
}
@Override
public boolean hasNext() {
return !returned2;
}
@Override
public T next() {
if (returned2) {
throw new NoSuchElementException("no more items to return");
}
if (returned1) {
returned2 = true;
return item2;
}
returned1 = true;
return item1;
}
}
| 794 |
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/collections/SimpleEntry.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.collections;
import java.util.Map;
public final class SimpleEntry<K, V> implements Map.Entry<K, V> {
private final K key;
private V value;
private SimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
public static <K, V> Map.Entry<K, V> of(K key, V value) {
return new SimpleEntry<>(key, value);
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
V old = this.value;
this.value = value;
return old;
}
/**
* @param o an instance of <tt>Map.Entry</tt>
* @return true when keys and values of both <tt>Map.Entry</tt> match
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || !(o instanceof Map.Entry)) {
return false;
}
Map.Entry<?, ?> that = (Map.Entry<?, ?>) o;
return (key != null ? key.equals(that.getKey()) : that.getKey() == null)
&& (value != null ? value.equals(that.getValue()) : that.getValue() == null);
}
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
}
| 795 |
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/Order.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.List;
/**
* Ordered list of values. The ordering is set by a pair of an arbitrary index key and the primary key.
* {@link Order} object is immutable. Changes to an order produce new copies of it.
*/
public interface Order<VALUE> {
/**
* @return immutable ordered set of values.
*/
List<VALUE> orderedList();
}
| 796 |
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/Indexes.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.io.Closeable;
import java.util.HashMap;
import java.util.Map;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
public final class Indexes {
private Indexes() {
}
public static <PRIMARY_KEY, INPUT> Builder<PRIMARY_KEY, INPUT> newBuilder() {
return new Builder<>();
}
public static <PRIMARY_KEY, INPUT> IndexSet<PRIMARY_KEY, INPUT> empty() {
return new Builder<PRIMARY_KEY, INPUT>().build();
}
public static Closeable monitor(Id id, IndexSetHolder<?, ?> indexSetHolder, Registry registry) {
return new IndexSetMetrics(id, indexSetHolder, registry);
}
public static class Builder<PRIMARY_KEY, INPUT> {
private final Map<String, DefaultGroup<?, PRIMARY_KEY, INPUT, ?>> groups = new HashMap<>();
private final Map<String, DefaultIndex<?, PRIMARY_KEY, INPUT, ?>> indexes = new HashMap<>();
private final Map<String, DefaultOrder<?, PRIMARY_KEY, INPUT, ?>> orders = new HashMap<>();
public <INDEX_KEY, OUTPUT> Builder<PRIMARY_KEY, INPUT> withGroup(String groupId,
IndexSpec<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> indexSpec) {
groups.put(groupId, DefaultGroup.newEmpty(indexSpec));
return this;
}
public <INDEX_KEY, OUTPUT> Builder<PRIMARY_KEY, INPUT> withIndex(String indexId,
IndexSpec<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> indexSpec) {
indexes.put(indexId, DefaultIndex.newEmpty(indexSpec));
return this;
}
public <INDEX_KEY, OUTPUT> Builder<PRIMARY_KEY, INPUT> withOrder(String orderId,
IndexSpec<INDEX_KEY, PRIMARY_KEY, INPUT, OUTPUT> indexSpec) {
orders.put(orderId, DefaultOrder.newEmpty(indexSpec));
return this;
}
public IndexSet<PRIMARY_KEY, INPUT> build() {
return new DefaultIndexSet<>(groups, indexes, orders);
}
}
}
| 797 |
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/Index.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.Map;
/**
* A map from some unique index key to a value. A given input value may be split into several values with unique ids
* within the index. This is the opposite of {@link Group} which aggregates input values by some key.
* For example, a JobWithTasks input value could be mapped to collection of tasks, with the UNIQUE_INDEX_KEY being the task id.
*/
public interface Index<UNIQUE_INDEX_KEY, VALUE> {
Map<UNIQUE_INDEX_KEY, VALUE> get();
}
| 798 |
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/IndexSetHolderBasic.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;
/**
* Basic, not thread safe implementation of {@link IndexSetHolder}.
*/
public class IndexSetHolderBasic<PRIMARY_KEY, INPUT> implements IndexSetHolder<PRIMARY_KEY, INPUT> {
private volatile IndexSet<PRIMARY_KEY, INPUT> indexSet;
public IndexSetHolderBasic(IndexSet<PRIMARY_KEY, INPUT> indexSet) {
this.indexSet = indexSet;
}
@Override
public IndexSet<PRIMARY_KEY, INPUT> getIndexSet() {
return indexSet;
}
@Override
public void add(Collection<INPUT> values) {
this.indexSet = indexSet.add(values);
}
@Override
public void remove(Collection<PRIMARY_KEY> values) {
this.indexSet = indexSet.remove(values);
}
}
| 799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.